text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Support hash params for origin and app guid | var Client = require('client'),
Utils = require('utils'),
ZAFClient = {};
/// ### ZAFClient API
///
/// When you include the ZAF SDK on your website, you get access to the `ZAFClient` object.
///
/// #### ZAFClient.init([callback(context)])
///
/// Returns a [`client`](#client-object) object.
///
/// ##### Arguments
///
/// * `callback(context)` (optional) a function called as soon as communication with
/// the Zendesk app is established. The callback receives a context object with
/// data related to the Zendesk app, including `currentAccount`, `currentUser`, and `location`
///
/// Example:
///
/// ```javascript
/// var client = ZAFClient.init(function(context) {
/// var currentUser = context.currentUser;
/// console.log('Hi ' + currentUser.name);
/// });
/// ```
ZAFClient.init = function(callback) {
var queryParams = Utils.queryParameters(),
hashParams = Utils.queryParameters(( document.location.hash || '' ).slice(1)),
origin = queryParams.origin || hashParams.origin,
app_guid = queryParams.app_guid || hashParams.app_guid,
client;
if (!origin || !app_guid) { return false; }
client = new Client({ origin: origin, appGuid: app_guid });
if (typeof callback === 'function') {
client.on('app.registered', callback.bind(client));
}
return client;
};
module.exports = ZAFClient;
| var Client = require('client'),
Utils = require('utils'),
ZAFClient = {};
/// ### ZAFClient API
///
/// When you include the ZAF SDK on your website, you get access to the `ZAFClient` object.
///
/// #### ZAFClient.init([callback(context)])
///
/// Returns a [`client`](#client-object) object.
///
/// ##### Arguments
///
/// * `callback(context)` (optional) a function called as soon as communication with
/// the Zendesk app is established. The callback receives a context object with
/// data related to the Zendesk app, including `currentAccount`, `currentUser`, and `location`
///
/// Example:
///
/// ```javascript
/// var client = ZAFClient.init(function(context) {
/// var currentUser = context.currentUser;
/// console.log('Hi ' + currentUser.name);
/// });
/// ```
ZAFClient.init = function(callback) {
var params = Utils.queryParameters(),
client;
if (!params.origin || !params.app_guid) { return false; }
client = new Client({ origin: params.origin, appGuid: params.app_guid });
if (typeof callback === 'function') {
client.on('app.registered', callback.bind(client));
}
return client;
};
module.exports = ZAFClient;
|
Rename of the author field to content_type in the model, in order to
avoid confusion | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Authors(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return self.content_object.name
class Announcements(models.Model):
title = models.CharField(max_length = 500)
pubdate = models.DateTimeField()
creator = models.ForeignKey(Authors)
unique = models.CharField(max_length = 255, unique = True)
url = models.URLField()
summary = models.TextField(null = True)
enclosure = models.CharField("Attachment URL", max_length = 255, null = True)
def __unicode__(self):
return self.title
| # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Authors(models.Model):
author = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('author', 'object_id')
def __unicode__(self):
return self.content_object.name
class Announcements(models.Model):
title = models.CharField(max_length = 500)
pubdate = models.DateTimeField()
creator = models.ForeignKey(Authors)
unique = models.CharField(max_length = 255, unique = True)
url = models.URLField()
summary = models.TextField(null = True)
enclosure = models.CharField("Attachment URL", max_length = 255, null = True)
def __unicode__(self):
return self.title
|
Remove posix from npm-shrinkwrap on webapp | Package.describe({
name: 'meteor-base',
version: '1.5.1',
// Brief, one-line summary of the package.
summary: 'Packages that every Meteor app needs',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.imply([
// Super basic stuff about where your code is running and async utilities
'meteor',
// This package enables making client-server connections; currently Meteor
// only supports building client/server web applications so this is not
// removable
'webapp',
// The protocol and client/server libraries that Meteor uses to send data
'ddp',
// This package uses the user agent of each incoming HTTP request to
// decide whether to inject <script> tags into the <head> of the
// response document to polyfill ECMAScript 5 support.
'es5-shim',
// Push code changes to the client and automatically reload the page
'hot-code-push'
]);
});
| Package.describe({
name: 'meteor-base',
version: '1.5.0',
// Brief, one-line summary of the package.
summary: 'Packages that every Meteor app needs',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.imply([
// Super basic stuff about where your code is running and async utilities
'meteor',
// This package enables making client-server connections; currently Meteor
// only supports building client/server web applications so this is not
// removable
'webapp',
// The protocol and client/server libraries that Meteor uses to send data
'ddp',
// This package uses the user agent of each incoming HTTP request to
// decide whether to inject <script> tags into the <head> of the
// response document to polyfill ECMAScript 5 support.
'es5-shim',
// Push code changes to the client and automatically reload the page
'hot-code-push'
]);
});
|
Add additional view for sitemap.xml | from flask import render_template, current_app, flash, redirect, url_for, send_from_directory
from . import main
from forms import ContactForm
from ..email import send_email
@main.route('/<path:filename>')
def static_from_root(filename):
return send_from_directory(current_app.static_folder, filename)
@main.route('/')
def index():
return render_template('index.html')
@main.route('/about')
def about():
return render_template('about.html')
@main.route('/menu')
def menu():
return render_template('menu.html')
@main.route('/hours-and-directions')
def hours():
return render_template('hours-and-directions.html')
@main.route('/contact', methods=['GET', 'POST'])
def contact():
contact_form = ContactForm()
if contact_form.validate_on_submit():
name = contact_form.name.data
email = contact_form.email.data
phone = contact_form.phone.data
message = contact_form.message.data
send_email(current_app.config['MAIL_USERNAME'], 'Robata Grill Inquiry',
'mail/message', name=name, email=email, phone=phone, message=message)
flash('Your message has been sent. We will be in contact with you shortly.')
return redirect(url_for('main.contact'))
return render_template('contact.html', contact_form = contact_form)
@main.route('/imageScroll')
def imageScroll():
return render_template('imageScroll.html')
| from flask import render_template, current_app, flash, redirect, url_for
from . import main
from forms import ContactForm
from ..email import send_email
@main.route('/')
def index():
return render_template('index.html')
@main.route('/about')
def about():
return render_template('about.html')
@main.route('/menu')
def menu():
return render_template('menu.html')
@main.route('/hours-and-directions')
def hours():
return render_template('hours-and-directions.html')
@main.route('/contact', methods=['GET', 'POST'])
def contact():
contact_form = ContactForm()
if contact_form.validate_on_submit():
name = contact_form.name.data
email = contact_form.email.data
phone = contact_form.phone.data
message = contact_form.message.data
send_email(current_app.config['MAIL_USERNAME'], 'Robata Grill Inquiry',
'mail/message', name=name, email=email, phone=phone, message=message)
flash('Your message has been sent. We will be in contact with you shortly.')
return redirect(url_for('main.contact'))
return render_template('contact.html', contact_form = contact_form)
@main.route('/imageScroll')
def imageScroll():
return render_template('imageScroll.html')
|
Add docstring to select command. | """
flashcards.commands.sets
~~~~~~~~~~~~~~~~~~~
Contains the commands and subcommands related to the sets resource.
"""
import os
import click
from flashcards import sets
from flashcards import storage
@click.group('sets')
def sets_group():
"""Command related to the StudySet object """
pass
@click.command('new')
@click.option('--title', prompt='Title of the study set')
@click.option('--desc', prompt='Description for the study set (optional)')
def new(title, desc):
"""
Create a new study set.
User supplies a title and a description.
If this study set does not exist, it is created.
"""
study_set = sets.StudySet(title, desc)
filepath = storage.create_studyset_file(study_set)
# automatically select this studyset
storage.link_selected_studyset(filepath)
click.echo('Study set created !')
@click.command('select')
@click.argument('studyset')
def select(studyset):
"""
Select a studyset.
Focus on a studyset, every new added cards are going to be put directly in
this studyset.
"""
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
click.echo('Selected studyset: %s' % studyset_obj.title)
click.echo('Next created cards will be automatically added '
'to this studyset.')
sets_group.add_command(new)
sets_group.add_command(select)
| """
flashcards.commands.sets
~~~~~~~~~~~~~~~~~~~
Contains the commands and subcommands related to the sets resource.
"""
import os
import click
from flashcards import sets
from flashcards import storage
@click.group('sets')
def sets_group():
"""Command related to the StudySet object """
pass
@click.command('new')
@click.option('--title', prompt='Title of the study set')
@click.option('--desc', prompt='Description for the study set (optional)')
def new(title, desc):
"""
Create a new study set.
User supplies a title and a description.
If this study set does not exist, it is created.
"""
study_set = sets.StudySet(title, desc)
filepath = storage.create_studyset_file(study_set)
# automatically select this studyset
storage.link_selected_studyset(filepath)
click.echo('Study set created !')
@click.command('select')
@click.argument('studyset')
def select(studyset):
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
click.echo('Selected studyset: %s' % studyset_obj.title)
click.echo('Next created cards will be automatically added '
'to this studyset.')
sets_group.add_command(new)
sets_group.add_command(select)
|
Add MANIFEST.in to keep tox happy | from setuptools import setup
from kafka_info import __version__
setup(
name="kafka-info",
version=__version__,
author="Federico Giraud",
author_email="fgiraud@yelp.com",
description="Shows kafka cluster information and metrics",
packages=[
"kafka_info",
"kafka_info.utils",
"kafka_info.commands",
"kafka_reassignment",
"kafka_consumer_manager",
"kafka_consumer_manager.commands"],
data_files=[
("bash_completion.d",
["bash_completion.d/kafka-info"]),
],
scripts=[
"kafka-info",
"kafka-reassignment",
"kafka-consumer-manager"],
install_requires=[
"argparse",
"argcomplete",
"kazoo",
"PyYAML",
"yelp-kafka",
],
)
| from setuptools import setup
from kafka_info import __version__
setup(
name="kafka-info",
version=__version__,
author="Federico Giraud",
author_email="fgiraud@yelp.com",
description="Shows kafka cluster information and metrics",
packages=[
"kafka_info",
"kafka_info.utils",
"kafka_info.commands",
"kafka_reassignment",
"kafka_consumer_manager",
"kafka_consumer_manager.commands"],
data_files=[
("bash_completion.d",
["kafka-info"],
["kafka-reassignment"])],
scripts=[
"kafka-info",
"kafka-reassignment",
"kafka-consumer-manager"],
install_requires=[
"argparse",
"argcomplete",
"kazoo",
"PyYAML",
"yelp-kafka",
],
)
|
Update dependencies and fix missing comma | from setuptools import setup
from Cython.Build import cythonize
import numpy as np
setup(
name='ism',
version='0.1',
description="Implementation of Image Source Method.",
#long_description=open('README').read(),
author='Frederik Rietdijk',
author_email='fridh@fridh.nl',
license='LICENSE',
packages=['ism'],
scripts=[],
zip_safe=False,
install_requires=[
'geometry',
'numpy',
'matplotlib',
'cython',
'cytoolz'
],
include_dirs = [np.get_include()],
ext_modules = cythonize('ism/*.pyx'),
)
| from setuptools import setup
from Cython.Build import cythonize
import numpy as np
setup(
name='ism',
version='0.1',
description="Implementation of Image Source Method.",
#long_description=open('README').read(),
author='Frederik Rietdijk',
author_email='fridh@fridh.nl',
license='LICENSE',
packages=['ism'],
scripts=[],
zip_safe=False,
install_requires=[
'geometry',
'numpy',
'matplotlib'
'cython',
],
include_dirs = [np.get_include()],
ext_modules = cythonize('ism/*.pyx'),
)
|
Update the alltests.java in tests.engine | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. 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
*
* Contributors: Actuate Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.birt.report.tests.engine;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.birt.report.tests.engine.api.AllApiTests;
import org.eclipse.birt.report.tests.engine.regression.AllRegressionTests;
import org.eclipse.birt.report.tests.engine.smoke.AllSmokeTests;
public class AllTests
{
public static Test suite( )
{
TestSuite test = new TestSuite( );
test.addTest( AllRegressionTests.suite( ) );
// test.addTest( AllCompatibilityTests.suite( ) );
test.addTest( AllSmokeTests.suite( ) );
test.addTest( AllApiTests.suite( ) );
return test;
}
} | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. 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
*
* Contributors: Actuate Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.birt.report.tests.engine;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.birt.report.tests.engine.api.AllApiTests;
import org.eclipse.birt.report.tests.engine.regression.AllRegressionTests;
import org.eclipse.birt.report.tests.engine.smoke.AllSmokeTests;
public class AllTests
{
public static Test suite( )
{
TestSuite test = new TestSuite( );
// test.addTest( AllRegressionTests.suite( ) );
// test.addTest( AllCompatibilityTests.suite( ) );
test.addTest( AllSmokeTests.suite( ) );
// test.addTest( AllApiTests.suite( ) );
return test;
}
} |
[TACHYON-1559] Add additional test for randomness property | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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 tachyon.client;
import org.junit.Test;
import org.junit.Assert;
/**
* Tests {@link ClientUtils}.
*/
public final class ClientUtilsTest {
/**
* Tests if output of {@link ClientUtils#getRandomNonNegativeLong()} is non-negative.
* Also tests for randomness property.
*
*/
@Test
public void getRandomNonNegativeLongTest() throws Exception {
Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() != ClientUtils.getRandomNonNegativeLong());
}
} | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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 tachyon.client;
import org.junit.Test;
import org.junit.Assert;
/**
* Tests {@link ClientUtils}.
*/
public final class ClientUtilsTest {
/**
* Tests if output of {@link ClientUtils#getRandomNonNegativeLong()} is non-negative.
*/
@Test
public void getRandomNonNegativeLongTest() throws Exception {
Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
}
}
|
Test translations now uses instance.language. | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.test.utils import override_settings
from ..registry import LinguistRegistry as Registry
from . import settings
from .translations import (
FooModel,
FooTranslation
)
LANGUAGES = [l[0] for l in settings.LANGUAGES]
@override_settings(DEBUG=True)
class TranslationTest(TestCase):
"""
Tests the Linguist's Translation class.
"""
def setUp(self):
self.registry = Registry()
self.registry.register(FooTranslation)
self.instance = FooModel()
def test_fields(self):
for language in LANGUAGES:
self.assertIn('title_%s' % language, dir(FooModel))
def test_getter_setter(self):
with self.assertNumQueries(3):
# save = 1 query
self.instance.save()
# get / create "en" translation = 2 queries
self.instance.title = 'Hello'
self.assertEqual(self.instance.title_en, 'Hello')
self.assertIsNone(self.instance.title_fr)
self.instance.language = 'fr'
self.instance.title = 'Bonjour'
self.assertEqual(self.instance.title_en, 'Hello')
self.assertEqual(self.instance.title_fr, 'Bonjour')
| # -*- coding: utf-8 -*-
from django.test import TestCase
from django.test.utils import override_settings
from ..registry import LinguistRegistry as Registry
from . import settings
from .translations import (
FooModel,
FooTranslation
)
LANGUAGES = [l[0] for l in settings.LANGUAGES]
@override_settings(DEBUG=True)
class TranslationTest(TestCase):
"""
Tests the Linguist's Translation class.
"""
def setUp(self):
self.registry = Registry()
self.registry.register(FooTranslation)
self.instance = FooModel()
def test_fields(self):
for language in LANGUAGES:
self.assertIn('title_%s' % language, dir(FooModel))
def test_getter_setter(self):
with self.assertNumQueries(3):
# save = 1 query
self.instance.save()
# get / create "en" translation = 2 queries
self.instance.title = 'Hello'
self.assertEqual(self.instance.title_en, 'Hello')
self.assertIsNone(self.instance.title_fr)
self.instance.set_current_language('fr')
self.instance.title = 'Bonjour'
self.assertEqual(self.instance.title_en, 'Hello')
self.assertEqual(self.instance.title_fr, 'Bonjour')
|
Fix expression vs statement mistake in JS AST | var helpersFor = require("../helpers-for");
var fileWrapper = require("../file-wrapper");
var ast = require("../ast");
var es = require("../es");
function makeExportsFor(transform, exportVars) {
return exportVars.map(function(v) {
var varName = es.Literal(null, v.data);
var varRef = transform(v);
var jsExports = es.Identifier(null, "exports");
var exportRef =
es.MemberExpression(v.loc, true, jsExports, varName);
var setExportRef =
es.AssignmentExpression(null, "=", exportRef, varRef);
return es.ExpressionStatement(null, setExportRef);
});
}
function Module(transform, node) {
var retUndef = ast.ExprStmt(null, ast.Undefined(null));
var block = ast.Block(null, node.statements, retUndef);
var blockJs = transform(block);
var predef = helpersFor(blockJs);
var theExports = makeExportsFor(transform, node.exports);
// BEGIN HACK: Add the exports into the block
var theBody = blockJs.callee.body.body;
theBody.pop();
theExports.forEach(function(exp) {
theBody.push(exp);
});
// END HACK
var body = predef.concat([es.ExpressionStatement(null, blockJs)]);
return fileWrapper(body);
}
module.exports = Module;
| var helpersFor = require("../helpers-for");
var fileWrapper = require("../file-wrapper");
var ast = require("../ast");
var es = require("../es");
function makeExportsFor(transform, exportVars) {
return exportVars.map(function(v) {
var varName = es.Literal(null, v.data);
var varRef = transform(v);
var jsExports = es.Identifier(null, "exports");
var exportRef =
es.MemberExpression(v.loc, true, jsExports, varName);
var setExportRef =
es.AssignmentExpression(null, "=", exportRef, varRef);
return es.ExpressionStatement(null, setExportRef);
});
}
function Module(transform, node) {
var retUndef = ast.ExprStmt(null, ast.Undefined(null));
var block = ast.Block(null, node.statements, retUndef);
var blockJs = transform(block);
var predef = helpersFor(blockJs);
var theExports = makeExportsFor(transform, node.exports);
// BEGIN HACK: Add the exports into the black
var theBody = blockJs.callee.body.body;
theBody.pop();
theExports.forEach(function(exp) {
theBody.push(exp);
});
// END HACK
var body = predef.concat([blockJs]);
return fileWrapper(body);
}
module.exports = Module;
|
Add unused param:language flag for OpenMinTeD purposes | #!/usr/bin/env python
import argparse
import pubrunner
import pubrunner.command_line
import os
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Main access point for OpenMinTeD Docker component')
parser.add_argument('--input',required=True,type=str,help='Input directory')
parser.add_argument('--output',required=True,type=str,help='Output directory')
parser.add_argument('--param:language',required=False,type=str,help='Ignored language parameter')
args = parser.parse_args()
assert os.path.isdir(args.input)
assert os.path.isdir(args.output)
inputFormat = 'uimaxmi'
githubRepo = 'https://github.com/jakelever/Ab3P'
sys.argv = ['pubrunner']
sys.argv += ['--defaultsettings']
sys.argv += ['--forceresource_dir', args.input]
sys.argv += ['--forceresource_format', inputFormat]
sys.argv += ['--outputdir', args.output]
sys.argv += [githubRepo]
pubrunner.command_line.main()
| #!/usr/bin/env python
import argparse
import pubrunner
import pubrunner.command_line
import os
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Main access point for OpenMinTeD Docker component')
parser.add_argument('--input',required=True,type=str,help='Input directory')
parser.add_argument('--output',required=True,type=str,help='Output directory')
args = parser.parse_args()
assert os.path.isdir(args.input)
assert os.path.isdir(args.output)
inputFormat = 'uimaxmi'
githubRepo = 'https://github.com/jakelever/Ab3P'
sys.argv = ['pubrunner']
sys.argv += ['--defaultsettings']
sys.argv += ['--forceresource_dir', args.input]
sys.argv += ['--forceresource_format', inputFormat]
sys.argv += ['--outputdir', args.output]
sys.argv += [githubRepo]
pubrunner.command_line.main()
|
Use port 465 for SES SMTP transport
Fixes #34064 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Mailer\Bridge\Amazon\Transport;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/**
* @author Kevin Verschaeve
*/
class SesSmtpTransport extends EsmtpTransport
{
/**
* @param string $region Amazon SES region (currently one of us-east-1, us-west-2, or eu-west-1)
*/
public function __construct(string $username, string $password, string $region = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
parent::__construct(sprintf('email-smtp.%s.amazonaws.com', $region ?: 'eu-west-1'), 465, true, $dispatcher, $logger);
$this->setUsername($username);
$this->setPassword($password);
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Mailer\Bridge\Amazon\Transport;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/**
* @author Kevin Verschaeve
*/
class SesSmtpTransport extends EsmtpTransport
{
/**
* @param string $region Amazon SES region (currently one of us-east-1, us-west-2, or eu-west-1)
*/
public function __construct(string $username, string $password, string $region = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
parent::__construct(sprintf('email-smtp.%s.amazonaws.com', $region ?: 'eu-west-1'), 587, true, $dispatcher, $logger);
$this->setUsername($username);
$this->setPassword($password);
}
}
|
Use 'isinstance' in preference to 'type' method | from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to render the author property as a list
# containing a single item under some circumstances.
# In those cases, the SchemaOrg class will fail due to the unexpected
# type, and this method is called as a fallback.
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and isinstance(author, list) and len(author) == 1:
return author[0].get("name")
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.yields()
def image(self):
return self.schema.image()
def ingredients(self):
return self.schema.ingredients()
def instructions(self):
return self.schema.instructions()
def ratings(self):
return self.schema.ratings()
| from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to render the author property as a list
# containing a single item under some circumstances.
# In those cases, the SchemaOrg class will fail due to the unexpected
# type, and this method is called as a fallback.
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and type(author) == list and len(author) == 1:
return author[0].get("name")
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.yields()
def image(self):
return self.schema.image()
def ingredients(self):
return self.schema.ingredients()
def instructions(self):
return self.schema.instructions()
def ratings(self):
return self.schema.ratings()
|
Fix handling of empty results | (function() {
angular.module('appControllers')
.controller('UradovnyController', ['$scope', 'AppService', function($scope, AppService) {
this.update = function() {
AppService.getData($scope, 'uj', 'uradovny', {'resource': $scope.resource})
.then(function(data) {
$scope.uradovny = data["@graph"][0].hasPOS;
});
};
$scope.isEmpty = function() {
return !angular.isDefined($scope.uradovny) || $scope.uradovny.length == 0;
};
AppService.init($scope, ['resource'], this.update);
}]);
})(); | (function() {
angular.module('appControllers')
.controller('UradovnyController', ['$scope', 'AppService', function($scope, AppService) {
this.update = function() {
AppService.getData($scope, 'uj', 'uradovny', {'resource': $scope.resource})
.then(function(data) {
$scope.uradovny = data["@graph"][0].hasPOS;
});
};
$scope.isEmpty = function() {
return $scope.uradovny.length == 0;
};
AppService.init($scope, ['resource'], this.update);
}]);
})(); |
:fire: Remove unnecessary method overrides from AboutStatusBar | /** @babel */
/** @jsx etch.dom */
import {CompositeDisposable} from 'atom'
import etch from 'etch'
import EtchComponent from './etch-component'
class AboutStatusBar extends EtchComponent {
constructor () {
super()
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.<br/><br/>Click the squirrel icon for more information.'}))
}
handleClick () {
atom.workspace.open('atom://about')
}
render () {
return (
<span type='button' className='about-release-notes icon icon-squirrel inline-block' onclick={this.handleClick.bind(this)} />
)
}
destroy () {
super()
this.subscriptions.dispose()
}
}
export default AboutStatusBar
| /** @babel */
/** @jsx etch.dom */
import {CompositeDisposable} from 'atom'
import etch from 'etch'
import EtchComponent from './etch-component'
class AboutStatusBar extends EtchComponent {
constructor () {
super()
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.<br/><br/>Click the squirrel icon for more information.'}))
}
handleClick () {
atom.workspace.open('atom://about')
}
update () {
etch.update(this)
}
render () {
return (
<span type='button' className='about-release-notes icon icon-squirrel inline-block' onclick={this.handleClick.bind(this)} />
)
}
destroy () {
this.subscriptions.dispose()
}
}
export default AboutStatusBar
|
Check for Laravel 4 before calling $this->package() | <?php namespace Manavo\BootstrapForms;
use Illuminate\Html\HtmlServiceProvider as IlluminateHtmlServiceProvider;
class BootstrapFormsServiceProvider extends IlluminateHtmlServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
if (version_compare($app::VERSION, '5.0') < 0) {
$this->package('manavo/bootstrap-forms');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function registerFormBuilder()
{
$this->app->bindShared('form', function ($app) {
$form = new FormBuilder($app['html'], $app['url'],
$app['session.store']->getToken());
return $form->setSessionStore($app['session.store']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
| <?php namespace Manavo\BootstrapForms;
use Illuminate\Html\HtmlServiceProvider as IlluminateHtmlServiceProvider;
class BootstrapFormsServiceProvider extends IlluminateHtmlServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('manavo/bootstrap-forms');
}
/**
* Register the service provider.
*
* @return void
*/
public function registerFormBuilder()
{
$this->app->bindShared('form', function ($app) {
$form = new FormBuilder($app['html'], $app['url'],
$app['session.store']->getToken());
return $form->setSessionStore($app['session.store']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
|
Clean up CLI a bit
Default arguments are useful. | # -*- coding: utf-8 -*-
"""
Copyright [2009-2020] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import click
from rnacentral_pipeline.rnacentral.genes import build, write
@click.group("genes")
def cli():
"""
A group of commands dealing with building genes.
"""
pass
@cli.command("build")
@click.option(
"--format",
default="csv",
type=click.Choice(write.Format.names(), case_sensitive=False),
)
@click.argument("data_file", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def build_genes(data_file, output, format=None):
"""
Build the genes for the given data file. The file can contain all data for a
specific assembly.
"""
data = build.from_json(data_file)
write.write(data, write.Format.from_name(format), output)
| # -*- coding: utf-8 -*-
"""
Copyright [2009-2020] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import click
from rnacentral_pipeline.rnacentral.genes import build, write
@click.group("genes")
def cli():
"""
A group of commands dealing with building genes.
"""
pass
@cli.command("build")
@click.option("--format", type=click.Choice(write.Format.names(), case_sensitive=False))
@click.argument("data_file", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def build_genes(data_file, output, format=None):
"""
Build the genes for the given data file. This assumes that the file is
already split into reasonable chunks.
"""
data = build.from_json(data_file)
write.write(data, write.Format.from_name(format), output)
|
Add exists method to data point repository. | /*
* Copyright 2014 Open mHealth
*
* 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.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of data points.
*
* @see org.springframework.data.repository.CrudRepository
* @author Emerson Farrugia
*/
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {
boolean exists(String id);
Optional<DataPoint> findOne(String id);
DataPoint save(DataPoint dataPoint);
Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);
void delete(String id);
}
| /*
* Copyright 2014 Open mHealth
*
* 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.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of data points.
*
* @see org.springframework.data.repository.CrudRepository
* @author Emerson Farrugia
*/
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {
Optional<DataPoint> findOne(String id);
Iterable<DataPoint> findAll();
DataPoint save(DataPoint dataPoint);
Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);
Long delete(String id);
}
|
Fix weather changing to soon after Rain/Drought ceremony | package totemic_commons.pokefenn.ceremony;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import totemic_commons.pokefenn.api.ceremony.Ceremony;
import totemic_commons.pokefenn.api.music.MusicInstrument;
/**
* Created by Pokefenn.
* Licensed under MIT (If this is one of my Mods)
*/
public class CeremonyRain extends Ceremony
{
public final boolean doRain;
public CeremonyRain(boolean doRain, String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments)
{
super(name, musicNeeded, maxStartupTime, instruments);
this.doRain = doRain;
}
@Override
public void effect(World world, BlockPos pos)
{
if(!world.isRemote && world.isRaining() != doRain)
{
world.getWorldInfo().setRaining(doRain);
world.getWorldInfo().setRainTime(0);
}
}
}
| package totemic_commons.pokefenn.ceremony;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import totemic_commons.pokefenn.api.ceremony.Ceremony;
import totemic_commons.pokefenn.api.music.MusicInstrument;
/**
* Created by Pokefenn.
* Licensed under MIT (If this is one of my Mods)
*/
public class CeremonyRain extends Ceremony
{
public final boolean doRain;
public CeremonyRain(boolean doRain, String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments)
{
super(name, musicNeeded, maxStartupTime, instruments);
this.doRain = doRain;
}
@Override
public void effect(World world, BlockPos pos)
{
if(!world.isRemote && world.isRaining() != doRain)
{
world.getWorldInfo().setRaining(doRain);
}
}
}
|
Add CORS header to function | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import boto3
table_name = os.environ.get("TABLE_NAME")
table = boto3.resource("dynamodb").Table(table_name)
def _log_dynamo(response):
print "HTTPStatusCode:{}, RetryAttempts:{}, ScannedCount:{}, Count:{}".format(
response.get("ResponseMetadata").get("HTTPStatusCode"),
response.get("ResponseMetadata").get("RetryAttempts"),
response.get("ScannedCount"),
response.get("Count")
)
def get_items(event, context):
response = table.scan(Limit=10)
_log_dynamo(response)
return {
"statusCode": 200,
"body": json.dumps(response["Items"], indent=1),
"headers": {"Access-Control-Allow-Origin": "*"}
}
def get_item(event, context):
response = table.get_item(Key={"id": event.get("pathParameters").get("id")})
_log_dynamo(response)
return {
"statusCode": 200,
"body": json.dumps(response["Item"], indent=1)
}
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import boto3
table_name = os.environ.get("TABLE_NAME")
table = boto3.resource("dynamodb").Table(table_name)
def _log_dynamo(response):
print "HTTPStatusCode:{}, RetryAttempts:{}, ScannedCount:{}, Count:{}".format(
response.get("ResponseMetadata").get("HTTPStatusCode"),
response.get("ResponseMetadata").get("RetryAttempts"),
response.get("ScannedCount"),
response.get("Count")
)
def get_items(event, context):
response = table.scan(Limit=10)
_log_dynamo(response)
return {
"statusCode": 200,
"body": json.dumps(response["Items"], indent=1)
}
def get_item(event, context):
response = table.get_item(Key={"id": event.get("pathParameters").get("id")})
_log_dynamo(response)
return {
"statusCode": 200,
"body": json.dumps(response["Item"], indent=1)
}
|
Fix eager loading of orgterm. | <?php
namespace Kula\HEd\Bundle\SchedulingBundle\Controller;
use Kula\Core\Bundle\FrameworkBundle\Controller\Controller;
class CoreRoomsController extends Controller {
public function indexAction() {
$this->authorize();
$this->processForm();
$this->setRecordType('Core.Organization.School.Term', null,
array('Core.Organization.Term' =>
array('Core.Organization.Term.OrganizationID' => $this->focus->getSchoolIDs(),
'Core.Organization.Term.TermID' => $this->focus->getTermID()
)
)
);
$rooms = array();
if ($this->record->getSelectedRecordID()) {
// Get Rooms
$rooms = $this->db()->db_select('STUD_ROOM')
->fields('STUD_ROOM')
->condition('ORGANIZATION_TERM_ID', $this->record->getSelectedRecordID())
->orderBy('ROOM_NUMBER', 'ASC')
->execute()->fetchAll();
}
return $this->render('KulaHEdSchedulingBundle:CoreRooms:index.html.twig', array('rooms' => $rooms));
}
public function chooserAction() {
$this->authorize();
$data = $this->chooser('HEd.Room')->createChooserMenu($this->request->query->get('q'));
return $this->JSONResponse($data);
}
} | <?php
namespace Kula\HEd\Bundle\SchedulingBundle\Controller;
use Kula\Core\Bundle\FrameworkBundle\Controller\Controller;
class CoreRoomsController extends Controller {
public function indexAction() {
$this->authorize();
$this->processForm();
$this->setRecordType('Core.Organization.School.Term', null,
array('CORE_ORGANIZATION_TERMS' =>
array('ORGANIZATION_ID' => $this->focus->getSchoolIDs(),
'TERM_ID' => $this->focus->getTermID()
)
)
);
$rooms = array();
if ($this->record->getSelectedRecordID()) {
// Get Rooms
$rooms = $this->db()->db_select('STUD_ROOM')
->fields('STUD_ROOM')
->condition('ORGANIZATION_TERM_ID', $this->record->getSelectedRecordID())
->orderBy('ROOM_NUMBER', 'ASC')
->execute()->fetchAll();
}
return $this->render('KulaHEdSchedulingBundle:CoreRooms:index.html.twig', array('rooms' => $rooms));
}
public function chooserAction() {
$this->authorize();
$data = $this->chooser('HEd.Room')->createChooserMenu($this->request->query->get('q'));
return $this->JSONResponse($data);
}
} |
Make a first attempt to identify the build issue | import {
Future,
isFuture,
reject,
of,
never,
isNever
} from './core';
import * as dispatchers from './dispatchers/index.js';
import {after} from './after';
import {both} from './both';
import {cache} from './cache';
import {chainRec} from './chain-rec';
import {encase, encase2, encase3, attempt} from './encase';
import {first} from './race';
import {fromPromise, fromPromise2, fromPromise3} from './from-promise';
import {go} from './go';
import {hook} from './hook';
import {node} from './node';
import {parallel} from './parallel';
import {rejectAfter} from './reject-after';
import {error} from './internal/throw';
if(typeof Object.create !== 'function') error('Please polyfill Object.create to use Fluture');
if(typeof Object.assign !== 'function') error('Please polyfill Object.assign to use Fluture');
export default Object.assign(Future, dispatchers, {
Future,
isFuture,
reject,
of,
never,
isNever,
after,
both,
cache,
first,
fromPromise,
fromPromise2,
fromPromise3,
hook,
node,
parallel,
rejectAfter,
chainRec,
encase,
encase2,
encase3,
attempt,
go,
try: attempt,
do: go
});
| import {
Future,
isFuture,
reject,
of,
never,
isNever
} from './core';
import * as dispatchers from './dispatchers/index';
import {after} from './after';
import {both} from './both';
import {cache} from './cache';
import {chainRec} from './chain-rec';
import {encase, encase2, encase3, attempt} from './encase';
import {first} from './race';
import {fromPromise, fromPromise2, fromPromise3} from './from-promise';
import {go} from './go';
import {hook} from './hook';
import {node} from './node';
import {parallel} from './parallel';
import {rejectAfter} from './reject-after';
import {error} from './internal/throw';
if(typeof Object.create !== 'function') error('Please polyfill Object.create to use Fluture');
if(typeof Object.assign !== 'function') error('Please polyfill Object.assign to use Fluture');
export default Object.assign(Future, dispatchers, {
Future,
isFuture,
reject,
of,
never,
isNever,
after,
both,
cache,
first,
fromPromise,
fromPromise2,
fromPromise3,
hook,
node,
parallel,
rejectAfter,
chainRec,
encase,
encase2,
encase3,
attempt,
go,
try: attempt,
do: go
});
|
Revert "Added support for custom redirect URL when sending verification email…" | <?php
namespace Auth0\SDK\API\Management;
use Auth0\SDK\API\Helpers\ApiClient;
use Auth0\SDK\API\Header\ContentType;
class Jobs extends GenericResource
{
public function get($id)
{
return $this->apiClient->get()
->jobs($id)
->call();
}
public function getErrors($id)
{
return $this->apiClient->get()
->jobs($id)
->errors()
->call();
}
public function importUsers($file_path, $connection_id)
{
return $this->apiClient->post()
->jobs()
->addPath('users-imports')
->addFile('users', $file_path)
->addFormParam('connection_id', $connection_id)
->call();
}
public function sendVerificationEmail($user_id)
{
return $this->apiClient->post()
->jobs()
->addPath('verification-email')
->withHeader(new ContentType('application/json'))
->withBody(json_encode([
'user_id' => $user_id
]))
->call();
}
} | <?php
namespace Auth0\SDK\API\Management;
use Auth0\SDK\API\Helpers\ApiClient;
use Auth0\SDK\API\Header\ContentType;
class Jobs extends GenericResource
{
public function get($id)
{
return $this->apiClient->get()
->jobs($id)
->call();
}
public function getErrors($id)
{
return $this->apiClient->get()
->jobs($id)
->errors()
->call();
}
public function importUsers($file_path, $connection_id)
{
return $this->apiClient->post()
->jobs()
->addPath('users-imports')
->addFile('users', $file_path)
->addFormParam('connection_id', $connection_id)
->call();
}
public function sendVerificationEmail($user_id, $result_url = null)
{
$body = [
'user_id' => $user_id
];
if(!is_null($result_url)){
$body['result_url'] = $result_url;
}
return $this->apiClient->post()
->jobs()
->addPath('verification-email')
->withHeader(new ContentType('application/json'))
->withBody(json_encode($body))
->call();
}
}
|
Remove public to pass signature test
git-svn-id: 60e751271f50ec028ae56d425821c1c711e0b018@905897 13f79535-47bb-0310-9956-ffa450edef68 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 javax.el;
class ELUtils {
private static volatile ExpressionFactory cachedExpressionFactory;
private static boolean cachedExpressionFactoryEnabled = Boolean.valueOf(System.getProperty("org.apache.geronimo.spec.el.useCachedExpressionFactory", "true"));
public static ExpressionFactory getCachedExpressionFactory() {
return cachedExpressionFactory;
}
public static boolean isCachedExpressionFactoryEnabled() {
return cachedExpressionFactoryEnabled;
}
public static void setCachedExpressionFactory(ExpressionFactory expressionFactory) {
cachedExpressionFactory = expressionFactory;
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 javax.el;
public class ELUtils {
private static volatile ExpressionFactory cachedExpressionFactory;
private static volatile boolean cachedExpressionFactoryEnabled = Boolean.valueOf(System.getProperty("org.apache.geronimo.spec.el.useCachedExpressionFactory", "true"));
public static ExpressionFactory getCachedExpressionFactory() {
return cachedExpressionFactory;
}
public static boolean isCachedExpressionFactoryEnabled() {
return cachedExpressionFactoryEnabled;
}
public static void setCachedExpressionFactory(ExpressionFactory expressionFactory) {
cachedExpressionFactory = expressionFactory;
}
}
|
Allow cleanup to be a promise. | #!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var chalk = require('chalk');
var rimraf = require('rimraf');
var helpers = require('broccoli-kitchen-sink-helpers');
var Watcher = require('broccoli/lib/watcher');
var broccoli = require('broccoli');
function createWatcher(destDir, interval) {
var tree = broccoli.loadBrocfile();
var builder = new broccoli.Builder(tree);
var watcher = new Watcher(builder, {interval: interval || 100});
var atExit = function() {
builder.cleanup()
.then(function() {
process.exit(1);
});
};
process.on('SIGINT', atExit);
process.on('SIGTERM', atExit);
watcher.on('change', function(results) {
rimraf.sync(destDir);
helpers.copyRecursivelySync(results.directory, destDir);
console.log(chalk.green("Build successful - " + Math.floor(results.totalTime / 1e6) + 'ms'));
});
watcher.on('error', function(err) {
console.log(chalk.red('\n\nBuild failed.\n'));
});
return watcher;
}
createWatcher(process.argv[2], process.argv[3]);
| #!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var chalk = require('chalk');
var rimraf = require('rimraf');
var helpers = require('broccoli-kitchen-sink-helpers');
var Watcher = require('broccoli/lib/watcher');
var broccoli = require('broccoli');
function createWatcher(destDir, interval) {
var tree = broccoli.loadBrocfile();
var builder = new broccoli.Builder(tree);
var watcher = new Watcher(builder, {interval: interval || 100});
var atExit = function() {
builder.cleanup();
process.exit(1);
};
process.on('SIGINT', atExit);
process.on('SIGTERM', atExit);
watcher.on('change', function(results) {
rimraf.sync(destDir);
helpers.copyRecursivelySync(results.directory, destDir);
console.log(chalk.green("Build successful - " + Math.floor(results.totalTime / 1e6) + 'ms'));
});
watcher.on('error', function(err) {
console.log(chalk.red('\n\nBuild failed.\n'));
});
return watcher;
}
createWatcher(process.argv[2], process.argv[3]);
|
Set H2 over TLS as the default configuration | package com.github.arteam.dropwizard.http2.client;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.client.HttpClient;
/**
* Date: 11/26/15
* Time: 10:22 AM
* <p>
* A builder for {@link HttpClient}. It builds an instance from an external
* configuration and ties it to Dropwizard environment.
*
* @author Artem Prigoda
*/
public class JettyHttpClientBuilder {
private Environment environment;
private Http2ClientConfiguration configuration = new Http2ClientConfiguration();
public JettyHttpClientBuilder(Environment environment) {
this.environment = environment;
}
public JettyHttpClientBuilder using(Http2ClientConfiguration configuration) {
this.configuration = configuration;
return this;
}
public HttpClient build(String name) {
ClientTransportFactory connectionFactoryBuilder = configuration.getConnectionFactoryBuilder();
HttpClient httpClient = new HttpClient(
connectionFactoryBuilder.httpClientTransport(environment.metrics(), name),
connectionFactoryBuilder.sslContextFactory());
environment.lifecycle().manage(httpClient);
return httpClient;
}
public HttpClient build() {
return build("");
}
}
| package com.github.arteam.dropwizard.http2.client;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.client.HttpClient;
/**
* Date: 11/26/15
* Time: 10:22 AM
* <p>
* A builder for {@link HttpClient}. It builds an instance from an external
* configuration and ties it to Dropwizard environment.
*
* @author Artem Prigoda
*/
public class JettyHttpClientBuilder {
private Environment environment;
private Http2ClientConfiguration configuration;
public JettyHttpClientBuilder(Environment environment) {
this.environment = environment;
}
public JettyHttpClientBuilder using(Http2ClientConfiguration configuration) {
this.configuration = configuration;
return this;
}
public HttpClient build(String name) {
ClientTransportFactory connectionFactoryBuilder = configuration.getConnectionFactoryBuilder();
HttpClient httpClient = new HttpClient(
connectionFactoryBuilder.httpClientTransport(environment.metrics(), name),
connectionFactoryBuilder.sslContextFactory());
environment.lifecycle().manage(httpClient);
return httpClient;
}
public HttpClient build() {
return build("");
}
}
|
Use isolatedModules for ts-jest to speed up test | module.exports = {
globals: {
'ts-jest': {
isolatedModules: true,
diagnostics: false
}
},
roots: ['<rootDir>/src/js'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.js$': 'ts-jest'
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(t|j)sx?$',
moduleDirectories: ['node_modules', 'src', 'src/js'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
transformIgnorePatterns: ['<rootDir>/node_modules/(?!(react-dnd|dnd-core))'],
moduleNameMapper: {
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'babel-jest'
},
setupFilesAfterEnv: ['<rootDir>/src/js/test/setupTest.ts'],
testURL: 'http://localhost/',
collectCoverage: true,
coverageDirectory: './coverage/'
}
| module.exports = {
globals: {
'ts-jest': {
diagnostics: false
}
},
roots: ['<rootDir>/src/js'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.js$': 'ts-jest'
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(t|j)sx?$',
moduleDirectories: ['node_modules', 'src', 'src/js'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
transformIgnorePatterns: ['<rootDir>/node_modules/(?!(react-dnd|dnd-core))'],
moduleNameMapper: {
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'babel-jest'
},
setupFilesAfterEnv: ['<rootDir>/src/js/test/setupTest.ts'],
testURL: 'http://localhost/',
collectCoverage: true,
coverageDirectory: './coverage/'
}
|
Correct search onclick event delegation by using currentTarget | const searchEntitySelector = '.js-search-entity'
const SearchAnalytics = {
init() {
this.pageNumber =
new URLSearchParams(window.location.search).get('page') || 1
const entities = document.querySelectorAll(searchEntitySelector)
if (entities) {
for (let i = 0; i < entities.length; i++) {
entities[i].addEventListener('click', this.onClickHandler.bind(this))
}
}
},
pushAnalyticsEvent({
searchResultRank,
searchResultPageNumber,
searchCategory,
}) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({
event: 'searchResultClick',
searchResultPageNumber,
searchResultRank,
searchCategory,
})
},
onClickHandler(e) {
const target = e.currentTarget
if (target) {
this.pushAnalyticsEvent({
searchResultRank: target.dataset.searchResultRank,
searchResultPageNumber: this.pageNumber,
searchCategory: target.dataset.searchCategory,
})
}
},
}
module.exports = SearchAnalytics
| const searchEntitySelector = '.js-search-entity'
const SearchAnalytics = {
init() {
this.pageNumber =
new URLSearchParams(window.location.search).get('page') || 1
const entities = document.querySelectorAll(searchEntitySelector)
if (entities) {
for (let i = 0; i < entities.length; i++) {
entities[i].addEventListener('click', this.onClickHandler.bind(this))
}
}
},
pushAnalyticsEvent({
searchResultRank,
searchResultPageNumber,
searchCategory,
}) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({
event: 'searchResultClick',
searchResultPageNumber,
searchResultRank,
searchCategory,
})
},
onClickHandler(e) {
const target = e.target
if (target) {
this.pushAnalyticsEvent({
searchResultRank: target.dataset.searchResultRank,
searchResultPageNumber: this.pageNumber,
searchCategory: target.dataset.searchCategory,
})
}
},
}
module.exports = SearchAnalytics
|
config: Make sure use_testing() is not detected as a unit test by nose | import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
# Make sure use_testing() is not detected as a unit test by nose
use_testing.__test__ = False
| import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
|
Remove upload view from sourcecollectionview | AV.SourceCollectionView = Backbone.View.extend({
el: '#list_container',
initialize: function() {
this.listenTo(this.collection, 'all', this.render);
console.log("Initialize View");
},
events: {
"click #deleteButton": "delete",
//"click #uploadButton": "upload",
},
template: _.template( $("#list_template").html()),
render: function () {
this.$el.empty();
console.log("Rendered");
this.$el.html(this.template({sources: this.collection.models}));
test();
},
delete: function(ev) {
//ev is the mouse event. We receive the data-value which contains
//the id.
test("in delete in source collection");
var idToDelete = $(ev.target).data('value');
var sourceToRemove = this.collection.find(function (source) {
return source.id == idToDelete;});
sourceToRemove.urlRoot = 'php/redirect.php/source/';
sourceToRemove.destroy();
}
});
| AV.SourceCollectionView = Backbone.View.extend({
el: '#list_container',
initialize: function() {
this.listenTo(this.collection, 'all', this.render);
console.log("Initialize View");
},
events: {
"click #deleteButton": "delete",
//"click #uploadButton": "upload",
},
template: _.template( $("#list_template").html()),
render: function () {
this.$el.empty();
console.log("Rendered");
this.$el.html(this.template({sources: this.collection.models}));
test();
},
delete: function(ev) {
//ev is the mouse event. We receive the data-value which contains
//the id.
test("in delete in source collection");
var idToDelete = $(ev.target).data('value');
var sourceToRemove = this.collection.find(function (source) {
return source.id == idToDelete;});
sourceToRemove.urlRoot = 'php/redirect.php/source/';
sourceToRemove.destroy();
},
upload: function(ev) {
uploadModel = new AV.SourceModel({name: $("#upload").val(), data: $("#uploadContent").val()});
uploadModel.save();
},
});
|
Use UUID as primary key of PodcastUpdateResult | from datetime import datetime
from django.db import models
from mygpo.core.models import UUIDModel
from mygpo.podcasts.models import Podcast
class PodcastUpdateResult(UUIDModel):
""" Results of a podcast update
Once an instance is stored, the update is assumed to be finished. """
# The podcast that was updated
podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE)
# The timestamp at which the updated started to be executed
start = models.DateTimeField(default=datetime.utcnow)
# The duration of the update
duration = models.DurationField()
# A flad indicating whether the update was successful
successful = models.BooleanField()
# An error message. Should be empty if the update was successful
error_message = models.TextField()
# A flag indicating whether the update created the podcast
podcast_created = models.BooleanField()
# The number of episodes that were created by the update
episodes_added = models.IntegerField()
class Meta(object):
get_latest_by = 'start'
ordering = ['-start']
indexes = [
models.Index(fields=['podcast', 'start'])
]
| from datetime import datetime
from django.db import models
from mygpo.podcasts.models import Podcast
class PodcastUpdateResult(models.Model):
""" Results of a podcast update
Once an instance is stored, the update is assumed to be finished. """
# The podcast that was updated
podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE)
# The timestamp at which the updated started to be executed
start = models.DateTimeField(default=datetime.utcnow)
# The duration of the update
duration = models.DurationField()
# A flad indicating whether the update was successful
successful = models.BooleanField()
# An error message. Should be empty if the update was successful
error_message = models.TextField()
# A flag indicating whether the update created the podcast
podcast_created = models.BooleanField()
# The number of episodes that were created by the update
episodes_added = models.IntegerField()
class Meta(object):
get_latest_by = 'start'
ordering = ['-start']
indexes = [
models.Index(fields=['podcast', 'start'])
]
|
Debug any incoming POST request. | import json
import logging
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from settings import *
class MainHandler(tornado.web.RequestHandler):
def post(self):
logging.debug(json.dumps(self.request))
application = tornado.web.Application([
(r'/', MainHandler),
])
if __name__ == "__main__":
define("port", default="443", help="Port to listen on")
define("host", default="localhost", help="Server address to listen on")
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(application, ssl_options={
"certfile": PEMFILE,
"keyfile": KEYFILE
})
http_server.listen(int(options.port), address=options.host)
tornado.ioloop.IOLoop.current().start()
| import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from settings import *
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r'/', MainHandler),
])
if __name__ == "__main__":
define("port", default="443", help="Port to listen on")
define("host", default="localhost", help="Server address to listen on")
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(application, ssl_options={
"certfile": PEMFILE,
"keyfile": KEYFILE
})
http_server.listen(int(options.port), address=options.host)
tornado.ioloop.IOLoop.current().start()
|
Make sure any config overrides are reset
The new deploy unit tests have conf.set_override() but
don't reset these after each test, so depending on the
test order there are failures.
This just addes a generic cleanup in the base class to catch
all of them.
Change-Id: Idb1b4ef158808b08657f34bfe1546fa2ec0dae9f | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import contextlib
from oslo_config import cfg
from oslotest import base
import six
import testscenarios
# Python 3, thank you for dropping contextlib.nested
if six.PY3:
@contextlib.contextmanager
def nested(*contexts):
with contextlib.ExitStack() as stack:
yield [stack.enter_context(c) for c in contexts]
else:
nested = contextlib.nested
class BaseTestCase(testscenarios.WithScenarios,
base.BaseTestCase):
"""Test case base class for all unit tests."""
def setUp(self):
super(BaseTestCase, self).setUp()
self.addCleanup(cfg.CONF.reset)
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import contextlib
from oslotest import base
import six
import testscenarios
# Python 3, thank you for dropping contextlib.nested
if six.PY3:
@contextlib.contextmanager
def nested(*contexts):
with contextlib.ExitStack() as stack:
yield [stack.enter_context(c) for c in contexts]
else:
nested = contextlib.nested
class BaseTestCase(testscenarios.WithScenarios,
base.BaseTestCase):
"""Test case base class for all unit tests."""
|
Use route whitelist method for security | /*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
Router.configure({
layoutTemplate: 'MasterLayout',
loadingTemplate: 'Loading',
notFoundTemplate: 'NotFound'
});
Router.route('/', {
name: 'marketing'
});
Router.route('/pages', {
name: 'pages.index'
});
Router.route('/pages/new', {
name: 'pages.new'
});
Router.route('/pages/:_id', {
name: 'pages.show'
});
Router.route('/settings', {
name: 'settings.index'
});
Router.route('/users/:_id', {
name: 'users.show'
});
Router.route('/users/:_id/edit', {
name:'users.edit'
});
var requireLogin = function () {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('AccessDenied');
}
} else {
this.next();
}
};
Router.onBeforeAction('dataNotFound');
Router.onBeforeAction(requireLogin, {
except: [
'marketing',
'pages.show'
]
});
| /*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
Router.configure({
layoutTemplate: 'MasterLayout',
loadingTemplate: 'Loading',
notFoundTemplate: 'NotFound'
});
Router.route('/', {
name: 'marketing'
});
Router.route('/pages', {
name: 'pages.index'
});
Router.route('/pages/new', {
name: 'pages.new'
});
Router.route('/pages/:_id', {
name: 'pages.show'
});
Router.route('/settings', {
name: 'settings.index'
});
Router.route('/users/:_id', {
name: 'users.show'
});
Router.route('/users/:_id/edit', {
name:'users.edit'
});
var requireLogin = function () {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('AccessDenied');
}
} else {
this.next();
}
};
Router.onBeforeAction('dataNotFound');
Router.onBeforeAction(requireLogin, {
only: [
'pages.index',
'pages.new',
'settings.index',
'users.show',
'users.edit'
]
});
|
Add log_errors flag to _execute | from __future__ import unicode_literals, print_function
import logging
import subprocess
logger = logging.getLogger(__name__)
def _execute(cmd, strict=False, log_errors=True):
"""
Make executing a command locally a little less painful
"""
logger.debug("executing {0}".format(cmd))
process = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
return_code = process.wait()
# flake8 by default returns non-zero
# status code when any violations have been found
# so only log if error message is present
if return_code != 0 and (err or strict):
if log_errors:
logger.error(err)
if strict:
raise subprocess.CalledProcessError(return_code, cmd)
return out.decode('utf-8')
| from __future__ import unicode_literals, print_function
import logging
import subprocess
logger = logging.getLogger(__name__)
def _execute(cmd, strict=False):
"""
Make executing a command locally a little less painful
"""
logger.debug("executing {0}".format(cmd))
process = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
return_code = process.wait()
# flake8 by default returns non-zero
# status code when any violations have been found
# so only log if error message is present
if return_code != 0 and (err or strict):
logger.error(err)
if strict:
raise subprocess.CalledProcessError(return_code, cmd)
return out.decode('utf-8')
|
Fix API usage for API level 10. | /*
* Copyright 2014 Danny Baumann
*
* 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.gh4a;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
public class EventReceiver extends BroadcastReceiver {
@SuppressLint("InlinedApi")
@Override
public void onReceive(Context context, Intent intent) {
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
downloadManagerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
context.startActivity(downloadManagerIntent);
}
}
}
| /*
* Copyright 2014 Danny Baumann
*
* 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.gh4a;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class EventReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
downloadManagerIntent.setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(downloadManagerIntent);
}
}
}
|
Add space between anon function and parens. | /*
* To Title Case 2.0 – http://individed.com/code/to-title-case/
* Copyright © 2008–2012 David Gouch. Licensed under the MIT License.
*/
String.prototype.toTitleCase = function () {
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;
return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {
if (index > 0 && index + p1.length !== title.length &&
p1.search(smallWords) > -1 && title[index - 2] !== ":" &&
title[index - 1].search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (p1.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
| /*
* To Title Case 2.0 – http://individed.com/code/to-title-case/
* Copyright © 2008–2012 David Gouch. Licensed under the MIT License.
*/
String.prototype.toTitleCase = function() {
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;
return this.replace(/([^\W_]+[^\s-]*) */g, function(match, p1, index, title) {
if (index > 0 && index + p1.length !== title.length &&
p1.search(smallWords) > -1 && title[index - 2] !== ":" &&
title[index - 1].search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (p1.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
|
Change default adapter for new apps to filesystem | /*
* Geddy JavaScript Web development framework
* Copyright 2112 Matthew Eernisse (mde@fleegix.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.
*
*/
var config = {
detailedErrors: true
, debug: true
, hostname: null
, port: 4000
, model: {
defaultAdapter: 'filesystem'
}
, sessions: {
store: 'memory'
, key: 'sid'
, expiry: 14 * 24 * 60 * 60
}
};
module.exports = config;
| /*
* Geddy JavaScript Web development framework
* Copyright 2112 Matthew Eernisse (mde@fleegix.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.
*
*/
var config = {
detailedErrors: true
, debug: true
, hostname: null
, port: 4000
, model: {
defaultAdapter: 'memory'
}
, sessions: {
store: 'memory'
, key: 'sid'
, expiry: 14 * 24 * 60 * 60
}
};
module.exports = config;
|
Allow to pull value from parent configuration, if set. | package org.jbake.render.support;
import org.apache.commons.configuration.CompositeConfiguration;
public class MockCompositeConfiguration extends CompositeConfiguration {
private boolean _bool = false;
private String _string = "random string";
public MockCompositeConfiguration withDefaultBoolean(boolean bool) {
_bool = bool;
return this;
}
public MockCompositeConfiguration withInnerString(String string) {
_string = string;
return this;
}
@Override
public boolean getBoolean(String key) {
if ( super.containsKey(key) ) {
return super.getBoolean(key);
}
return _bool;
}
@Override
public String getString(String key) {
if ( super.containsKey(key) ) {
return super.getString(key);
}
return _string;
}
} | package org.jbake.render.support;
import org.apache.commons.configuration.CompositeConfiguration;
public class MockCompositeConfiguration extends CompositeConfiguration {
private boolean _bool = false;
private String _string = "random string";
public MockCompositeConfiguration withDefaultBoolean(boolean bool) {
_bool = bool;
return this;
}
public MockCompositeConfiguration withInnerString(String string) {
_string = string;
return this;
}
@Override
public boolean getBoolean(String key) {
if ( super.containsKey(key) ) {
return super.getBoolean(key);
}
return _bool;
}
@Override
public String getString(String string) {
return _string;
}
} |
Add back Track component image | import PropTypes from 'prop-types';
import React from 'react';
import styles from 'components/Track/Track.scss';
export default class Track extends React.Component {
render() {
return (
<div className={styles.track}>
<div className={styles.image}>
<img src={this.props.image}/>
</div>
<div className={styles.nameAndDescription}>
<div className={styles.name}>
{this.props.name}
</div>
<div className={styles.description}>
{this.props.description}
</div>
</div>
</div>
)
}
}
Track.propTypes = {
name: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
description: PropTypes.string.isRequired
}
| import PropTypes from 'prop-types';
import React from 'react';
import styles from 'components/Track/Track.scss';
export default class Track extends React.Component {
render() {
return (
<div className={styles.track}>
<div className={styles.nameAndDescription}>
<div className={styles.name}>
{this.props.name}
</div>
<div className={styles.description}>
{this.props.description}
</div>
</div>
</div>
)
}
}
Track.propTypes = {
name: PropTypes.string.isRequired,
image: PropTypes.string,
description: PropTypes.string.isRequired
}
|
Fix .it directory not being deleted on windows. | package main
import (
path "path/filepath"
"os"
"github.com/qlova/ilang/src"
_ "github.com/qlova/ilang/src/modules/all"
_ "github.com/qlova/ilang/src/types/all"
)
func ic(input, directory string) {
file, err := os.Open(input)
if err != nil {
return
}
ic := ilang.NewCompiler(file)
if directory == "" {
directory = path.Dir(input)
}
//Open the output file with the file type replaced to .u
var filename = path.Base(input)[:len(path.Base(input))-2]+".u"
if output, err := os.Create(directory+"/"+filename); err != nil {
ic.RaiseError("Could not create output file!", err.Error())
} else {
ic.Output = output
defer output.Close()
}
if lib, err := os.Create(directory+"/ilang.u"); err != nil {
ic.RaiseError("Could not create output library file!", err.Error())
} else {
ic.Lib = lib
defer lib.Close()
}
ic.Compile()
}
| package main
import (
path "path/filepath"
"os"
"github.com/qlova/ilang/src"
_ "github.com/qlova/ilang/src/modules/all"
_ "github.com/qlova/ilang/src/types/all"
)
func ic(input, directory string) {
file, err := os.Open(input)
if err != nil {
return
}
ic := ilang.NewCompiler(file)
if directory == "" {
directory = path.Dir(input)
}
//Open the output file with the file type replaced to .u
var filename = path.Base(input)[:len(path.Base(input))-2]+".u"
if output, err := os.Create(directory+"/"+filename); err != nil {
ic.RaiseError("Could not create output file!", err.Error())
} else {
ic.Output = output
}
if lib, err := os.Create(directory+"/ilang.u"); err != nil {
ic.RaiseError("Could not create output library file!", err.Error())
} else {
ic.Lib = lib
}
ic.Compile()
}
|
Fix issue with config-nodemgr and cassandra-repair listening on same port
contrail-config-nodemgr spawns contrail-cassandra-repair using
subprocess.Popen and thus contrail-cassandra-repair inherits all
the fds including the listening fd. Then when contrail-config-nodemgr
is restarted/killed, contrail-cassandra-repair will still have the
listening fd and hence contrail-config-nodemgr will not be able to
come up and listen on the same port. Fix is to use - close_fds=True
in the Popen call since the parent and child don't really need to
communicate or share anything using fds and this will close all the
fds shared from parent in the child.
Change-Id: Icef9f981c6447dd013cebeab727f49c5e2cf74f8
Closes-Bug: #1643466 | #
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
import subprocess
class CassandraManager(object):
def __init__(self, cassandra_repair_logdir):
self.cassandra_repair_logdir = cassandra_repair_logdir
def status(self):
subprocess.Popen(["contrail-cassandra-status",
"--log-file", "/var/log/cassandra/status.log",
"--debug"], close_fds=True)
def repair(self):
logdir = self.cassandra_repair_logdir + "repair.log"
subprocess.Popen(["contrail-cassandra-repair",
"--log-file", logdir,
"--debug"], close_fds=True)
| #
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
import subprocess
class CassandraManager(object):
def __init__(self, cassandra_repair_logdir):
self.cassandra_repair_logdir = cassandra_repair_logdir
def status(self):
subprocess.Popen(["contrail-cassandra-status",
"--log-file", "/var/log/cassandra/status.log",
"--debug"])
def repair(self):
logdir = self.cassandra_repair_logdir + "repair.log"
subprocess.Popen(["contrail-cassandra-repair",
"--log-file", logdir,
"--debug"])
|
Allow the cache to be turned off | <?php
/**
* Copyright (C) 2016 Stratadox
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Stratadox
* @package Stratadox\Di
*/
namespace Stratadox\Di;
use Closure;
interface ContainerInterface
{
public function set($name, Closure $factory, $cache = false);
public function get($name, $type = '');
public function has($name);
public function forget($name);
}
| <?php
/**
* Copyright (C) 2016 Stratadox
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Stratadox
* @package Stratadox\Di
*/
namespace Stratadox\Di;
use Closure;
interface ContainerInterface
{
public function set($name, Closure $factory);
public function get($name, $type = '');
public function has($name);
public function forget($name);
}
|
Check if the x-frame-options header is already set
Former-commit-id: 5121dd2f802162895e09676b855a50fb7f09155f
Former-commit-id: 587564af563a41e838051cc40f67c2415e7a893a | <?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;
class Response extends \Symfony\Component\HttpFoundation\Response {
public function send() {
$cleared = Cookie::getClearedCookies();
foreach($cleared as $cookie) {
$this->headers->clearCookie($cookie);
}
$cookies = Cookie::getCookies();
foreach($cookies as $cookie) {
$this->headers->setCookie($cookie);
}
if ($this->headers->has('X-Frame-Options') === false) {
$x_frame_options = Config::get('concrete.security.misc.x_frame_options');
if (Core::make('helper/validation/strings')->notempty($x_frame_options)) {
$this->headers->set('X-Frame-Options', $x_frame_options);
}
}
parent::send();
}
} | <?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;
class Response extends \Symfony\Component\HttpFoundation\Response {
public function send() {
$cleared = Cookie::getClearedCookies();
foreach($cleared as $cookie) {
$this->headers->clearCookie($cookie);
}
$cookies = Cookie::getCookies();
foreach($cookies as $cookie) {
$this->headers->setCookie($cookie);
}
$x_frame_options = Config::get('concrete.security.misc.x_frame_options');
if (Core::make('helper/validation/strings')->notempty($x_frame_options)) {
$this->headers->set('X-Frame-Options', $x_frame_options);
}
parent::send();
}
} |
Add groups url to serialized urls. | from addons.base.serializer import CitationsAddonSerializer
class ZoteroSerializer(CitationsAddonSerializer):
addon_short_name = 'zotero'
@property
def serialized_node_settings(self):
result = super(ZoteroSerializer, self).serialized_node_settings
result['library'] = {
'name': self.node_settings.fetch_library_name
}
return result
@property
def addon_serialized_urls(self):
node = self.node_settings.owner
serialized_urls = super(ZoteroSerializer, self).addon_serialized_urls
serialized_urls['groups'] = node.api_url_for('{0}_group_list'.format(self.addon_short_name))
return serialized_urls
| from addons.base.serializer import CitationsAddonSerializer
class ZoteroSerializer(CitationsAddonSerializer):
addon_short_name = 'zotero'
@property
def serialized_node_settings(self):
result = super(ZoteroSerializer, self).serialized_node_settings
result['library'] = {
'name': self.node_settings.fetch_library_name
}
return result
@property
def addon_serialized_urls(self):
node = self.node_settings.owner
serialized_urls = super(ZoteroSerializer, self).addon_serialized_urls
serialized_urls['groups'] = node.api_url_for('{0}_group_list'.format(self.addon_short_name))
return serialized_urls
|
Delete Cloud Profile in Basic Package | /*
* Copyright (C) 2016 Thinkenterprise
*
* 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.
*
*
* @author Michael Schaefer
*/
package com.thinkenterprise;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import com.thinkenterprise.service.CloudEnvironmentService;
import com.thinkenterprise.service.DevelopmentEnvironmentService;
import com.thinkenterprise.service.EnvironmentService;
@Configuration
public class ApplicationConfiguration {
@Bean
@Profile("default")
public EnvironmentService getDefaultEnvironmentService() {
return new DevelopmentEnvironmentService();
}
public EnvironmentService getCloudEnvironmentService() {
return new CloudEnvironmentService();
}
}
| /*
* Copyright (C) 2016 Thinkenterprise
*
* 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.
*
*
* @author Michael Schaefer
*/
package com.thinkenterprise;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import com.thinkenterprise.service.CloudEnvironmentService;
import com.thinkenterprise.service.DevelopmentEnvironmentService;
import com.thinkenterprise.service.EnvironmentService;
@Configuration
public class ApplicationConfiguration {
@Bean
@Profile("default")
public EnvironmentService getDefaultEnvironmentService() {
return new DevelopmentEnvironmentService();
}
@Bean
@Profile("cloud")
@Primary
public EnvironmentService getCloudEnvironmentService() {
return new CloudEnvironmentService();
}
}
|
Fix typo: compare baseline with baseline | package pipeTesting;
import core.Artifact;
import core.ArtifactID;
import util.Os;
/**
* Created by nwilson on 2/23/15.
*/
public class CmdTest extends Test {
private static final String BASELINE_ARG = "\\$BASELINE";
private static final String ACTUAL_ARG = "\\$ACTUAL";
private final String cmd;
public CmdTest(String cmd, ArtifactID aid, String name) {
super(aid, name);
this.cmd = cmd;
}
@Override
void Verify(Artifact base, Artifact actual) {
String cmdParsed = this.cmd;
cmdParsed = cmdParsed.replaceAll(BASELINE_ARG, base.file.getAbsolutePath());
cmdParsed = cmdParsed.replaceAll(ACTUAL_ARG, actual.file.getAbsolutePath());
assert Os.current.Exec(cmdParsed) == 0;
}
}
| package pipeTesting;
import core.Artifact;
import core.ArtifactID;
import util.Os;
/**
* Created by nwilson on 2/23/15.
*/
public class CmdTest extends Test {
private static final String BASELINE_ARG = "\\$BASELINE";
private static final String ACTUAL_ARG = "\\$ACTUAL";
private final String cmd;
public CmdTest(String cmd, ArtifactID aid, String name) {
super(aid, name);
this.cmd = cmd;
}
@Override
void Verify(Artifact base, Artifact actual) {
String cmdParsed = this.cmd;
cmdParsed = cmdParsed.replaceAll(BASELINE_ARG, base.file.getAbsolutePath());
cmdParsed = cmdParsed.replaceAll(ACTUAL_ARG, base.file.getAbsolutePath());
assert Os.current.Exec(cmdParsed) == 0;
}
}
|
Add TrimFormatter and RemoveBracesFormatter to save actions | package net.sf.jabref.logic.formatter;
import net.sf.jabref.logic.formatter.bibtexfields.*;
import java.util.Arrays;
import java.util.List;
public class BibtexFieldFormatters {
public static final PageNumbersFormatter PAGE_NUMBERS = new PageNumbersFormatter();
public static final SuperscriptFormatter SUPERSCRIPTS = new SuperscriptFormatter();
public static final DateFormatter DATE = new DateFormatter();
public static final MonthFormatter MONTH_FORMATTER = new MonthFormatter();
public static final AuthorsFormatter AUTHORS_FORMATTER = new AuthorsFormatter();
public static final LatexFormatter LATEX_FORMATTER = new LatexFormatter();
public static final UnitFormatter UNIT_FORMATTER = new UnitFormatter();
public static final TrimFormatter TRIM_FORMATTER = new TrimFormatter();
public static final RemoveBracesFormatter REMOVE_BRACES_FORMATTER = new RemoveBracesFormatter();
public static final List<Formatter> ALL = Arrays.asList(PAGE_NUMBERS, SUPERSCRIPTS, DATE, AUTHORS_FORMATTER, LATEX_FORMATTER, MONTH_FORMATTER, UNIT_FORMATTER, TRIM_FORMATTER, REMOVE_BRACES_FORMATTER);
}
| package net.sf.jabref.logic.formatter;
import net.sf.jabref.logic.formatter.bibtexfields.*;
import java.util.Arrays;
import java.util.List;
public class BibtexFieldFormatters {
public static final PageNumbersFormatter PAGE_NUMBERS = new PageNumbersFormatter();
public static final SuperscriptFormatter SUPERSCRIPTS = new SuperscriptFormatter();
public static final DateFormatter DATE = new DateFormatter();
public static final MonthFormatter MONTH_FORMATTER = new MonthFormatter();
public static final AuthorsFormatter AUTHORS_FORMATTER = new AuthorsFormatter();
public static final LatexFormatter LATEX_FORMATTER = new LatexFormatter();
public static final UnitFormatter UNIT_FORMATTER = new UnitFormatter();
public static final List<Formatter> ALL = Arrays.asList(PAGE_NUMBERS, SUPERSCRIPTS, DATE, AUTHORS_FORMATTER, LATEX_FORMATTER, MONTH_FORMATTER, UNIT_FORMATTER);
}
|
Fix implementation of sample application | package com.growthbeat.growthbeatsample;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.growthbeat.Growthbeat;
import com.growthbeat.analytics.GrowthAnalytics;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Growthbeat.getInstance().initialize(this, "OyVa3zboPjHVjsDC", "3EKydeJ0imxJ5WqS22FJfdVamFLgu7XA");
Growthbeat.getInstance().initializeGrowthAnalytics();
}
@Override
public void onStart() {
super.onStart();
GrowthAnalytics.getInstance().open();
GrowthAnalytics.getInstance().setBasicTags();
}
@Override
public void onStop() {
super.onStop();
GrowthAnalytics.getInstance().close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| package com.growthbeat.growthbeatsample;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.growthbeat.Growthbeat;
import com.growthbeat.analytics.GrowthAnalytics;
import com.growthpush.model.Environment;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Growthbeat.getInstance().initialize(getApplicationContext(), "OyVa3zboPjHVjsDC", "3EKydeJ0imxJ5WqS22FJfdVamFLgu7XA");
Growthbeat.getInstance().initializeGrowthPush(BuildConfig.DEBUG ? Environment.development : Environment.production, "955057365401");
Growthbeat.getInstance().initializeGrowthReplay();
GrowthAnalytics.getInstance().getHttpClient().setBaseUrl("http://api.stg.analytics.growthbeat.com/");
}
@Override
public void onStart() {
super.onStart();
GrowthAnalytics.getInstance().open();
GrowthAnalytics.getInstance().setBasicTags();
}
@Override
public void onStop() {
super.onStop();
GrowthAnalytics.getInstance().close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
Add data available to report template
git-svn-id: 28fe03dfd74dd77dcc8ecfe99fabcec8eed81bba@3509 8555b757-d854-4b86-925a-82fd84c90ff4 | <?php
$lines = array();
foreach($report->logs as $entry) {
$date = Utilities::formatDate($entry->created);
$lid = 'report_';
if($report->target_type == 'Recipient')
$lid .= 'recipient_';
if($entry->author_type == 'Guest')
$lid .= 'guest_';
$lid .= 'event_'.$entry->event;
$action = Lang::tr($lid)->r(
array(
'event' => $entry->event,
'date' => $entry->created,
'time_taken' => $entry->time_taken,
'author' => $entry->author,
'log' => $entry
),
$entry->target
);
$lines[] = array('date' => $date, 'action' => $action);
}
// Find longest date to compute first column width
$dw = max(array_map(function($line) {
return strlen($line['date']);
}, $lines));
foreach($lines as $line) {
echo $line['date'].str_repeat(' ', $dw - strlen($line['date'])).' : ';
echo chunk_split($line['action'], 76, GlobalConstants::NEW_LINE.str_repeat(' ', $dw + 3));
}
| <?php
$lines = array();
foreach($report->logs as $entry) {
$date = Utilities::formatDate($entry->created);
$lid = 'report_';
if($report->target_type == 'Recipient')
$lid .= 'recipient_';
if($entry->author_type == 'Guest')
$lid .= 'guest_';
$lid .= 'event_'.$entry->event;
$action = Lang::tr($lid)->r(
array(
'author' => $entry->author,
'log' => $entry
),
$entry->target
);
$lines[] = array('date' => $date, 'action' => $action);
}
// Find longest date to compute first column width
$dw = max(array_map(function($line) {
return strlen($line['date']);
}, $lines));
foreach($lines as $line) {
echo $line['date'].str_repeat(' ', $dw - strlen($line['date'])).' : ';
echo chunk_split($line['action'], 76, GlobalConstants::NEW_LINE.str_repeat(' ', $dw + 3));
}
|
Use nearest neighbor scaling in demo renderer. | !function(PIXI, exports) {
'use strict';
var Point = exports.Point,
Rect = exports.Rect;
function Frame(position, url, options) {
this.pos = position;
this.dir = options.direction || new Point(1, 1);
this.offset = options.offset || new Point(0, 0);
var base = PIXI.BaseTexture.fromImage(url, false, PIXI.scaleModes.NEAREST),
slice = options.crop || new Rect(0, 0, base.width, base.height),
tex = new PIXI.Texture(base, slice);
this.sprite = new PIXI.Sprite(tex);
this.render();
}
Frame.prototype.render = function() {
var gPos = this.sprite.position,
gScale = this.sprite.scale;
gPos.x = Math.round(this.pos.x + this.offset.x);
gPos.y = Math.round(this.pos.y + this.offset.y);
gScale.x = this.dir.x;
gScale.y = this.dir.y;
/*
* Flipping will result in the sprite appearing to jump (flips on the 0,
* rather than mid-sprite), so subtract the sprite's size from its position
* if it's flipped.
*/
if(gScale.x < 0) gPos.x -= this.sprite.width;
if(gScale.y < 0) gPos.y -= this.sprite.height;
};
exports.Frame = Frame;
}(PIXI, demo);
| !function(PIXI, exports) {
'use strict';
var Point = exports.Point,
Rect = exports.Rect;
function Frame(position, url, options) {
this.pos = position;
this.dir = options.direction || new Point(1, 1);
this.offset = options.offset || new Point(0, 0);
var base = PIXI.BaseTexture.fromImage(url),
slice = options.crop || new Rect(0, 0, base.width, base.height),
tex = new PIXI.Texture(base, slice);
this.sprite = new PIXI.Sprite(tex);
this.render();
}
Frame.prototype.render = function() {
var gPos = this.sprite.position,
gScale = this.sprite.scale;
gPos.x = Math.round(this.pos.x + this.offset.x);
gPos.y = Math.round(this.pos.y + this.offset.y);
gScale.x = this.dir.x;
gScale.y = this.dir.y;
/*
* Flipping will result in the sprite appearing to jump (flips on the 0,
* rather than mid-sprite), so subtract the sprite's size from its position
* if it's flipped.
*/
if(gScale.x < 0) gPos.x -= this.sprite.width;
if(gScale.y < 0) gPos.y -= this.sprite.height;
};
exports.Frame = Frame;
}(PIXI, demo);
|
Use the correct upper scope
I'm not sure what bugs this is causing, but it definitely looks broken. There is no such thing as `scopeManager.upper`. Following the [docs](https://github.com/estools/escope/blob/aa35861faa76a09f01203dee3497a939d70b463c/README.md#example), we should use `currentScope.upper`. | import {analyze} from 'escope';
import {isFunction} from './utils/functionType';
const emptyFn = () => {}; // eslint-disable-line no-empty-function
/**
* A helper for traversing with scope info from escope.
*
* Usage:
*
* traverser.traverse(ast, withScope(ast, {
* enter(node, parent, scope) {
* // do something with node and scope
* }
* }))
*
* @param {Object} ast The AST root node also passed to traverser.
* @param {Object} cfg Object with enter/leave function as expected by traverser.
* @return {Object} Object with enter/leave functions to be passed to traverser.
*/
export default function withScope(ast, {enter = emptyFn, leave = emptyFn}) {
const scopeManager = analyze(ast, {ecmaVersion: 6});
let currentScope = scopeManager.acquire(ast);
return {
enter(node, parent) {
if (isFunction(node)) {
currentScope = scopeManager.acquire(node);
}
return enter.call(this, node, parent, currentScope);
},
leave(node, parent) {
if (isFunction(node)) {
currentScope = currentScope.upper;
}
return leave.call(this, node, parent, currentScope);
}
};
}
| import {analyze} from 'escope';
import {isFunction} from './utils/functionType';
const emptyFn = () => {}; // eslint-disable-line no-empty-function
/**
* A helper for traversing with scope info from escope.
*
* Usage:
*
* traverser.traverse(ast, withScope(ast, {
* enter(node, parent, scope) {
* // do something with node and scope
* }
* }))
*
* @param {Object} ast The AST root node also passed to traverser.
* @param {Object} cfg Object with enter/leave function as expected by traverser.
* @return {Object} Object with enter/leave functions to be passed to traverser.
*/
export default function withScope(ast, {enter = emptyFn, leave = emptyFn}) {
const scopeManager = analyze(ast, {ecmaVersion: 6});
let currentScope = scopeManager.acquire(ast);
return {
enter(node, parent) {
if (isFunction(node)) {
currentScope = scopeManager.acquire(node);
}
return enter.call(this, node, parent, currentScope);
},
leave(node, parent) {
if (isFunction(node)) {
currentScope = scopeManager.upper;
}
return leave.call(this, node, parent, currentScope);
}
};
}
|
Add ignoreVisible for getting directory before content-changed event,
because changing to invisible directory does not fire content-change | <?php
class Kwc_Directories_TopChoose_Events extends Kwc_Abstract_Events
{
protected function _onOwnRowUpdate(Kwf_Component_Data $c, Kwf_Events_Event_Row_Abstract $event)
{
parent::_onOwnRowUpdate($c, $event);
if ($event->isDirty('directory_component_id')) {
$subroots = Kwf_Component_Data_Root::getInstance()
->getComponentsByDbId($event->row->directory_component_id, array('ignoreVisible'=>true));
foreach ($subroots as $subroot) {
$this->fireEvent(new Kwc_Directories_List_EventDirectoryChanged($this->_class, $subroot));
}
}
}
}
| <?php
class Kwc_Directories_TopChoose_Events extends Kwc_Abstract_Events
{
protected function _onOwnRowUpdate(Kwf_Component_Data $c, Kwf_Events_Event_Row_Abstract $event)
{
parent::_onOwnRowUpdate($c, $event);
if ($event->isDirty('directory_component_id')) {
$subroots = Kwf_Component_Data_Root::getInstance()
->getComponentsByDbId($event->row->directory_component_id);
foreach ($subroots as $subroot) {
$this->fireEvent(new Kwc_Directories_List_EventDirectoryChanged($this->_class, $subroot));
}
}
}
}
|
Clean up existing OS handling a little
* Avoid fall-through in switch statement.
* Improve error message in the case of incompatibility.
* Rename linux() function to posix().
* Sort cases alphabetically for improved readability. | var os = require('os')
var path = require('path')
var homedir = require('os-homedir')
function posix (id) {
var cacheHome = process.env.XDG_CACHE_HOME || path.join(homedir(), '.cache')
return path.join(cacheHome, id)
}
function darwin (id) {
return path.join(homedir(), 'Library', 'Caches', id)
}
function win32 (id) {
var appData = process.env.LOCALAPPDATA || path.join(homedir(), 'AppData', 'Local')
return path.join(appData, id, 'Cache')
}
var implementation = (function () {
switch (os.platform()) {
case 'android': return posix
case 'darwin': return darwin
case 'linux': return posix
case 'win32': return win32
default: throw new Error('Your OS "' + os.platform() + '" is currently not supported by node-cachedir.')
}
}())
module.exports = function (id) {
if (typeof id !== 'string') {
throw new TypeError('id is not a string')
}
if (id.length === 0) {
throw new Error('id cannot be empty')
}
if (/[^0-9a-zA-Z-]/.test(id)) {
throw new Error('id cannot contain special characters')
}
return implementation(id)
}
| var os = require('os')
var path = require('path')
var homedir = require('os-homedir')
function linux (id) {
var cacheHome = process.env.XDG_CACHE_HOME || path.join(homedir(), '.cache')
return path.join(cacheHome, id)
}
function darwin (id) {
return path.join(homedir(), 'Library', 'Caches', id)
}
function win32 (id) {
var appData = process.env.LOCALAPPDATA || path.join(homedir(), 'AppData', 'Local')
return path.join(appData, id, 'Cache')
}
var implementation = (function () {
switch (os.platform()) {
case 'android':
case 'linux': return linux
case 'darwin': return darwin
case 'win32': return win32
default: throw new Error('Your OS is currently not supported by node-cachedir.')
}
}())
module.exports = function (id) {
if (typeof id !== 'string') {
throw new TypeError('id is not a string')
}
if (id.length === 0) {
throw new Error('id cannot be empty')
}
if (/[^0-9a-zA-Z-]/.test(id)) {
throw new Error('id cannot contain special characters')
}
return implementation(id)
}
|
Disable CA cert checking, since it doesn't work on DH. | ---
---
<?php
///////////////////////////////////////
// Basic Config of the phpCAS client //
///////////////////////////////////////
// Full Hostname of your CAS Server
$cas_host = 'cas.fsu.edu';
// Context of the CAS Server
$cas_context = '/cas';
// Port of your CAS server. Normally for a https server it's 443
$cas_port = 443;
// Path to the ca chain that issued the cas server certificate
//$cas_server_ca_cert_path = __DIR__ . '/COMODOHigh-AssuranceSecureServerCA.crt';
//////////////////////////////////////////
// Cassowary Setting //
//////////////////////////////////////////
// Default list of users with global access
// note: rely on the fact that JSON string lists are PHP compatible
//$cassowary_users = {{ site.administrators | jsonify }};
$cassowary_users = array('{{ site.administrators | join: "', '" }}');
// Show or hide 19th century cassowary prints
$cassowary_show_pics = true;
// Show or hide page debug info
$cassowary_show_debug = false;
| ---
---
<?php
///////////////////////////////////////
// Basic Config of the phpCAS client //
///////////////////////////////////////
// Full Hostname of your CAS Server
$cas_host = 'cas.fsu.edu';
// Context of the CAS Server
$cas_context = '/cas';
// Port of your CAS server. Normally for a https server it's 443
$cas_port = 443;
// Path to the ca chain that issued the cas server certificate
$cas_server_ca_cert_path = __DIR__ . '/COMODOHigh-AssuranceSecureServerCA.crt';
//////////////////////////////////////////
// Cassowary Setting //
//////////////////////////////////////////
// Default list of users with global access
// note: rely on the fact that JSON string lists are PHP compatible
//$cassowary_users = {{ site.administrators | jsonify }};
$cassowary_users = array('{{ site.administrators | join: "', '" }}');
// Show or hide 19th century cassowary prints
$cassowary_show_pics = true;
// Show or hide page debug info
$cassowary_show_debug = false;
|
Update packaging metadata for accuracy | from setuptools import setup
import marquise.marquise
extension = marquise.marquise.ffi.verifier.get_extension()
with open('VERSION', 'r') as f:
VERSION = f.readline().strip()
# These notes suggest that there's not yet any "correct" way to do packageable
# CFFI interfaces. For now I'm splitting the CFFI stuff from the python
# interface stuff, and it seems to do the job okay, though dealing with
# packages and modules is a flailfest at best for me.
# https://bitbucket.org/cffi/cffi/issue/109/enable-sane-packaging-for-cffi
setup(
name="marquise",
version=VERSION,
description="Python bindings for libmarquise",
author="Barney Desmond",
author_email="engineering@anchor.net.au",
url="https://github.com/anchor/pymarquise",
zip_safe=False,
packages=[
"marquise",
],
ext_modules = [extension],
)
| from setuptools import setup
import marquise.marquise
extension = marquise.marquise.ffi.verifier.get_extension()
with open('VERSION', 'r') as f:
VERSION = f.readline().strip()
# These notes suggest that there's not yet any "correct" way to do packageable
# CFFI interfaces. For now I'm splitting the CFFI stuff from the python
# interface stuff, and it seems to do the job okay, though dealing with
# packages and modules is a flailfest at best for me.
# https://bitbucket.org/cffi/cffi/issue/109/enable-sane-packaging-for-cffi
setup(
name="marquise",
version=VERSION,
description="Python bindings for libmarquise",
author="Sharif Olorin",
author_email="sio@tesser.org",
url="https://github.com/anchor/pymarquise",
zip_safe=False,
packages=[
"marquise",
],
ext_modules = [extension],
)
|
Fix Python 2 compatibility issue | import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE= '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def iterm2_image_bytes(b, filename=None, inline=1):
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
def iterm2_display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.write(iterm2_image_bytes(f.read(), filename=fn))
| import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE= '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def iterm2_image_bytes(b, filename=None, inline=1):
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
def iterm2_display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'br') as f:
sys.stdout.write(iterm2_image_bytes(f.read(), filename=fn))
|
Use proper base object for Performance panel overlay | /* See license.txt for terms of usage */
"use strict";
// Add-on SDK
const { loadSheet, removeSheet } = require("sdk/stylesheet/utils");
const { Class } = require("sdk/core/heritage");
// Firebug.SDK
const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);
const { PanelOverlay } = require("firebug.sdk/lib/panel-overlay.js");
/**
* @overlay This object represents an overlay that is responsible
* for customizing the 'Performance' panel.
*/
const PerformanceOverlay = Class(
/** @lends PerformanceOverlay */
{
extends: PanelOverlay,
overlayId: "performance",
onApplyTheme: function(win, oldTheme) {
loadSheet(win, "chrome://firebug/skin/performance.css", "author");
},
onUnapplyTheme: function(win, newTheme) {
removeSheet(win, "chrome://firebug/skin/performance.css", "author");
},
// Options
/**
* The performance panel uses the original popup menu already
* populated with all options since its XUL structure is
* wired with the JS logic. See: devtools/client/performance/performance.xul
*/
getOptionsMenuPopup: function() {
let doc = this.getPanelDocument();
return doc.getElementById("performance-options-menupopup");
},
});
// Exports from this module
exports.PerformanceOverlay = PerformanceOverlay;
| /* See license.txt for terms of usage */
"use strict";
const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);
const { loadSheet, removeSheet } = require("sdk/stylesheet/utils");
const { Class } = require("sdk/core/heritage");
const { BaseOverlay } = require("../chrome/base-overlay.js");
/**
* @overlay This object represents an overlay that is responsible
* for customizing the 'Performance' panel.
*/
const PerformanceOverlay = Class(
/** @lends PerformanceOverlay */
{
extends: BaseOverlay,
overlayId: "performance",
// Initialization
initialize: function(options) {
BaseOverlay.prototype.initialize.apply(this, arguments);
},
onReady: function(options) {
BaseOverlay.prototype.onReady.apply(this, arguments);
},
destroy: function() {
},
onApplyTheme: function(win, oldTheme) {
loadSheet(win, "chrome://firebug/skin/performance.css", "author");
},
onUnapplyTheme: function(win, newTheme) {
removeSheet(win, "chrome://firebug/skin/performance.css", "author");
},
// Options
/**
* The performance panel uses the original popup menu already
* populated with all options since its XUL structure is
* wired with the JS logic. See: devtools/client/performance/performance.xul
*/
getOptionsMenuPopup: function() {
let doc = this.getPanelDocument();
return doc.getElementById("performance-options-menupopup");
},
});
// Exports from this module
exports.PerformanceOverlay = PerformanceOverlay;
|
Change J keybind to Jesus | /*
* Copyright 2014 - 2016 | Wurst-Imperium | All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package tk.wurst_client.options;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.TreeSet;
public class KeybindManager extends TreeMap<String, TreeSet<String>>
{
public KeybindManager()
{
put("B", ".t fastbreak", ".t fastplace");
put("C", ".t fullbright");
put("G", ".t flight");
put("GRAVE", ".t speednuker");
put("H", ".t /home");
put("J", ".t jesus");
put("K", ".t multiaura");
put("L", ".t nuker");
put("LCONTROL", ".t navigator");
put("R", ".t killaura");
put("RSHIFT", ".t navigator");
put("U", ".t freecam");
put("X", ".t x-ray");
put("Z", ".t sneak");
}
public void put(String key, String... commands)
{
put(key, new TreeSet<String>(Arrays.asList(commands)));
}
}
| /*
* Copyright 2014 - 2016 | Wurst-Imperium | All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package tk.wurst_client.options;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.TreeSet;
public class KeybindManager extends TreeMap<String, TreeSet<String>>
{
public KeybindManager()
{
put("B", ".t fastbreak", ".t fastplace");
put("C", ".t fullbright");
put("G", ".t flight");
put("GRAVE", ".t speednuker");
put("H", ".t /home");
put("J", ".t phase");
put("K", ".t multiaura");
put("L", ".t nuker");
put("LCONTROL", ".t navigator");
put("R", ".t killaura");
put("RSHIFT", ".t navigator");
put("U", ".t freecam");
put("X", ".t x-ray");
put("Z", ".t sneak");
}
public void put(String key, String... commands)
{
put(key, new TreeSet<String>(Arrays.asList(commands)));
}
}
|
Add more careful version checks | # License information goes here
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# The line above will help with 2to3 support.
def most_recent_tag(tags,username=None):
"""Scan an SVN tags directory and return the most recent tag.
Parameters
----------
tags : str
A URL pointing to an SVN tags directory.
username : str, optional
If set, pass the value to SVN's ``--username`` option.
Returns
-------
most_recent_tag : str
The most recent tag found in ``tags``.
"""
from distutils.version import StrictVersion as V
from subprocess import Popen, PIPE
command = ['svn']
if username is not None:
command += ['--username', username]
command += ['ls',tags]
proc = Popen(command,stdout=PIPE,stderr=PIPE)
out, err = proc.communicate()
try:
mrt = sorted([v.rstrip('/') for v in out.split('\n') if len(v) > 0],
key=lambda x: V(x))[-1]
except IndexError:
mrt = '0.0.0'
return mrt
| # License information goes here
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# The line above will help with 2to3 support.
def most_recent_tag(tags,username=None):
"""Scan an SVN tags directory and return the most recent tag.
Parameters
----------
tags : str
A URL pointing to an SVN tags directory.
username : str, optional
If set, pass the value to SVN's ``--username`` option.
Returns
-------
most_recent_tag : str
The most recent tag found in ``tags``.
"""
from subprocess import Popen, PIPE
command = ['svn']
if username is not None:
command += ['--username', username]
command += ['ls',tags]
proc = Popen(command,stdout=PIPE,stderr=PIPE)
out, err = proc.communicate()
try:
mrt = sorted([v.rstrip('/') for v in out.split('\n') if len(v) > 0])[-1]
except IndexError:
mrt = '0.0.0'
return mrt
|
Allow using DataStore class as if dict | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.save()
return
with open(self.storagePath) as storageFile:
self.data = json.load(storageFile)
def save(self):
tmpFile = "{}.tmp".format(self.storagePath)
with open(tmpFile, "w") as storageFile:
storageFile.write(json.dumps(self.data, indent=4))
os.rename(tmpFile, self.storagePath)
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __getitem__(self, item):
return self.data[item]
| import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = None
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.data = {}
self.save()
return
with open(self.storagePath) as storageFile:
self.data = json.load(storageFile)
def save(self):
tmpFile = "{}.tmp".format(self.storagePath)
with open(tmpFile, "w") as storageFile:
storageFile.write(json.dumps(self.data, indent=4))
os.rename(tmpFile, self.storagePath)
|
Send a newline with configuration commands. | import logging
import os
from lobster import util
from lobster.core.command import Command
from lockfile import AlreadyLocked
class Configure(Command):
@property
def help(self):
return 'change the configuration of a running lobster process'
def setup(self, argparser):
argparser.add_argument('command', help='a python expression to change a mutable configuration setting')
def run(self, args):
logger = logging.getLogger('lobster.configure')
try:
pidfile = util.get_lock(args.config.workdir)
logger.info("Lobster process not running, directly changing configuration.")
with util.PartiallyMutable.lockdown():
exec args.command in {'config': args.config, 'storage': args.config.storage}, {}
args.config.save()
except AlreadyLocked:
logger.info("Lobster process still running, contacting process...")
logger.info("sending command: " + args.command)
logger.info("check the log of the main process for success")
icp = open(os.path.join(args.config.workdir, 'ipc'), 'w')
icp.write(args.command + '\n')
except Exception as e:
logger.error("can't change values: {}".format(e))
| import logging
import os
from lobster import util
from lobster.core.command import Command
from lockfile import AlreadyLocked
class Configure(Command):
@property
def help(self):
return 'change the configuration of a running lobster process'
def setup(self, argparser):
argparser.add_argument('command', help='a python expression to change a mutable configuration setting')
def run(self, args):
logger = logging.getLogger('lobster.configure')
try:
pidfile = util.get_lock(args.config.workdir)
logger.info("Lobster process not running, directly changing configuration.")
with util.PartiallyMutable.lockdown():
exec args.command in {'config': args.config, 'storage': args.config.storage}, {}
args.config.save()
except AlreadyLocked:
logger.info("Lobster process still running, contacting process...")
logger.info("sending command: " + args.command)
logger.info("check the log of the main process for success")
icp = open(os.path.join(args.config.workdir, 'ipc'), 'w')
icp.write(args.command)
except Exception as e:
logger.error("can't change values: {}".format(e))
|
Rollback database changes for all tests | <?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as LaravelTestCase;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
abstract class TestCase extends LaravelTestCase
{
use DatabaseTransactions,
MockeryPHPUnitIntegration; // Increments assertion count
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected $baseUrl = 'http://localhost';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../example/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}
| <?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\TestCase as LaravelTestCase;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
abstract class TestCase extends LaravelTestCase
{
use MockeryPHPUnitIntegration; // Increments assertion count
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected $baseUrl = 'http://localhost';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../example/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}
|
Fix keys being stuck in keyring container | package net.mcft.copy.betterstorage.inventory;
import net.mcft.copy.betterstorage.api.IKey;
import net.mcft.copy.betterstorage.misc.Constants;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public class InventoryKeyring extends InventoryItem {
public InventoryKeyring(EntityPlayer player, String title) {
super(player, 9, (title.isEmpty() ? Constants.containerKeyring : title), !title.isEmpty());
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
return ((stack == null) || ((stack.getItem() instanceof IKey) &&
((IKey)stack.getItem()).isNormalKey()));
}
@Override
public void onInventoryChanged() {
updateStack();
}
@Override
protected void updateStack() {
int count = 0;
for (ItemStack stack : allContents[0])
if (stack != null) count++;
stack.setItemDamage(count);
super.updateStack();
}
}
| package net.mcft.copy.betterstorage.inventory;
import net.mcft.copy.betterstorage.api.IKey;
import net.mcft.copy.betterstorage.misc.Constants;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public class InventoryKeyring extends InventoryItem {
public InventoryKeyring(EntityPlayer player, String title) {
super(player, 9, (title.isEmpty() ? Constants.containerKeyring : title), !title.isEmpty());
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
return ((stack != null) && (stack.getItem() instanceof IKey) &&
((IKey)stack.getItem()).isNormalKey());
}
@Override
public void onInventoryChanged() {
updateStack();
}
@Override
protected void updateStack() {
int count = 0;
for (ItemStack stack : allContents[0])
if (stack != null) count++;
stack.setItemDamage(count);
super.updateStack();
}
}
|
Update logging peer to debug | "use strict";
const config = require('./config/database');
const DHT = require('bittorrent-dht');
const redis = require("redis");
const client = redis.createClient(config.redis.port, config.redis.host, config.redis.options);
const bunyan = require("bunyan");
const logger = bunyan.createLogger({name: "crawler"});
const dht = new DHT();
dht.listen(6881, () => {
logger.info('now listening');
logger.info(dht.address());
});
dht.on('ready', () => {
logger.info('now ready');
});
dht.on('announce', (peer, infoHash) => {
logger.info(`announce : ${peer.host}:${peer.port} : ${infoHash.toString('hex')}`);
dht.lookup(infoHash);
client.rpush("DHTS", infoHash.toString('hex'));
});
dht.on('peer', (peer, infoHash, from) => {
logger.debug(`peer : ${peer.host}:${peer.port} : ${infoHash.toString('hex')}`);
});
dht.on('error', (err) => {
logger.error(err);
dht.destroy();
});
| "use strict";
const config = require('./config/database');
const DHT = require('bittorrent-dht');
const redis = require("redis");
const client = redis.createClient(config.redis.port, config.redis.host, config.redis.options);
const bunyan = require("bunyan");
const logger = bunyan.createLogger({name: "crawler"});
const dht = new DHT();
dht.listen(6881, () => {
logger.info('now listening');
logger.info(dht.address());
});
dht.on('ready', () => {
logger.info('now ready');
});
dht.on('announce', (peer, infoHash) => {
logger.info(`announce : ${peer.host}:${peer.port} : ${infoHash.toString('hex')}`);
dht.lookup(infoHash);
client.rpush("DHTS", infoHash.toString('hex'));
});
dht.on('peer', (peer, infoHash, from) => {
logger.info(`announce : ${peer.host}:${peer.port} : ${infoHash.toString('hex')}`);
});
dht.on('error', (err) => {
logger.error(err);
dht.destroy();
});
|
Update test cases asserts, to update TextVisitor creating better
description | package com.github.verhagen.textadventure.core.domain;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.github.verhagen.textadventure.core.impl.domain.Item;
import com.github.verhagen.textadventure.core.impl.domain.Room;
import com.github.verhagen.textadventure.core.impl.domain.TextVisitor;
public class TextVisitorTest {
@Test
public void visitEmptyHall() {
String description = "There is a front door on the south and a door on the east.";
IRoom hall = new Room("hall", description);
TextVisitor visitor = new TextVisitor();
hall.accept(visitor);
assertEquals(visitor.asText(), "You are in a hall. " + description);
}
@Test
public void visitHallWithABook() {
String description = "There is a front door on the south and a door on the east.";
String title = "TRS-80 Assembly-Language Programming";
IRoom hall = new Room("hall", description);
IItem book = new Item("book", title);
hall.add(book);
TextVisitor visitor = new TextVisitor();
hall.accept(visitor);
assertEquals(visitor.asText(), "You are in a hall. " + description + " Items: " + book.getName());
}
}
| package com.github.verhagen.textadventure.core.domain;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.github.verhagen.textadventure.core.impl.domain.Item;
import com.github.verhagen.textadventure.core.impl.domain.Room;
import com.github.verhagen.textadventure.core.impl.domain.TextVisitor;
public class TextVisitorTest {
@Test
public void visitEmptyHall() {
String description = "There is a front door on the south and a door on the east.";
IRoom hall = new Room("hall", description);
TextVisitor visitor = new TextVisitor();
hall.accept(visitor);
assertEquals(visitor.asText(), description);
}
@Test
public void visitHallWithABook() {
String description = "There is a front door on the south and a door on the east.";
String title = "TRS-80 Assembly-Language Programming";
IRoom hall = new Room("hall", description);
IItem book = new Item("book", title);
hall.add(book);
TextVisitor visitor = new TextVisitor();
hall.accept(visitor);
assertEquals(visitor.asText(), description + "Items: " + book.getName());
}
}
|
Use regex to match user metrics | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
import pytest
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(admin_app, config_overrides, make_admin_app):
app = make_admin_app(**config_overrides)
with app.app_context():
yield app.test_client()
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}])
def test_metrics(client):
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8'
assert response.mimetype == 'text/plain'
# Not a full match as there can be other metrics, too.
regex = re.compile(
'users_active_count \\d+\n'
'users_uninitialized_count \\d+\n'
'users_suspended_count \\d+\n'
'users_deleted_count \\d+\n'
'users_total_count \\d+\n'
)
assert regex.search(response.get_data(as_text=True)) is not None
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}])
def test_disabled_metrics(client):
response = client.get('/metrics')
assert response.status_code == 404
| """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import pytest
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(admin_app, config_overrides, make_admin_app):
app = make_admin_app(**config_overrides)
with app.app_context():
yield app.test_client()
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}])
def test_metrics(client):
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8'
assert response.mimetype == 'text/plain'
assert response.get_data(as_text=True) == (
'users_active_count 0\n'
'users_uninitialized_count 0\n'
'users_suspended_count 0\n'
'users_deleted_count 0\n'
'users_total_count 0\n'
)
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}])
def test_disabled_metrics(client):
response = client.get('/metrics')
assert response.status_code == 404
|
Make menu item parents expand based on their children's activeness | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery/jquery-2.1.1.js
//= require jquery_ujs
//= require bootstrap-sprockets
//= require metisMenu/jquery.metisMenu.js
//= require pace/pace.min.js
//= require slimscroll/jquery.slimscroll.min.js
//= require toastr
//= require sweetalert2
//= require_tree .
$(document).ready(function() {
var activeLi = $('li.active');
activeLi.parentsUntil( 'nav', 'li').addClass('active');
activeLi.parentsUntil( 'nav', 'ul').removeClass('collapse');
});
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery/jquery-2.1.1.js
//= require jquery_ujs
//= require bootstrap-sprockets
//= require metisMenu/jquery.metisMenu.js
//= require pace/pace.min.js
//= require slimscroll/jquery.slimscroll.min.js
//= require toastr
//= require sweetalert2
//= require_tree .
|
[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL | # Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
| # Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
Fix `Tourney` model's database table name | """
byceps.services.tourney.models.tourney
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import NewType
from uuid import UUID
from ....database import db, generate_uuid
from ....util.instances import ReprBuilder
from .tourney_category import TourneyCategory
TourneyID = NewType('TourneyID', UUID)
class Tourney(db.Model):
"""A tournament."""
__tablename__ = 'tourneys'
__table_args__ = (
db.UniqueConstraint('group_id', 'title'),
)
id = db.Column(db.Uuid, default=generate_uuid, primary_key=True)
group_id = db.Column(db.Uuid, db.ForeignKey('tourney_groups.id'), index=True, nullable=False)
group = db.relationship(TourneyCategory)
title = db.Column(db.Unicode(40), nullable=False)
def __init__(self, group: TourneyCategory, title: str) -> None:
self.group = group
self.title = title
def __repr__(self) -> str:
return ReprBuilder(self) \
.add_with_lookup('group') \
.add_with_lookup('title') \
.build()
| """
byceps.services.tourney.models.tourney
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import NewType
from uuid import UUID
from ....database import db, generate_uuid
from ....util.instances import ReprBuilder
from .tourney_category import TourneyCategory
TourneyID = NewType('TourneyID', UUID)
class Tourney(db.Model):
"""A tournament."""
__tablename__ = 'tourney_teams'
__table_args__ = (
db.UniqueConstraint('group_id', 'title'),
)
id = db.Column(db.Uuid, default=generate_uuid, primary_key=True)
group_id = db.Column(db.Uuid, db.ForeignKey('tourney_groups.id'), index=True, nullable=False)
group = db.relationship(TourneyCategory)
title = db.Column(db.Unicode(40), nullable=False)
def __init__(self, group: TourneyCategory, title: str) -> None:
self.group = group
self.title = title
def __repr__(self) -> str:
return ReprBuilder(self) \
.add_with_lookup('group') \
.add_with_lookup('title') \
.build()
|
Fix example of how to run script, and make it executable | #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", "emailAddress": "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
| #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", 'emailAddress': "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
|
Update file header with proper challenge name and link | // Challenge 32 - Break HMAC-SHA1 with a slightly less artificial timing leak
// http://cryptopals.com/sets/4/challenges/32
package cryptopals
import (
"crypto/sha1"
"net/http"
"time"
)
type challenge32 struct {
}
func (challenge32) ForgeHmacSHA1SignaturePrecise(addr, file string) []byte {
sig := make([]byte, sha1.Size)
x := challenge31{}
for i := 0; i < len(sig); i++ {
var valBest byte
var timeBest time.Duration
for j := 0; j < 256; j++ {
sig[i] = byte(j)
url := x.buildURL(addr, file, sig)
start := time.Now()
for k := 0; k < 15; k++ {
resp, _ := http.Get(url)
resp.Body.Close()
}
elapsed := time.Since(start)
if elapsed > timeBest {
valBest = byte(j)
timeBest = elapsed
}
}
sig[i] = valBest
}
return sig
}
| // Challenge 31 - Implement and break HMAC-SHA1 with an artificial timing leak
// http://cryptopals.com/sets/4/challenges/31
package cryptopals
import (
"crypto/sha1"
"net/http"
"time"
)
type challenge32 struct {
}
func (challenge32) ForgeHmacSHA1SignaturePrecise(addr, file string) []byte {
sig := make([]byte, sha1.Size)
x := challenge31{}
for i := 0; i < len(sig); i++ {
var valBest byte
var timeBest time.Duration
for j := 0; j < 256; j++ {
sig[i] = byte(j)
url := x.buildURL(addr, file, sig)
start := time.Now()
for k := 0; k < 15; k++ {
resp, _ := http.Get(url)
resp.Body.Close()
}
elapsed := time.Since(start)
if elapsed > timeBest {
valBest = byte(j)
timeBest = elapsed
}
}
sig[i] = valBest
}
return sig
}
|
Fix an error that could happen if someone entered text for articles per day in a GP entry. | <?php
$exp = $_REQUEST['exp'];
$message = $_REQUEST['message'];
$amount = $_REQUEST['amount'];
if (empty($exp) || empty($message) || empty($amount))
create_error('You left some value blank');
if(!is_numeric($amount))
{
create_error('Articles per day must be a number');
}
if ($exp == 1)
$value = 'YES';
else
$value = 'NO';
$db->query('SELECT * FROM galactic_post_applications WHERE game_id = '.$player->getGameID().' AND account_id = '.$player->getAccountID());
if ($db->nextRecord())
create_error('You have already applied once. Please be patient and your application will be answered at a later time.');
$db->query('INSERT INTO galactic_post_applications (game_id, account_id, description, written_before, articles_per_day) VALUES ('.SmrSession::$game_id.', '.$player->getAccountID().', ' . $db->escape_string($message,true) . ', '.$db->escapeString($value).', '.$db->escapeNumber($amount).')');
$container = array();
$container['url'] = 'skeleton.php';
if (!$player->isLandedOnPlanet())
$container['body'] = 'current_sector.php';
else
$container['body'] = 'planet_main.php';
$container['msg'] = 'Thank you for your application. It has been sent to the main editor and he will let you know if you have been accepted.';
forward($container);
?> | <?php
$exp = $_REQUEST['exp'];
$message = $_REQUEST['message'];
$amount = $_REQUEST['amount'];
if (empty($exp) || empty($message) || empty($amount))
create_error('You left some value blank');
if ($exp == 1)
$value = 'YES';
else
$value = 'NO';
$db->query('SELECT * FROM galactic_post_applications WHERE game_id = '.$player->getGameID().' AND account_id = '.$player->getAccountID());
if ($db->nextRecord())
create_error('You have already applied once. Please be patient and your application will be answered at a later time.');
$db->query('REPLACE INTO galactic_post_applications (game_id, account_id, description, written_before, articles_per_day) VALUES ('.SmrSession::$game_id.', '.$player->getAccountID().', ' . $db->escape_string($message,true) . ', '.$db->escapeString($value).', '.$amount.')');
$container = array();
$container['url'] = 'skeleton.php';
if (!$player->isLandedOnPlanet())
$container['body'] = 'current_sector.php';
else
$container['body'] = 'planet_main.php';
$container['msg'] = 'Thank you for your application. It has been sent to the main editor and he will let you know if you have been accepted.';
forward($container);
?> |
Use new marketing.scss in gulp workflow | var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
var paths = {
'jquery': './resources/vendor/jquery/',
'bootstrap': './resources/vendor/bootstrap-sass/assets/'
}
elixir(function(mix) {
mix.sass("app.scss", 'public/css/', {includePaths: [paths.bootstrap + 'stylesheets/']})
.sass("marketing.scss", 'public/css/', {includePaths: [paths.bootstrap + 'stylesheets/']})
.copy(paths.bootstrap + 'fonts/bootstrap/**', 'public/fonts')
.scripts([
'vendor/jquery/dist/jquery.js',
'vendor/bootstrap/dist/js/bootstrap.min.js',
'js/app.js',
], 'public/js/app.js', 'resources/')
.version(['css/app.css', 'css/marketing.css', 'js/app.js']);
mix.phpUnit();
});
| var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
var paths = {
'jquery': './resources/vendor/jquery/',
'bootstrap': './resources/vendor/bootstrap-sass/assets/'
}
elixir(function(mix) {
mix.sass("app.scss", 'public/css/', {includePaths: [paths.bootstrap + 'stylesheets/']})
.copy(paths.bootstrap + 'fonts/bootstrap/**', 'public/fonts')
.scripts([
'vendor/jquery/dist/jquery.js',
'vendor/bootstrap/dist/js/bootstrap.min.js',
'js/app.js',
], 'public/js/app.js', 'resources/')
.version(['css/app.css', 'js/app.js']);
mix.phpUnit();
});
|
Add a little bit of demo data to show what the list_orders view does | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from ..models import (
DBSession,
Order,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
with transaction.manager:
for i in range(0,10):
order = Order('exref_%s' % i, 1)
DBSession.add(order)
orders = DBSession.query(Order).all()
print len(orders)
| import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from ..models import (
DBSession,
Order,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
with transaction.manager:
order = Order('order_0001', 1)
DBSession.add(order)
orders = DBSession.query(Order).all()
print len(orders)
|
Revert Commit to Goals Service | // goalService.getAllGoals();
//
angular.module('sparrowFit')
.service('goalService',function($http){
this.getAllGoals= function (){
var allGoals=$http.get('/api/get/goals');
console.log('allGoals in goalService',allGoals);
return allGoals;
}
this.getGoal=function(goalID){
function goalMatchesParam(goal){
return goal.id === Number(goalID);
}
// var requestedGoal= this.getAllGoals()
// .filter(function(goal){
// return goalMatchesParam(goal)
// }).join('');
var requestedGoal= this.getAllGoals()
.find(goalMatchesParam)
return requestedGoal
}
this.addGoal=function(newGoal,callBack){
// call end point here
$http.post('/post/goals',newGoal);
callBack(newGoal);
};
})
| // goalService.getAllGoals();
//
angular.module('sparrowFit')
.service('goalService',function($http){
this.getAllGoals= function (){
var allGoals=$http.get('/api/get/goals');
return allGoals;
}
this.getGoal=function(goalID){
function goalMatchesParam(goal){
return goal.id === Number(goalID);
}
// var requestedGoal= this.getAllGoals()
// .filter(function(goal){
// return goalMatchesParam(goal)
// }).join('');
var requestedGoal= this.getAllGoals()
.find(goalMatchesParam)
return requestedGoal
}
this.addGoal=function(newGoal,callBack){
// call end point here
$http.post('/post/goals',newGoal);
callBack(newGoal);
};
})
|
Change scope in register function for $app
When running unit tests, the register fails since $this is not in object context | <?php namespace Krucas\Notification;
use Illuminate\Support\ServiceProvider;
class NotificationServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('edvinaskrucas/notification');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');
$this->app['notification'] = $this->app->share(function($app)
{
return new Notification($app['config'], $app['session']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
| <?php namespace Krucas\Notification;
use Illuminate\Support\ServiceProvider;
class NotificationServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('edvinaskrucas/notification');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');
$this->app['notification'] = $this->app->share(function($app)
{
return new Notification($this->app['config'], $this->app['session']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
} |
Use old filename to ensure backward compatibility | const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
entry: {
'dolphin-platform': './src/clientContextFactory.js',
'dolphin-platform.min': './src/clientContextFactory.js'
},
devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'dolphin',
libraryTarget: 'umd',
//umdNamedDefine: true
},
plugins: [
new UglifyJsPlugin({
include: /\.min\.js$/
})
]
};
| const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
entry: {
'dolphin-platform.bundle': './src/clientContextFactory.js',
'dolphin-platform.bundle.min': './src/clientContextFactory.js'
},
devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'dolphin',
libraryTarget: 'umd',
//umdNamedDefine: true
},
plugins: [
new UglifyJsPlugin({
include: /\.min\.js$/
})
]
};
|
Make all the things unicode. | """
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
| """
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|
Fix `context` argument wrongly passed to callback | /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Passes each element in the array to the given callback.
*
* @function Phaser.Utils.Array.Each
* @since 3.4.0
*
* @param {array} array - The array to search.
* @param {function} callback - A callback to be invoked for each item in the array.
* @param {object} context - The context in which the callback is invoked.
* @param {...*} [args] - Additional arguments that will be passed to the callback, after the child.
*
* @return {array} The input array.
*/
var Each = function (array, callback, context)
{
var i;
var args = [ null ];
for (i = 3; i < arguments.length; i++)
{
args.push(arguments[i]);
}
for (i = 0; i < array.length; i++)
{
args[0] = array[i];
callback.apply(context, args);
}
return array;
};
module.exports = Each;
| /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Passes each element in the array to the given callback.
*
* @function Phaser.Utils.Array.Each
* @since 3.4.0
*
* @param {array} array - The array to search.
* @param {function} callback - A callback to be invoked for each item in the array.
* @param {object} context - The context in which the callback is invoked.
* @param {...*} [args] - Additional arguments that will be passed to the callback, after the child.
*
* @return {array} The input array.
*/
var Each = function (array, callback, context)
{
var i;
var args = [ null ];
for (i = 2; i < arguments.length; i++)
{
args.push(arguments[i]);
}
for (i = 0; i < array.length; i++)
{
args[0] = array[i];
callback.apply(context, args);
}
return array;
};
module.exports = Each;
|
Add output value to test setup. | <?php
/**
* Created by PhpStorm.
* User: clemens
* Date: 21-03-14
* Time: 11:27
*/
namespace UmlGeneratorPhp;
use UmlGeneratorPhp\OopFilter;
use UmlGeneratorPhp\OopToDot;
class OopToDotTest extends \PHPUnit_Framework_TestCase
{
private $parser;
private $traverser;
public function setUp()
{
$this->parser = new \PhpParser\Parser(new \PhpParser\Lexer);
$this->traverser = new \PhpParser\NodeTraverser;
$filter = new OopFilter;
$filter->setMeta([
'file' => '/dummy/path.php',
'output' => 'dummy/output',
]);
$this->traverser->addVisitor($filter);
}
public function testGenerateHTML()
{
$code = file_get_contents(__DIR__ . '/data/class01.php');
$stmts = $this->parser->parse($code);
$data = $this->traverser->traverse($stmts);
//var_dump($data);
$toDot = new OopToDot();
$dot = $toDot->getClassDiagram($data);
}
}
| <?php
/**
* Created by PhpStorm.
* User: clemens
* Date: 21-03-14
* Time: 11:27
*/
namespace UmlGeneratorPhp;
use UmlGeneratorPhp\OopFilter;
use UmlGeneratorPhp\OopToDot;
class OopToDotTest extends \PHPUnit_Framework_TestCase
{
private $parser;
private $traverser;
public function setUp()
{
$this->parser = new \PhpParser\Parser(new \PhpParser\Lexer);
$this->traverser = new \PhpParser\NodeTraverser;
$filter = new OopFilter;
$filter->setMeta([
'file' => '/dummy/path.php'
]);
$this->traverser->addVisitor($filter);
}
public function testGenerateHTML()
{
$code = file_get_contents(__DIR__ . '/data/class01.php');
$stmts = $this->parser->parse($code);
$data = $this->traverser->traverse($stmts);
//var_dump($data);
$toDot = new OopToDot();
$dot = $toDot->getClassDiagram($data);
}
}
|
Set a valid default path | /* global window, document */
// TODO: Add default/missing icon path
var _DEFAULT_ICON_PATH = 'M0 0Z';
var _paths = {};
var IconStore = {
getPath: function(iconName) {
if (_paths[iconName]) {
return _paths[iconName];
}
if (typeof window === 'undefined') {
return _DEFAULT_ICON_PATH;
}
try {
var path = document.getElementById(iconName)
.getElementsByTagName('path')[0]
.getAttribute('d');
_paths[iconName] = path;
return path;
}
catch(err) {
console.error(new Error('Could not find icon path'));
return _DEFAULT_ICON_PATH;
}
}
};
module.exports = IconStore; | /* global window, document */
// TODO: Add default/missing icon path
var _DEFAULT_ICON_PATH = 'Need a real path...';
var _paths = {};
var IconStore = {
getPath: function(iconName) {
if (_paths[iconName]) {
return _paths[iconName];
}
if (typeof window === 'undefined') {
return _DEFAULT_ICON_PATH;
}
try {
var path = document.getElementById(iconName)
.getElementsByTagName('path')[0]
.getAttribute('d');
_paths[iconName] = path;
return path;
}
catch(err) {
console.error(new Error('Could not find icon path'));
}
}
};
module.exports = IconStore; |
Fix RelativePane breaking father-child contract | package fr.ourten.brokkgui.panel;
import fr.ourten.brokkgui.component.GuiNode;
import fr.ourten.brokkgui.data.RelativeBindingHelper;
/**
* @author Ourten 9 oct. 2016
*/
public class GuiRelativePane extends GuiPane
{
@Override
public void addChild(final GuiNode node)
{
this.addChild(node, .5f, .5f);
}
public void addChild(final GuiNode node, final float ratioX, final float ratioY)
{
this.getChildrensProperty().add(node);
node.setFather(this);
RelativeBindingHelper.bindToRelative(node, this, ratioX, ratioY);
}
public void setChildPos(final GuiNode node, final float ratioX, final float ratioY)
{
if (this.getChildrensProperty().contains(node))
{
node.getxPosProperty().unbind();
node.getyPosProperty().unbind();
RelativeBindingHelper.bindToRelative(node, this, ratioX, ratioY);
}
}
} | package fr.ourten.brokkgui.panel;
import fr.ourten.brokkgui.component.GuiNode;
import fr.ourten.brokkgui.data.RelativeBindingHelper;
/**
* @author Ourten 9 oct. 2016
*/
public class GuiRelativePane extends GuiPane
{
@Override
public void addChild(final GuiNode node)
{
this.addChild(node, .5f, .5f);
}
public void addChild(final GuiNode node, final float ratioX, final float ratioY)
{
this.getChildrensProperty().add(node);
RelativeBindingHelper.bindToRelative(node, this, ratioX, ratioY);
}
public void setChildPos(final GuiNode node, final float ratioX, final float ratioY)
{
if (this.getChildrensProperty().contains(node))
{
node.getxPosProperty().unbind();
node.getyPosProperty().unbind();
RelativeBindingHelper.bindToRelative(node, this, ratioX, ratioY);
}
}
} |
Import: Use @RunWith(Suite.class) for emul test suites.
...and update J2CL AllTests accordingly.
I will delete duplicated J2CL suites in another CL.
commit 032e49ff8d12170b00ac3232174f365df0182f4e
Author: Goktug Gokdogan <goktug@google.com>
Date: Wed Apr 12 20:06:35 2017 -0700
Use @RunWith(Suite.class) for emul test suites.
Change-Id: I2fc94ccf4298714dfee8ba9628f9137e30cdb8a0
PiperOrigin-RevId: 153108807 | /*
* Copyright 2015 Google Inc.
*
* 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.google.gwt.emultest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/** TestSuite for all of GWT's emul suites. */
@RunWith(Suite.class)
@SuiteClasses({
BigDecimalSuite.class,
BigIntegerSuite.class,
CollectionsSuite.class,
EmulSuite.class,
EmulJava8Suite.class,
})
public class AllTests {}
| /*
* Copyright 2015 Google Inc.
*
* 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.google.gwt.emultest;
import junit.framework.Test;
import junit.framework.TestSuite;
/** TestSuite for all of GWT's emul suites. */
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("All Emul tests");
suite.addTest(BigDecimalSuite.suite());
suite.addTest(BigIntegerSuite.suite());
suite.addTest(CollectionsSuite.suite());
suite.addTest(EmulSuite.suite());
suite.addTest(EmulJava8Suite.suite());
suite.addTest(TreeMapSuiteSub.suite());
suite.addTest(TreeSetSuiteSub.suite());
return suite;
}
}
|
Send measurement data as msg.payload | /**
* Copyright 2016 Jorne Roefs
*
**/
module.exports = function(RED) {
"use strict";
var fs = require('fs');
var child_process = require('child_process');
function ThsenseNode(n) {
RED.nodes.createNode(this,n);
var node = this;
var readth = __dirname + '/../bin/readth.sh';
fs.access(readth, fs.X_OK, (err) => {
console.log(err ? 'No execution access to ' + readth : 'ReadTH access OK');
});
this.on('input', function (msg) {
node.log(__dirname);
child_process.execFile(readth, (err, stdout, stderr) => {
if (err) {
node.error(err);
return null;
}
// node.log(stdout);
msg.payload = JSON.parse(stdout);
node.send(msg);
});
});
this.on("close", function() {
});
}
RED.nodes.registerType("thsense",ThsenseNode);
}
| /**
* Copyright 2016 Jorne Roefs
*
**/
module.exports = function(RED) {
"use strict";
var fs = require('fs');
var child_process = require('child_process');
function ThsenseNode(n) {
RED.nodes.createNode(this,n);
var node = this;
var readth = __dirname + '/../bin/readth.sh';
fs.access(readth, fs.X_OK, (err) => {
console.log(err ? 'No execution access to ' + readth : 'ReadTH access OK');
});
this.on('input', function (msg) {
node.log(__dirname);
child_process.execFile(readth, (err, stdout, stderr) => {
if (err) {
node.error(err);
return null;
}
node.log(stdout);
node.send(msg);
});
});
this.on("close", function() {
});
}
RED.nodes.registerType("thsense",ThsenseNode);
}
|
Change decreasing price start range
Closes #115 | package com.nincraft.ninbot.components.ac;
import lombok.Getter;
import java.util.Random;
@Getter
public enum TurnipPattern {
DECREASING, BIG_SPIKE(3, 100, 400, 1.5), SMALL_SPIKE(4, 65, 175, 5), RANDOM(150, 50);
private int spikeUpperBound;
private int spikeBase;
private int spikeCount;
private int upperBound = 49;
private int base = 50;
private double divisor;
TurnipPattern() {
}
TurnipPattern(int upperBound, int base) {
this.upperBound = upperBound;
this.base = base;
}
TurnipPattern(int spikeCount, int spikeBase, int spikeUpperBound, double divisor) {
this.spikeCount = spikeCount;
this.spikeBase = spikeBase;
this.spikeUpperBound = spikeUpperBound;
this.divisor = divisor;
}
public static TurnipPattern getRandomTurnipPattern(long seed) {
Random random = new Random(seed);
return values()[random.nextInt(values().length)];
}
}
| package com.nincraft.ninbot.components.ac;
import lombok.Getter;
import java.util.Random;
@Getter
public enum TurnipPattern {
DECREASING, BIG_SPIKE(3, 100, 400, 1.5), SMALL_SPIKE(4, 65, 175, 5), RANDOM(150, 50);
private int spikeUpperBound;
private int spikeBase;
private int spikeCount;
private int upperBound = 100;
private int base = 50;
private double divisor;
TurnipPattern() {
}
TurnipPattern(int upperBound, int base) {
this.upperBound = upperBound;
this.base = base;
}
TurnipPattern(int spikeCount, int spikeBase, int spikeUpperBound, double divisor) {
this.spikeCount = spikeCount;
this.spikeBase = spikeBase;
this.spikeUpperBound = spikeUpperBound;
this.divisor = divisor;
}
public static TurnipPattern getRandomTurnipPattern(long seed) {
Random random = new Random(seed);
return values()[random.nextInt(values().length)];
}
}
|
Fix a bug - salome.py is not imported here and this causes run-time Python exception | from meshpy import *
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
aFilterMgr = smesh.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1);
| import SMESH
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
aFilterMgr = aMeshGen.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1);
|
Enforce the existence of the Cache Directory at StartUp | var FileSystemHelper = require('./FileSystemHelper');
/**
* Provides default values and verifies that requied values are set.
*/
var DefaultOptions = function() {}
DefaultOptions.prototype.options = {
cacheDir: null,
port: process.env.MOCKINGJAYS_PORT || 9000,
serverBaseUrl: null
}
DefaultOptions.prototype.merge = function(options) {
var defaults = this.options;
// Directory where the cache files can be read and written to:
options.cacheDir = options.cacheDir || defaults.cacheDir;
if (!options.cacheDir) {
throw Error("cacheDir is required! It can not be empty.");
}
if (!FileSystemHelper.directoryExists(options.cacheDir)) {
console.warn('Cache Directory Does not Exists.')
console.warn('Attempting to Create: ', options.cacheDir);
FileSystemHelper
.createDirectory(options.cacheDir)
.catch(function() {
throw Error("Please Use a Writable Location for the Cache Directory.");
});
}
// The PORT where the server should bind.
options.port = options.port || defaults.port;
// The base URL of the server to proxy requests to.
options.serverBaseUrl = options.serverBaseUrl || defaults.serverBaseUrl;
if (!options.serverBaseUrl) {
throw Error("serverBaseUrl is required! It can not be empty.");
}
return options
}
module.exports = DefaultOptions
| /**
* Provides default values and verifies that requied values are set.
*/
var DefaultOptions = function() {}
DefaultOptions.prototype.options = {
cacheDir: null,
port: process.env.MOCKINGJAYS_PORT || 9000,
serverBaseUrl: null
}
DefaultOptions.prototype.merge = function(options) {
var defaults = this.options;
// Directory where the cache files can be read and written to:
options.cacheDir = options.cacheDir || defaults.cacheDir;
if (!options.cacheDir) {
throw Error("cacheDir is required! It can not be empty.");
}
// The PORT where the server should bind.
options.port = options.port || defaults.port;
// The base URL of the server to proxy requests to.
options.serverBaseUrl = options.serverBaseUrl || defaults.serverBaseUrl;
if (!options.serverBaseUrl) {
throw Error("serverBaseUrl is required! It can not be empty.");
}
return options
}
module.exports = DefaultOptions
|
Make the factory available to the usage simulator
Fixes #6 | <?php
/**
* Simulate plugin usage.
*
* @package WP_Plugin_Uninstall_Tester
* @since 0.1.0
*/
/**
* Load the main plugin file as if it was active in plugin usage simulation.
*
* @since 0.1.0
*/
function _wp_plugin_unintsall_tester_load_plugin_file() {
require $GLOBALS['argv'][1];
}
/**
* Load the WordPress tests functions.
*
* We are loading this so that we can add our tests filter to load the plugin, using
* tests_add_filter().
*
* @since 0.1.0
*/
require_once getenv( 'WP_TESTS_DIR' ) . 'includes/functions.php';
tests_add_filter( 'muplugins_loaded', '_wp_plugin_unintsall_tester_load_plugin_file' );
$simulation_file = $argv[2];
$config_file_path = $argv[3];
$is_multisite = $argv[4];
require dirname( __FILE__ ) . '/bootstrap.php';
/**
* Load the WP unit test factories.
*
* Use the $wp_test_factory global to create users, posts, etc., the same way that
* you use the $factory propety in WP unit test case classes.
*
* @since 0.2.0
*/
require_once getenv( 'WP_TESTS_DIR' ) . 'includes/factory.php';
$GLOBALS['wp_test_factory'] = new WP_UnitTest_Factory;
require $simulation_file;
| <?php
/**
* Simulate plugin usage.
*
* @package WP_Plugin_Uninstall_Tester
* @since 0.1.0
*/
/**
* Load the main plugin file as if it was active in plugin usage simulation.
*
* @since 0.1.0
*/
function _wp_plugin_unintsall_tester_load_plugin_file() {
require $GLOBALS['argv'][1];
}
/**
* Load the WordPress tests functions.
*
* We are loading this so that we can add our tests filter to load the plugin, using
* tests_add_filter().
*
* @since 0.1.0
*/
require_once getenv( 'WP_TESTS_DIR' ) . 'includes/functions.php';
tests_add_filter( 'muplugins_loaded', '_wp_plugin_unintsall_tester_load_plugin_file' );
$simulation_file = $argv[2];
$config_file_path = $argv[3];
$is_multisite = $argv[4];
require dirname( __FILE__ ) . '/bootstrap.php';
require $simulation_file;
|
Use max polling delay to avoid OSErrors | # Just to insure requirement
import colorlog # noqa
# Development mode: use a local OSF dev version and more granular logging
DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests`
# General settings
PROJECT_NAME = 'osf-offline'
PROJECT_AUTHOR = 'cos'
APPLICATION_SCOPES = 'osf.full_write'
# Base URL for API server; used to fetch data
API_BASE = 'https://staging-api.osf.io'
FILE_BASE = 'https://staging-files.osf.io'
# Interval (in seconds) to poll the OSF for server-side file changes
# YEARS * DAYS * HOURS * MIN * SECONDS
POLL_DELAY = 24 * 60 * 60 # Once per day
# Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms
ALERT_TIME = 1000 # ms
LOG_LEVEL = 'INFO'
# Logging configuration
CONSOLE_FORMATTER = {
'()': 'colorlog.ColoredFormatter',
'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s'
}
FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
| # Just to insure requirement
import colorlog # noqa
# Development mode: use a local OSF dev version and more granular logging
DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests`
# General settings
PROJECT_NAME = 'osf-offline'
PROJECT_AUTHOR = 'cos'
APPLICATION_SCOPES = 'osf.full_write'
# Base URL for API server; used to fetch data
API_BASE = 'https://staging-api.osf.io'
FILE_BASE = 'https://staging-files.osf.io'
# Interval (in seconds) to poll the OSF for server-side file changes
# YEARS * DAYS * HOURS * MIN * SECONDS
POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds
# Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms
ALERT_TIME = 1000 # ms
LOG_LEVEL = 'INFO'
# Logging configuration
CONSOLE_FORMATTER = {
'()': 'colorlog.ColoredFormatter',
'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s'
}
FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
|
Improve the docstring of AdditiveGaussian | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
| from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
Update Tweet method for api change | import tweepy
import time
class TwitterBot:
def __init__(self, auth, listen_msg, response_msg):
auth = tweepy.OAuthHandler(auth['consumer_key'], auth['consumer_secret'])
auth.set_access_token(auth['access_token'], auth['access_token_secret'])
self.api = tweepy.API(auth)
self.responded_tweets = set()
self.listen, self.response = listen_msg, response_msg
def tweet(self, message, mention_id=None):
self.api.update_status(status=message, in_reply_to_status_id=mention_id)
def respond(self, mention_text, message):
for mention in self.api.mentions_timeline(count=1):
if mention_text in mention.text.lower():
self.tweet(message.format(mention.user.screen_name), mention.id)
self.api.create_favorite(mention.id)
print('Responded to {0}.'.format(mention.user.screen_name))
if __name__ == '__main__':
tb = TwitterBot()
tb.respond('hi', '{} hey buddy!')
| import tweepy
import time
class TwitterBot:
def __init__(self, auth, listen_msg, response_msg):
auth = tweepy.OAuthHandler(auth['consumer_key'], auth['consumer_secret'])
auth.set_access_token(auth['access_token'], auth['access_token_secret'])
self.api = tweepy.API(auth)
self.responded_tweets = set()
self.listen, self.response = listen_msg, response_msg
def tweet(self, message, mention_id=None):
self.api.update_status(status=message, mention_id=mention_id)
def respond(self, mention_text, message):
for mention in self.api.mentions_timeline(count=1):
if mention_text in mention.text.lower():
self.tweet(message.format(mention.user.screen_name), mention.id)
self.api.create_favorite(mention.id)
print('Responded to {0}.'.format(mention.user.screen_name))
if __name__ == '__main__':
tb = TwitterBot()
tb.respond('hi', '{} hey buddy!')
|
Remove the PGPASSWORD requirement for tests.
If they're required and the value is missing, the test will fail. There's
no need to enforce that in the test itself. | package postgresql
import (
"os"
"testing"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
var testAccProviders map[string]terraform.ResourceProvider
var testAccProvider *schema.Provider
func init() {
testAccProvider = Provider().(*schema.Provider)
testAccProviders = map[string]terraform.ResourceProvider{
"postgresql": testAccProvider,
}
}
func TestProvider(t *testing.T) {
if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvider_impl(t *testing.T) {
var _ terraform.ResourceProvider = Provider()
}
func testAccPreCheck(t *testing.T) {
var host string
if host = os.Getenv("PGHOST"); host == "" {
t.Fatal("PGHOST must be set for acceptance tests")
}
if v := os.Getenv("PGUSER"); v == "" {
t.Fatal("PGUSER must be set for acceptance tests")
}
}
| package postgresql
import (
"os"
"testing"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
var testAccProviders map[string]terraform.ResourceProvider
var testAccProvider *schema.Provider
func init() {
testAccProvider = Provider().(*schema.Provider)
testAccProviders = map[string]terraform.ResourceProvider{
"postgresql": testAccProvider,
}
}
func TestProvider(t *testing.T) {
if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvider_impl(t *testing.T) {
var _ terraform.ResourceProvider = Provider()
}
func testAccPreCheck(t *testing.T) {
var host string
if host = os.Getenv("PGHOST"); host == "" {
t.Fatal("PGHOST must be set for acceptance tests")
}
if v := os.Getenv("PGUSER"); v == "" {
t.Fatal("PGUSER must be set for acceptance tests")
}
if v := os.Getenv("PGPASSWORD"); v == "" && host != "localhost" {
t.Fatal("PGPASSWORD must be set for acceptance tests if PGHOST is not localhost")
}
}
|
Bump version number to 0.2.2 | import os
from setuptools import setup, find_packages
version = '0.2.2'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-templatepages',
version = version,
description = "Django app for mapping URLs to templates on the filesystem",
long_description = read('README.rst'),
classifiers = [],
keywords = "",
author = "Bryan Chow",
author_email = '',
url = 'https://github.com/bryanchow/django-templatepages',
download_url = 'https://github.com/bryanchow/django-templatepages/tarball/master',
license = 'BSD',
packages = find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data = True,
zip_safe = False,
install_requires = [
'django',
],
)
| import os
from setuptools import setup, find_packages
version = '0.2.1'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-templatepages',
version = version,
description = "Django app for mapping URLs to templates on the filesystem",
long_description = read('README.rst'),
classifiers = [],
keywords = "",
author = "Bryan Chow",
author_email = '',
url = 'https://github.com/bryanchow/django-templatepages',
download_url = 'https://github.com/bryanchow/django-templatepages/tarball/master',
license = 'BSD',
packages = find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data = True,
zip_safe = False,
install_requires = [
'django',
],
)
|
Switch if-else block to dictionary lookup | from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
MANAGER_MAP = {
'pip': Pip,
'pip3': Pip3,
'pip_pypy': PipPypy,
'sys': Apt,
'npm': Npm,
'npmg': NpmG,
'bower': Bower,
'tsd': Tsd
}
PRIVATE_MANAGER_MAP = {
'pip': PrivatePip
}
def manager_key_to_cappa(manager_key):
if manager_key in MANAGER_MAP:
return MANAGER_MAP[manager_key]
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
if manager_key in PRIVATE_MANAGER_MAP:
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key))
| from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
def manager_key_to_cappa(manager_key):
if manager_key == 'pip':
return Pip
elif manager_key == 'pip3':
return Pip3
elif manager_key == 'pip_pypy':
return PipPypy
elif manager_key == 'sys':
return Apt
elif manager_key == 'npm':
return Npm
elif manager_key == 'npmg':
return NpmG
elif manager_key == 'bower':
return Bower
elif manager_key == 'tsd':
return Tsd
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
if manager_key == 'pip':
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key))
|
Update dsub version to 0.4.4.dev0
PiperOrigin-RevId: 344150311 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.4.dev0'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.3'
|
Check is user already signed up. | /*jslint white: true */
'use strict';
function SignupController($location, $scope, $routeParams, authenticateRequest, errorHandler, httpRequest, itemsRequest, userSession) {
$scope.user = {};
var inviteResponseCode;
$scope.errorHandler = errorHandler;
httpRequest.get('/api/invite/' + $routeParams.hex_code + '?email=' + $routeParams.email).then(function(inviteResponse) {
if (inviteResponse.data.accepted) {
$location.path('/login');
} else {
$scope.user.email = inviteResponse.data.email;
inviteResponseCode = inviteResponse.data.code;
}
});
function userLogin() {
userSession.setCredentials($scope.user.email, $scope.user.password);
authenticateRequest.login().then(function(authenticateResponse) {
userSession.setUserSessionData(authenticateResponse);
itemsRequest.getItems();
$location.path('/my');
}, function(authenticateResponse) {
$scope.errorHandler.errorMessage = authenticateResponse.data;
});
}
$scope.signUp = function() {
httpRequest.post('/api/invite/' + inviteResponseCode, {email: $scope.user.email, password: $scope.user.password}).then(function() {
userLogin();
});
};
}
SignupController.$inject = ['$location', '$scope', '$routeParams', 'authenticateRequest', 'errorHandler', 'httpRequest', 'itemsRequest', 'userSession'];
angular.module('em.app').controller('SignupController', SignupController);
| /*jslint white: true */
'use strict';
function SignupController($location, $scope, $routeParams, authenticateRequest, errorHandler, httpRequest, itemsRequest, userSession) {
$scope.user = {};
var inviteResponseCode;
$scope.errorHandler = errorHandler;
httpRequest.get('/api/invite/' + $routeParams.hex_code + '?email=' + $routeParams.email).then(function(inviteResponse) {
$scope.user.email = inviteResponse.data.email;
inviteResponseCode = inviteResponse.data.code;
});
function userLogin() {
userSession.setCredentials($scope.user.email, $scope.user.password);
authenticateRequest.login().then(function(authenticateResponse) {
userSession.setUserSessionData(authenticateResponse);
itemsRequest.getItems();
$location.path('/my');
}, function(authenticateResponse) {
$scope.errorHandler.errorMessage = authenticateResponse.data;
});
}
$scope.signUp = function() {
httpRequest.post('/api/invite/' + inviteResponseCode, {email: $scope.user.email, password: $scope.user.password}).then(function() {
userLogin();
});
};
}
SignupController.$inject = ['$location', '$scope', '$routeParams', 'authenticateRequest', 'errorHandler', 'httpRequest', 'itemsRequest', 'userSession'];
angular.module('em.app').controller('SignupController', SignupController);
|
Handle the No Data case. | /**
* Created by mgab on 14/05/2017.
*/
import React,{ Component } from 'react'
import Title from './common/styled-components/Title'
import Lottery from './Lottery'
export default class Lotteries extends Component {
render() {
const lotteriesToDisplay = []
if (this.props.lotteriesData) {
this.props.lotteriesData.map((lottery) => {
return lotteriesToDisplay.push(<Lottery name={lottery.getIn(['id'], '')}
jackpot={lottery.getIn(['jackpots'], [])[0]}
drawingDate={lottery.getIn(['drawingDate'], '')}
key={Math.random()} />)
})
}
return (
<div>
<Title>Lotteries</Title>
<div>
{lotteriesToDisplay.length > 0 ? lotteriesToDisplay : 'No data.'}
</div>
</div>
)
}
} | /**
* Created by mgab on 14/05/2017.
*/
import React,{ Component } from 'react'
import Title from './common/styled-components/Title'
import Lottery from './Lottery'
export default class Lotteries extends Component {
render() {
const lotteriesToDisplay = []
if (this.props.lotteriesData) {
this.props.lotteriesData.map((lottery) => {
lotteriesToDisplay.push(<Lottery name={lottery.getIn(['id'], '')}
jackpot={lottery.getIn(['jackpots'], [])[0]}
drawingDate={lottery.getIn(['drawingDate'], '')}
key={Math.random()} />)
})
}
return (
<div>
<Title>Lotteries</Title>
<div>
{lotteriesToDisplay && 'No data.'}
</div>
</div>
)
}
} |
Use expected identifier as actual if no match can be found. | package no.steria.skuldsku.testrunner.common;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import no.steria.skuldsku.testrunner.httprunner.result.HttpCallResult;
public final class HttpClientIdentifierMapper implements ClientIdentifierMapper {
private final Map<String, String> map;
public HttpClientIdentifierMapper(List<HttpCallResult> results) {
map = new HashMap<>();
for (HttpCallResult r : results) {
map.put(r.getExpected().getClientIdentifier(), r.getActual().getClientIdentifier());
}
map.put(null, null);
map.put("", "");
}
@Override
public String translateToActual(String expectedClientIdentifier) {
final String value = map.get(expectedClientIdentifier);
return (value != null) ? value : expectedClientIdentifier;
}
}
| package no.steria.skuldsku.testrunner.common;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import no.steria.skuldsku.testrunner.httprunner.result.HttpCallResult;
public final class HttpClientIdentifierMapper implements ClientIdentifierMapper {
private final Map<String, String> map;
public HttpClientIdentifierMapper(List<HttpCallResult> results) {
map = new HashMap<>();
for (HttpCallResult r : results) {
map.put(r.getExpected().getClientIdentifier(), r.getActual().getClientIdentifier());
}
map.put(null, null);
map.put("", "");
}
@Override
public String translateToActual(String expectedClientIdentifier) {
return map.get(expectedClientIdentifier);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.