text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use of @component for buttons in form
|
@section('js')
<script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script>
@endsection
@component('core::admin._buttons-form', ['model' => $model])
@endcomponent
{!! BootForm::hidden('id') !!}
@include('core::admin._image-fieldset', ['field' => 'image'])
@include('core::form._title-and-slug')
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
<div class="row">
<div class="col-sm-6">
{!! BootForm::text(__('Start date'), 'start_date')->value(old('start_date') ? : $model->present()->datetimeOrNow('start_date'))->addClass('datetimepicker') !!}
</div>
<div class="col-sm-6">
{!! BootForm::text(__('End date'), 'end_date')->value(old('end_date') ? : $model->present()->datetimeOrNow('end_date'))->addClass('datetimepicker') !!}
</div>
</div>
{!! TranslatableBootForm::text(__('Venue'), 'venue') !!}
{!! TranslatableBootForm::textarea(__('Address'), 'address')->rows(4) !!}
{!! TranslatableBootForm::textarea(__('Summary'), 'summary')->rows(4) !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}
|
@section('js')
<script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script>
@endsection
@include('core::admin._buttons-form')
{!! BootForm::hidden('id') !!}
@include('core::admin._image-fieldset', ['field' => 'image'])
@include('core::form._title-and-slug')
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
<div class="row">
<div class="col-sm-6">
{!! BootForm::text(__('Start date'), 'start_date')->value(old('start_date') ? : $model->present()->datetimeOrNow('start_date'))->addClass('datetimepicker') !!}
</div>
<div class="col-sm-6">
{!! BootForm::text(__('End date'), 'end_date')->value(old('end_date') ? : $model->present()->datetimeOrNow('end_date'))->addClass('datetimepicker') !!}
</div>
</div>
{!! TranslatableBootForm::text(__('Venue'), 'venue') !!}
{!! TranslatableBootForm::textarea(__('Address'), 'address')->rows(4) !!}
{!! TranslatableBootForm::textarea(__('Summary'), 'summary')->rows(4) !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}
|
Check if world is remote so event isn't fired for single player entity tick
|
package com.matt.forgehax.mods.services;
import static com.matt.forgehax.Helper.getLocalPlayer;
import static com.matt.forgehax.Helper.getWorld;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.mod.ServiceMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingEvent;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
/** Created on 6/14/2017 by fr1kin */
@RegisterMod
public class LocalPlayerUpdateEventService extends ServiceMod {
public LocalPlayerUpdateEventService() {
super("LocalPlayerUpdateEventService");
}
@SubscribeEvent
public void onUpdate(LivingEvent.LivingUpdateEvent event) {
if (getWorld() != null
&& !getWorld().isRemote
&& event.getEntityLiving().equals(getLocalPlayer())) {
Event ev = new LocalPlayerUpdateEvent(event.getEntityLiving());
MinecraftForge.EVENT_BUS.post(ev);
event.setCanceled(ev.isCanceled());
}
}
}
|
package com.matt.forgehax.mods.services;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.mod.ServiceMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingEvent;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
/** Created on 6/14/2017 by fr1kin */
@RegisterMod
public class LocalPlayerUpdateEventService extends ServiceMod {
public LocalPlayerUpdateEventService() {
super("LocalPlayerUpdateEventService");
}
@SubscribeEvent
public void onUpdate(LivingEvent.LivingUpdateEvent event) {
if (MC.world != null && event.getEntityLiving().equals(MC.player)) {
Event ev = new LocalPlayerUpdateEvent(event.getEntityLiving());
MinecraftForge.EVENT_BUS.post(ev);
event.setCanceled(ev.isCanceled());
}
}
}
|
Remove whitespace from top of file
Remove the unnecessary space at the top of the file before
the first code declaration.
|
var valid = function(el) {
// jquery the selector
var $el = $(el);
// narrow selection to only these validations
var $els = $el.find('[data-valid-required], [data-valid-pattern]');
// storage array to return
var arr = [];
// check for errors
var getError = function(element) {
// jquery the selector
var $element = $(element);
// trim the whitespace on inputs
var $value = $.trim($element.val());
// set the default error
var error = false;
var type = 'required';
// test the regex pattern
if ($element.data('valid-pattern')) {
type = 'pattern';
var regex = new RegExp($element.data('valid-pattern'));
// test() will return true for a match
// want to reverse that so it reads like english
// i.e. if there is an error, set error to true
error = ! regex.test($element.val());
}
// this will check for an empty value
// covers the required case
if ($value.length === 0) {
error = true;
}
if (!error) {
return false;
}
return {
'element' : $element[0],
'type' : type
};
};
$.each($els, function() {
var $el = $(this);
var err = getError($el);
if (err) {
arr.push(err);
}
});
return arr;
};
|
var valid = function(el) {
// jquery the selector
var $el = $(el);
// narrow selection to only these validations
var $els = $el.find('[data-valid-required], [data-valid-pattern]');
// storage array to return
var arr = [];
// check for errors
var getError = function(element) {
// jquery the selector
var $element = $(element);
// trim the whitespace on inputs
var $value = $.trim($element.val());
// set the default error
var error = false;
var type = 'required';
// test the regex pattern
if ($element.data('valid-pattern')) {
type = 'pattern';
var regex = new RegExp($element.data('valid-pattern'));
// test() will return true for a match
// want to reverse that so it reads like english
// i.e. if there is an error, set error to true
error = ! regex.test($element.val());
}
// this will check for an empty value
// covers the required case
if ($value.length === 0) {
error = true;
}
if (!error) {
return false;
}
return {
'element' : $element[0],
'type' : type
};
};
$.each($els, function() {
var $el = $(this);
var err = getError($el);
if (err) {
arr.push(err);
}
});
return arr;
};
|
Make URL a string because of iOS build problems.
|
/****************************************************************************
* Copyright (C) 2019 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH (info@ecsec.de)
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.mobile.activation;
import java.util.Set;
import org.openecard.robovm.annotations.FrameworkInterface;
/**
*
* @author Neil Crossley
*/
@FrameworkInterface
public interface EacControllerFactory {
ActivationController create(String url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction);
void destroy(ActivationController controller);
}
|
/****************************************************************************
* Copyright (C) 2019 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH (info@ecsec.de)
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.mobile.activation;
import java.net.URL;
import java.util.Set;
import org.openecard.robovm.annotations.FrameworkInterface;
/**
*
* @author Neil Crossley
*/
@FrameworkInterface
public interface EacControllerFactory {
ActivationController create(URL url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction);
void destroy(ActivationController controller);
}
|
Check that logging config file path is set.
|
package io.github.oliviercailloux.javase_maven_jul_hib_h2.launch;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import io.github.oliviercailloux.javase_maven_jul_hib_h2.entities.MyEntity;
public class Launcher {
@SuppressWarnings("unused")
private static final Logger LOGGER = Logger.getLogger(Launcher.class.getCanonicalName());
public static void main(String[] args) {
final String loggingConfigFilePathProperty = "java.util.logging.config.file";
final String loggingConfigFilePathValue = System.getProperty(loggingConfigFilePathProperty);
if (loggingConfigFilePathValue == null) {
LOGGER.warning("Property " + loggingConfigFilePathProperty
+ " not set. Logging will use its default configuration.");
}
LOGGER.info("Starting.");
new Launcher().launch();
}
public void launch() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyUnit");
EntityManager em1 = factory.createEntityManager();
EntityTransaction tx = em1.getTransaction();
tx.begin();
MyEntity myEntity = new MyEntity();
em1.persist(myEntity);
LOGGER.info("New entity id: " + myEntity.getId() + ".");
tx.commit();
tx.begin();
myEntity.setName("MyName");
tx.commit();
em1.close();
factory.close();
}
}
|
package io.github.oliviercailloux.javase_maven_jul_hib_h2.launch;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import io.github.oliviercailloux.javase_maven_jul_hib_h2.entities.MyEntity;
public class Launcher {
@SuppressWarnings("unused")
private static final Logger LOGGER = Logger.getLogger(Launcher.class.getCanonicalName());
public static void main(String[] args) {
LOGGER.info("Starting.");
new Launcher().launch();
}
public void launch() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyUnit");
EntityManager em1 = factory.createEntityManager();
EntityTransaction tx = em1.getTransaction();
tx.begin();
MyEntity myEntity = new MyEntity();
em1.persist(myEntity);
LOGGER.info("New entity id: " + myEntity.getId() + ".");
tx.commit();
tx.begin();
myEntity.setName("MyName");
tx.commit();
em1.close();
factory.close();
}
}
|
Refactor and add flow types
|
// @flow
import { times, uniq, compose, length } from 'ramda';
import { getRandomNumber, generatePassword } from '../../src/helpers/password';
const createArrayOfRandomNumbers = (min: number, max: number, count: number): Function =>
times((): number => getRandomNumber(min, max), count);
const countUniqueValuesInArray = compose(length, uniq, createArrayOfRandomNumbers);
test('Generates a random number between two numbers', () => {
// generates a number that is lower than max and higher than min
expect(getRandomNumber(1, 5)).toBeGreaterThanOrEqual(1);
expect(getRandomNumber(1, 5)).toBeLessThanOrEqual(5);
// for a maximum of 5, at least 2 numbers should be different
expect(countUniqueValuesInArray(1, 5, 5)).toBeGreaterThanOrEqual(2);
// for a maximum of 100, at least 50 numbers should be different
expect(countUniqueValuesInArray(1, 100, 100)).toBeGreaterThanOrEqual(50);
});
test('Generate a random password', () => {
const password = generatePassword(5);
expect(password).toMatch(/\w/g);
expect(password.split(' ').length).toEqual(5);
});
|
import { getRandomNumber, generatePassword } from '../../src/helpers/password';
const R = require('ramda');
// Get rid of this and refactor
const repeat = (fn, arg1, arg2, count) => {
const arr = [];
for (let i = 0; i < count; i += 1) {
arr.push(fn(arg1, arg2));
}
return arr;
};
test('Generates a random number between two numbers', () => {
// generates a number that is lower than max and higher than min
expect(getRandomNumber(1, 5)).toBeGreaterThanOrEqual(1);
expect(getRandomNumber(1, 5)).toBeLessThanOrEqual(5);
// for a maximum of 5, at least 3 numbers should be different
const arr = repeat(getRandomNumber, 1, 5, 5);
expect(R.uniq(arr).length).toBeGreaterThan(1);
// for a maximum of 100, at least 50 numbers should be different
const arr2 = repeat(getRandomNumber, 1, 100, 100);
expect(R.uniq(arr2).length).toBeGreaterThan(49);
});
test('Generate a random password', () => {
const password = generatePassword(5);
expect(password).toMatch(/\w/g);
expect(password.split(' ').length).toEqual(5);
});
|
Correct signature for updateConversationLoader params
|
import { GraphQLString, GraphQLNonNull } from "graphql"
import { mutationWithClientMutationId } from "graphql-relay"
import Conversation from "schema/me/conversation"
export default mutationWithClientMutationId({
name: "UpdateConversationMutation",
description: "Update a conversation.",
inputFields: {
conversationId: {
type: new GraphQLNonNull(GraphQLString),
description: "The id of the conversation to be updated.",
},
fromLastViewedMessageId: {
type: new GraphQLNonNull(GraphQLString),
description: "The message id to mark as read.",
},
},
outputFields: {
conversation: {
type: Conversation.type,
resolve: conversation => conversation,
},
},
mutateAndGetPayload: (
{ conversationId, fromLastViewedMessageId },
request,
{ rootValue: { conversationUpdateLoader } }
) => {
if (!conversationUpdateLoader) return null
return conversationUpdateLoader(conversationId, {
from_last_viewed_message_id: fromLastViewedMessageId,
})
},
})
|
import { GraphQLString, GraphQLNonNull } from "graphql"
import { mutationWithClientMutationId } from "graphql-relay"
import Conversation from "schema/me/conversation"
export default mutationWithClientMutationId({
name: "UpdateConversationMutation",
description: "Update a conversation.",
inputFields: {
conversationId: {
type: new GraphQLNonNull(GraphQLString),
description: "The id of the conversation to be updated.",
},
fromLastViewedMessageId: {
type: new GraphQLNonNull(GraphQLString),
description: "The message id to mark as read.",
},
},
outputFields: {
conversation: {
type: Conversation.type,
resolve: conversation => conversation,
},
},
mutateAndGetPayload: (
{ conversationId, fromLastViewedMessageId },
request,
{ rootValue: { conversationUpdateLoader } }
) => {
if (!conversationUpdateLoader) return null
return conversationUpdateLoader({
conversation_id: conversationId,
from_last_viewed_message_id: fromLastViewedMessageId,
})
},
})
|
Change failure to an alert message.
|
$(document).ready( function () {
$(".upvote").click( function(event) {
var responseId = $(this).data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: responseId },
dataType: 'JSON'
}).done( function (voteCount) {
if (voteCount == 1) {
$("span[data-id=" + responseId + "]").html(voteCount + " vote");
} else {
$("span[data-id=" + responseId + "]").html(voteCount + " vote");
}
}).fail( function (failureResponse) {
alert("You already voted for this response.");
console.log(failureResponse);
})
})
})
|
$(document).ready( function () {
$(".upvote").click( function(event) {
var responseId = $(this).data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: responseId },
dataType: 'JSON'
}).done( function (voteCount) {
if (voteCount == 1) {
$("span[data-id=" + responseId + "]").html(voteCount + " vote");
} else {
$("span[data-id=" + responseId + "]").html(voteCount + " vote");
}
}).fail( function (voteCount) {
console.log("Failed. Here is the voteCount:");
console.log(voteCount);
})
})
})
|
Update AudioChannel.playSong to use noteToFreq
|
var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
var args = args ? args : {};
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wave : "triangle";
this.volume = args.gain ? args.gain : 0.05;
}
AudioChannel.prototype.setNodes = function() {
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
this.oscill.connect(this.gain);
this.gain.connect(this.context.destination);
this.oscill.frequency.value = this.frequency;
this.oscill.type = this.wave;
this.gain.gain.value = this.volume;
};
AudioChannel.prototype.playSong = function(song) {
this.setNodes();
this.oscill.start();
var playNextNote = function(song) {
this.oscill.frequency.value = noteToFreq(song[0].note, song[0].octave);
if(song[1]) {
setTimeout(playNextNote.bind(this, song.slice(1)), song[0].length);
}
else {
setTimeout(function() {
this.gain.gain.value = 0;
}.bind(this), song[0].length);
}
}.bind(this);
playNextNote(song);
};
|
var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
if(args) {
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wave : "triangle";
this.volume = args.gain ? args.gain : 0.05;
}
}
AudioChannel.prototype.setNodes = function() {
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
this.oscill.connect(this.gain);
this.gain.connect(this.context.destination);
this.oscill.frequency.value = this.frequency;
this.oscill.type = this.wave;
this.gain.gain.value = this.volume;
};
AudioChannel.prototype.playSong = function(song) {
this.oscill.start();
var playNextNote = function(song) {
this.oscill.frequency.value = song[0].freq;
if(song[1]) {
setTimeout(playNextNote.bind(this, song.slice(1)), song[0].length);
}
else {
setTimeout(function() {
this.gain.gain.value = 0;
}.bind(this), song[0].length);
}
}.bind(this);
playNextNote(song);
};
|
Update blogroll and social links.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'IPython development team and Enthought, Inc.'
SITENAME = u'DistArray'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('NumPy', 'http://www.numpy.org/'),
('SciPy', 'http://www.scipy.org'),
('IPython', 'http://ipython.org/'),
('Enthought', 'http://www.enthought.com/'),
)
# Social widget
SOCIAL = (('github', 'https://github.com/enthought/distarray'),)
DEFAULT_PAGINATION = False
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'IPython development team and Enthought, Inc.'
SITENAME = u'DistArray'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('Python.org', 'http://python.org/'),
('Jinja2', 'http://jinja.pocoo.org/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = False
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
|
Add missing @EnableDiscoveryClient in standalone server sample
|
/*
* Copyright © 2017 the original authors (http://cereebro.io)
*
* 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 io.cereebro.sample.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import io.cereebro.server.EnableCereebroServer;
@SpringBootApplication
@EnableCereebroServer
@EnableDiscoveryClient
public class CereebroSampleServerEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(CereebroSampleServerEurekaClientApplication.class, args);
}
}
|
/*
* Copyright © 2017 the original authors (http://cereebro.io)
*
* 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 io.cereebro.sample.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import io.cereebro.server.EnableCereebroServer;
@SpringBootApplication
@EnableCereebroServer
public class CereebroSampleServerEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(CereebroSampleServerEurekaClientApplication.class, args);
}
}
|
Remove limit for search field
|
from django import forms
from django.db.models import get_model
from django.utils.translation import ugettext as _
StoreAddress = get_model('stores', 'StoreAddress')
class StoreSearchForm(forms.Form):
STATE_CHOICES = (
(_('VIC'), _('Victoria')),
(_('NSW'), _('New South Wales')),
(_('SA'), _('South Australia')),
(_('TAS'), _('Tasmania')),
(_('QLD'), _('Queensland')),
(_('NT'), _('Northern Territory')),
)
location = forms.CharField(widget=forms.HiddenInput)
store_search = forms.CharField(
widget=forms.TextInput(
attrs={'placeholder': _("Enter your postcode or suburb...")}
)
)
state = forms.ChoiceField(choices=STATE_CHOICES)
|
from django import forms
from django.db.models import get_model
from django.utils.translation import ugettext as _
StoreAddress = get_model('stores', 'StoreAddress')
class StoreSearchForm(forms.Form):
STATE_CHOICES = (
(_('VIC'), _('Victoria')),
(_('NSW'), _('New South Wales')),
(_('SA'), _('South Australia')),
(_('TAS'), _('Tasmania')),
(_('QLD'), _('Queensland')),
(_('NT'), _('Northern Territory')),
)
location = forms.CharField(widget=forms.HiddenInput)
store_search = forms.CharField(
max_length=4,
widget=forms.TextInput(attrs={'placeholder': _("Enter your postcode or suburb...")})
)
state = forms.ChoiceField(choices=STATE_CHOICES)
|
Fix NullPointerException when output base is null
|
package org.icij.extract.core;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import java.nio.charset.Charset;
import java.util.logging.Logger;
import org.apache.tika.parser.ParsingReader;
import org.apache.tika.exception.TikaException;
/**
* Extract
*
* @author Matthew Caruana Galizia <mcaruana@icij.org>
* @version 1.0.0-beta
* @since 1.0.0-beta
*/
public abstract class Spewer {
protected final Logger logger;
private Path outputBase = null;
public Spewer(Logger logger) {
this.logger = logger;
}
public abstract void write(Path file, ParsingReader reader, Charset outputEncoding) throws IOException, TikaException, SpewerException;
public void setOutputBase(Path outputBase) {
this.outputBase = outputBase;
}
public void setOutputBase(String outputBase) {
setOutputBase(FileSystems.getDefault().getPath(outputBase));
}
public Path filterOutputPath(Path file) {
if (null != outputBase && file.startsWith(outputBase)) {
return file.subpath(outputBase.getNameCount(), file.getNameCount());
}
return file;
}
public void finish() throws IOException {
logger.info("Spewer finishing pending jobs.");
}
}
|
package org.icij.extract.core;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import java.nio.charset.Charset;
import java.util.logging.Logger;
import org.apache.tika.parser.ParsingReader;
import org.apache.tika.exception.TikaException;
/**
* Extract
*
* @author Matthew Caruana Galizia <mcaruana@icij.org>
* @version 1.0.0-beta
* @since 1.0.0-beta
*/
public abstract class Spewer {
protected final Logger logger;
private Path outputBase = null;
public Spewer(Logger logger) {
this.logger = logger;
}
public abstract void write(Path file, ParsingReader reader, Charset outputEncoding) throws IOException, TikaException, SpewerException;
public void setOutputBase(Path outputBase) {
this.outputBase = outputBase;
}
public void setOutputBase(String outputBase) {
setOutputBase(FileSystems.getDefault().getPath(outputBase));
}
public Path filterOutputPath(Path file) {
if (file.startsWith(outputBase)) {
return file.subpath(outputBase.getNameCount(), file.getNameCount());
}
return file;
}
public void finish() throws IOException {
logger.info("Spewer finishing pending jobs.");
}
}
|
Convert LocalDateTime expected output to ISO-8601, since there's no timezone in LocalDateTime
|
/*
* ******************************************************************************
* Copyright 2016-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.dsbrowser.gui.services;
import org.junit.Test;
import java.time.LocalDateTime;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class BuildInfoService_Test {
@Test
public void parseDateString() {
final String buildDate = "Wed Mar 15 11:10:25 MDT 2017";
final LocalDateTime ldt = LocalDateTime.parse(buildDate, BuildInfoServiceImpl.dtf);
assertThat(ldt.toString(), is("2017-03-15T11:10:25"));
}
}
|
/*
* ******************************************************************************
* Copyright 2016-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.dsbrowser.gui.services;
import org.junit.Test;
import java.time.LocalDateTime;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class BuildInfoService_Test {
@Test
public void parseDateString() {
final String buildDate = "Wed Mar 15 11:10:25 MDT 2017";
final LocalDateTime ldt = LocalDateTime.parse(buildDate, BuildInfoServiceImpl.dtf);
final String formattedDate = ldt.format(BuildInfoServiceImpl.dtf);
//final String formattedDate = ldt.format(BuildInfoServiceImpl.dtf);
assertThat(formattedDate, is(buildDate));
}
}
|
Change package name from 's3' to 'ucldc_iiif'.
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "ucldc-iiif",
version = "0.0.1",
description = ("International Image Interoperability Framework (IIIF) implementation code for the UCLDC project"),
long_description=read('README.md'),
author='Barbara Hui',
author_email='barbara.hui@ucop.edu',
dependency_links=[
'https://github.com/ucldc/pynux/archive/master.zip#egg=pynux',
'https://github.com/barbarahui/nuxeo-calisphere/archive/master.zip#egg=UCLDC-Deep-Harvester'
],
install_requires=[
'boto',
'pynux',
'python-magic',
'UCLDC-Deep-Harvester'
],
packages=['ucldc_iiif'],
test_suite='tests'
)
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "ucldc-iiif",
version = "0.0.1",
description = ("International Image Interoperability Framework (IIIF) implementation code for the UCLDC project"),
long_description=read('README.md'),
author='Barbara Hui',
author_email='barbara.hui@ucop.edu',
dependency_links=[
'https://github.com/ucldc/pynux/archive/master.zip#egg=pynux',
'https://github.com/barbarahui/nuxeo-calisphere/archive/master.zip#egg=UCLDC-Deep-Harvester'
],
install_requires=[
'boto',
'pynux',
'python-magic',
'UCLDC-Deep-Harvester'
],
packages=['s3'],
test_suite='tests'
)
|
Fix for wrong application home path
|
package configurations
import (
"os"
"os/user"
"path"
)
var applicationName = "banksaurus"
// IsDev returns if in dev environment or not
func IsDev() bool {
if os.Getenv("GO_BANK_CLI_DEV") == "true" {
return true
}
return false
}
// DatabasePath returns the path nad name for the database
// taking into account the type of environment
func DatabasePath() (string, string) {
dbName := "bank"
if IsDev() {
return dbName, os.TempDir()
}
return dbName, ApplicationHomePath()
}
// LogPath returns the path to the log file
func LogPath() string {
return path.Join(ApplicationHomePath(), applicationName+".log")
}
// ApplicationHomePath builds the path to application data in the user home,
// something like ~/.bankservices
func ApplicationHomePath() string {
usr, err := user.Current()
if err != nil {
// TODO: no panic here...
panic(err)
}
return path.Join(usr.HomeDir, ".bank")
}
|
package configurations
import (
"os"
"os/user"
"path"
)
var applicationName = "banksaurus"
// IsDev returns if in dev environment or not
func IsDev() bool {
if os.Getenv("GO_BANK_CLI_DEV") == "true" {
return true
}
return false
}
// DatabasePath returns the path nad name for the database
// taking into account the type of environment
func DatabasePath() (string, string) {
dbName := "bank"
if IsDev() {
return dbName, os.TempDir()
}
return dbName, ApplicationHomePath()
}
// LogPath returns the path to the log file
func LogPath() string {
return path.Join(ApplicationHomePath(), applicationName+".log")
}
// ApplicationHomePath builds the path to application data in the user home,
// something like ~/.bankservices
func ApplicationHomePath() string {
usr, err := user.Current()
if err != nil {
// TODO: no panic here...
panic(err)
}
return path.Join(usr.HomeDir, ".bankservices")
}
|
Create generic packr function to get schema
|
package validate
import (
"fmt"
"log"
"os"
"path"
"github.com/gobuffalo/packr"
"github.com/xeipuuv/gojsonschema"
)
// ValidateJSON is used to check for validity
func ValidateJSON(doc string) bool {
file := path.Join("file:///", GetPath(), "/", doc)
s := GetSchema()
schemaLoader := gojsonschema.NewStringLoader(s)
documentLoader := gojsonschema.NewReferenceLoader(file)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
panic(err.Error())
}
if result.Valid() {
fmt.Printf("The document is valid\n")
return true
} else {
fmt.Printf("The document is not valid. see errors :\n")
for _, desc := range result.Errors() {
fmt.Printf("- %s\n", desc)
}
return false
}
}
// GetPath is used to get current path
func GetPath() string {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return dir
}
//GetSchema is used to obtain the string representation of schema.json via packr
func GetSchema() string {
box := packr.NewBox("../../../")
s, err := box.MustString("schema.json")
if err != nil {
panic(err.Error())
}
return s
}
|
package validate
import (
"fmt"
"log"
"os"
"path"
"github.com/gobuffalo/packr"
"github.com/xeipuuv/gojsonschema"
)
// ValidateJSON is used to check for validity
func ValidateJSON(doc string) bool {
file := path.Join("file:///", GetPath(), "/", doc)
box := packr.NewBox("../../../")
s, err := box.MustString("schema.json")
if err != nil {
panic(err.Error())
}
schemaLoader := gojsonschema.NewStringLoader(s)
documentLoader := gojsonschema.NewReferenceLoader(file)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
panic(err.Error())
}
if result.Valid() {
fmt.Printf("The document is valid\n")
return true
} else {
fmt.Printf("The document is not valid. see errors :\n")
for _, desc := range result.Errors() {
fmt.Printf("- %s\n", desc)
}
return false
}
}
// GetPath is used to get current path
func GetPath() string {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return dir
}
|
Use the correct name for the ListBuckets operation
|
var inspect = require('eyes').inspector();
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var S3 = awssum.load('amazon/s3').S3;
var env = process.env;
var accessKeyId = process.env.ACCESS_KEY_ID;
var secretAccessKey = process.env.SECRET_ACCESS_KEY;
var awsAccountId = process.env.AWS_ACCOUNT_ID;
var s3 = new S3({
'accessKeyId' : accessKeyId,
'secretAccessKey' : secretAccessKey,
'region' : amazon.US_EAST_1
});
console.log( 'Region :', s3.region() );
console.log( 'EndPoint :', s3.host() );
console.log( 'AccessKeyId :', s3.accessKeyId() );
// console.log( 'SecretAccessKey :', s3.secretAccessKey() );
console.log( 'AwsAccountId :', s3.awsAccountId() );
s3.ListBuckets(function(err, data) {
console.log("\nlisting all the buckets (no options given) - expecting success");
inspect(err, 'Error');
inspect(data, 'Data');
});
|
var inspect = require('eyes').inspector();
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var S3 = awssum.load('amazon/s3').S3;
var env = process.env;
var accessKeyId = process.env.ACCESS_KEY_ID;
var secretAccessKey = process.env.SECRET_ACCESS_KEY;
var awsAccountId = process.env.AWS_ACCOUNT_ID;
var s3 = new S3({
'accessKeyId' : accessKeyId,
'secretAccessKey' : secretAccessKey,
'region' : amazon.US_EAST_1
});
console.log( 'Region :', s3.region() );
console.log( 'EndPoint :', s3.host() );
console.log( 'AccessKeyId :', s3.accessKeyId() );
// console.log( 'SecretAccessKey :', s3.secretAccessKey() );
console.log( 'AwsAccountId :', s3.awsAccountId() );
s3.listBuckets(function(err, data) {
console.log("\nlisting all the buckets (no options given) - expecting success");
inspect(err, 'Error');
inspect(data, 'Data');
});
|
Add list order action boxoffice endpoint
|
<?php
require '../vendor/autoload.php';
$config = json_decode(file_get_contents("config/config.json"), true);
$config['root'] = __DIR__;
$app = new \Slim\App([ 'settings' => $config ]);
require '../dependencies.php';
// Routes
// =============================================================
$app->get('/events', Actions\ListVisibleEventsAction::class);
$app->get('/events/{id}', Actions\GetEventAction::class);
$app->get('/eventblocks/{id}', Actions\GetEventblockAction::class);
$app->get('/reservations', Actions\ListMyReservationsAction::class);
$app->post('/reservations', Actions\CreateReservationAction::class);
$app->put('/reservations/{id}', Actions\ChangeReductionForReservationAction::class);
$app->delete('/reservations/{id}', Actions\DeleteReservationAction::class);
$app->get('/orders', Actions\ListOrdersAction::class);
$app->post('/boxoffice-purchases', Actions\CreateBoxofficePurchaseAction::class);
// =============================================================
$app->run();
|
<?php
require '../vendor/autoload.php';
$config = json_decode(file_get_contents("config/config.json"), true);
$config['root'] = __DIR__;
$app = new \Slim\App([ 'settings' => $config ]);
require '../dependencies.php';
// Routes
// =============================================================
$app->get('/events', Actions\ListVisibleEventsAction::class);
$app->get('/events/{id}', Actions\GetEventAction::class);
$app->get('/eventblocks/{id}', Actions\GetEventblockAction::class);
$app->get('/reservations', Actions\ListMyReservationsAction::class);
$app->post('/reservations', Actions\CreateReservationAction::class);
$app->put('/reservations/{id}', Actions\ChangeReductionForReservationAction::class);
$app->delete('/reservations/{id}', Actions\DeleteReservationAction::class);
$app->post('/boxoffice-purchases', Actions\CreateBoxofficePurchaseAction::class);
// =============================================================
$app->run();
|
Use arrow function for this
|
const gulp = require('gulp')
const babel = require('gulp-babel')
const cache = require('gulp-cached')
const ext = require('gulp-ext')
const check = require('gulp-if')
const path = require('path')
const srcPath = 'src/**/*'
const condition = file => file.path.indexOf('/bin') > -1
gulp.task('transpile', function () {
return gulp.src(srcPath)
.pipe(cache('muffin'))
.pipe(babel({
presets: ['es2015'],
plugins: [
'transform-async-to-generator',
'transform-runtime',
'syntax-async-functions'
]
}))
.pipe(check(condition, ext.crop()))
.pipe(gulp.dest('dist'))
})
gulp.task('watch', function () {
gulp.watch(srcPath, ['transpile'])
})
gulp.task('default', ['watch', 'transpile'])
|
const gulp = require('gulp')
const babel = require('gulp-babel')
const cache = require('gulp-cached')
const ext = require('gulp-ext')
const check = require('gulp-if')
const path = require('path')
const srcPath = 'src/**/*'
const condition = function (file) {
return file.path.indexOf('/bin') > -1
}
gulp.task('transpile', function () {
return gulp.src(srcPath)
.pipe(cache('muffin'))
.pipe(babel({
presets: ['es2015'],
plugins: [
'transform-async-to-generator',
'transform-runtime',
'syntax-async-functions'
]
}))
.pipe(check(condition, ext.crop()))
.pipe(gulp.dest('dist'))
})
gulp.task('watch', function () {
gulp.watch(srcPath, ['transpile'])
})
gulp.task('default', ['watch', 'transpile'])
|
Add instruction for stopping dev server
|
<?php
namespace Spark\Core;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;
class DevelopmentServer
{
protected $documentRoot;
protected $router;
function __construct($documentRoot, $router)
{
$this->documentRoot = $documentRoot;
$this->router = $router;
}
function run($serverName = null, $port = null)
{
$serverName = $serverName ?: "localhost";
$port = $port ?: 3000;
$builder = new ProcessBuilder();
$builder->add((new PhpExecutableFinder)->find());
# Start PHP in development server mode
$builder->add('-S');
$builder->add("$serverName:$port");
# Add the document root
$builder->add('-t');
$builder->add($this->documentRoot);
# Add the router script
$builder->add($this->router);
$process = $builder->getProcess();
$process->setTimeout(null);
printf("Running development server on %s:%d ..." . PHP_EOL, $serverName, $port);
printf("Stop by pressing [CTRL] + [c]\n");
$process->run(function($type, $err) {
fwrite(STDERR, "$err\n");
});
}
}
|
<?php
namespace Spark\Core;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;
class DevelopmentServer
{
protected $documentRoot;
protected $router;
function __construct($documentRoot, $router)
{
$this->documentRoot = $documentRoot;
$this->router = $router;
}
function run($serverName = null, $port = null)
{
$serverName = $serverName ?: "localhost";
$port = $port ?: 3000;
$builder = new ProcessBuilder();
$builder->add((new PhpExecutableFinder)->find());
# Start PHP in development server mode
$builder->add('-S');
$builder->add("$serverName:$port");
# Add the document root
$builder->add('-t');
$builder->add($this->documentRoot);
# Add the router script
$builder->add($this->router);
$process = $builder->getProcess();
$process->setTimeout(null);
printf("Running development server on %s:%d ..." . PHP_EOL, $serverName, $port);
$process->run(function($type, $err) {
fwrite(STDERR, "$err\n");
});
}
}
|
Update feed-page-size given new feeds
|
var app = require('connect')();
var createRepostGuard = require('./src/repost-guard');
var fs = require('fs');
var log = require('./src/util').log;
var path = require('path');
// Keeping this forever in memory for now.
createRepostGuard.shared = createRepostGuard({
directory: path.join(__dirname, 'tmp'),
lineLimit: 5000, // ~350 links * 14 days
// Number of most recent links discounted for being on current page.
feedPageSize: 90, // ~30 items * 3 feeds
sync: false,
onReady: function() { log('Links loaded.'); }
});
createRepostGuard.shared.setUp();
require('./config').feeds.forEach(function(feed) {
var middleware = require(path.join(__dirname, 'src/feeds', feed.name));
app.use('/'+ feed.name, middleware.bind(null, feed));
});
app.use(function(request, response) {
response.statusCode = 404;
fs.readFile(path.join(__dirname, '404.shtml'), function(error, data) {
if (error) {
response.end('Feed not found!\n');
} else {
response.setHeader('Content-Type', 'text/html');
response.end(data);
}
});
});
require('http').createServer(app).listen(3000);
|
var app = require('connect')();
var createRepostGuard = require('./src/repost-guard');
var fs = require('fs');
var log = require('./src/util').log;
var path = require('path');
// Keeping this forever in memory for now.
createRepostGuard.shared = createRepostGuard({
directory: path.join(__dirname, 'tmp'),
lineLimit: 5000, // ~350 links * 14 days
// Number of most recent links discounted for being on current page.
feedPageSize: 30,
sync: false,
onReady: function() { log('Links loaded.'); }
});
createRepostGuard.shared.setUp();
require('./config').feeds.forEach(function(feed) {
var middleware = require(path.join(__dirname, 'src/feeds', feed.name));
app.use('/'+ feed.name, middleware.bind(null, feed));
});
app.use(function(request, response) {
response.statusCode = 404;
fs.readFile(path.join(__dirname, '404.shtml'), function(error, data) {
if (error) {
response.end('Feed not found!\n');
} else {
response.setHeader('Content-Type', 'text/html');
response.end(data);
}
});
});
require('http').createServer(app).listen(3000);
|
Add new properties, to be sandboxed
|
let origBot, origGuild;
// A dummy message object so ESLint doesn't complain
class Message {}
class Client {
constructor(bot, guild) {
origBot = bot;
origGuild = guild;
// TODO: sandboxed user
// this.user = bot.user
// TODO: sandboxed guild
// this.currentGuild = guild;
}
get guilds() {
return origBot.guilds.size;
}
get users() {
return origBot.users.size;
}
waitForMessage(authorId, channelId, timeout, check) {
if (!authorId || !channelId) return Promise.reject("Missing author/channel ID");
if (!check || typeof check !== "function") check = () => true;
let c = msg => {
if (msg.author.id == authorId && msg.channel.id == channelId
&& msg.channel.guild && msg.channel.guild.id == origGuild.id
&& check()) return true;
else return false;
};
origBot.waitForEvent("messageCreate", timeout, c)
.then((eventReturn) => new Message(eventReturn[0]));
}
}
module.exports = Client;
|
let origBot, origGuild;
// A dummy message object so ESLint doesn't complain
class Message {}
class Client {
constructor(bot, guild) {
origBot = bot;
origGuild = guild;
}
get guilds() {
return origBot.guilds.size
}
get users() {
return origBot.users.size
}
waitForMessage(authorId, channelId, timeout, check) {
if (!authorId || !channelId) return Promise.reject("Missing author/channel ID");
if (!check || typeof check !== "function") check = () => true;
let c = msg => {
if (msg.author.id == authorId && msg.channel.id == channelId
&& msg.channel.guild && msg.channel.guild.id == origGuild.id
&& check()) return true;
else return false;
};
origBot.waitForEvent("messageCreate", timeout, c)
.then((eventReturn) => new Message(eventReturn[0]));
}
}
module.exports = Client;
|
Use metaclasses to register node types.
|
import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
_nodeTypes = {}
class _NodeTypeRegistrar(type):
def __init__(self, name, bases, dict):
type.__init__(self, name, bases, dict)
_nodeTypes[self.nodeType] = self
class NodeType(object):
__metaclass__ = _NodeTypeRegistrar
nodeType = 'UNKNOWN'
def __init__(self):
pass
def freeze(self):
return (self.nodeType, self.__dict__)
@classmethod
def thaw(class_, d):
return class_(**d)
class Client(NodeType):
nodeType = 'CLIENT'
def thawNodeType(info):
nodeType = info[0]
return _nodeTypes[nodeType].thaw(info[1])
|
import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
class NodeType(object):
nodeType = 'UNKNOWN'
def __init__(self):
pass
def freeze(self):
return (self.nodeType, self.__dict__)
@classmethod
def thaw(class_, d):
return class_(**d)
class Client(NodeType):
nodeType = 'CLIENT'
_nodeTypes = {}
def registerNodeTypes(moduleName):
global _nodeTypes
for item in sys.modules[moduleName].__dict__.values():
if inspect.isclass(item) and issubclass(item, NodeType):
_nodeTypes[item.nodeType] = item
registerNodeTypes(__name__)
def registerNodeType(class_):
_nodeTypes[class_.nodeType] = class_
def thawNodeType(info):
nodeType = info[0]
return _nodeTypes[nodeType].thaw(info[1])
|
Split create database and create user into to individual commands
|
# -*- coding: utf-8 -*-
from fabric.api import run
def _generate_password():
import string
from random import sample
chars = string.letters + string.digits
return ''.join(sample(chars, 8))
def create_mysql_instance(mysql_user, mysql_password, instance_code):
user = instance_code
password = _generate_password()
cmd_create_database = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s;\"" % (
mysql_user, mysql_password, 3306,
user,)
cmd_create_user = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"grant all on %s.* to '%s'@'%%' identified by '%s';\"" % (
mysql_user, mysql_password, 3306,
user, user, password,)
run(cmd_create_database)
run(cmd_create_user)
# Local Variables: **
# comment-column: 56 **
# indent-tabs-mode: nil **
# python-indent: 4 **
# End: **
|
# -*- coding: utf-8 -*-
from fabric.api import task, run
def _generate_password():
import string
from random import sample
chars = string.letters + string.digits
return ''.join(sample(chars, 8))
def create_mysql_instance(mysql_user, mysql_password, instance_code):
user = instance_code
password = _generate_password()
cmd = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s; grant all on %s.* to '%s'@'%%' identified by '%s'\"" % (
mysql_user, mysql_password, 3306,
user, user, user, password,)
return run(cmd)
# Local Variables: **
# comment-column: 56 **
# indent-tabs-mode: nil **
# python-indent: 4 **
# End: **
|
Fix wart in event bus context
|
# -*- coding: utf-8 -*-
'''
A simple test engine, not intended for real use but as an example
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.event
import salt.utils.json
log = logging.getLogger(__name__)
def event_bus_context(opts):
if opts['__role'] == 'master':
event_bus = salt.utils.event.get_master_event(
opts,
opts['sock_dir'],
listen=True)
else:
event_bus = salt.utils.event.get_event(
'minion',
transport=opts['transport'],
opts=opts,
sock_dir=opts['sock_dir'],
listen=True)
log.debug('test engine started')
return event_bus
def start():
'''
Listen to events and write them to a log file
'''
with event_bus_context(__opts__) as event_bus:
while True:
event = event_bus.get_event()
jevent = salt.utils.json.dumps(event)
if event:
log.debug(jevent)
|
# -*- coding: utf-8 -*-
'''
A simple test engine, not intended for real use but as an example
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.event
import salt.utils.json
log = logging.getLogger(__name__)
def event_bus_context(opts):
if opts['__role'] == 'master':
event_bus = salt.utils.event.get_master_event(
opts,
opts['sock_dir'],
listen=True)
else:
event_bus = salt.utils.event.get_event(
'minion',
transport=opts['transport'],
opts=opts,
sock_dir=opts['sock_dir'],
listen=True)
log.debug('test engine started')
def start():
'''
Listen to events and write them to a log file
'''
with event_bus_context(__opts__) as event:
while True:
event = event_bus.get_event()
jevent = salt.utils.json.dumps(event)
if event:
log.debug(jevent)
|
[ENH] payments: Add a new action to add mulitple items to a cart (used in custom code only so far)
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@52748 b456876b-0849-0410-b77d-98878d47e9d5
|
<?php
// (c) Copyright 2002-2014 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: Controller.php 46965 2013-08-02 19:05:59Z jonnybradley $
class Services_Payment_Controller
{
function setUp()
{
Services_Exception_Disabled::check('payment_feature', 'wikiplugin_addtocart');
}
function action_addtocart($input)
{
$cartlib = TikiLib::lib('cart');
$params = $input->params->asArray();
return $cartlib->add_to_cart($params, $input);
}
function action_addalltocart($input)
{
$cartlib = TikiLib::lib('cart');
$items = $input->items->asArray();
$ret = array();
foreach ($items as $item) {
$ret[] = $cartlib->add_to_cart($item['params'], new jitFilter($item));
}
return $ret;
}
function action_capture($input)
{
$perms = Perms::get();
if (! $perms->payment_admin) {
throw new Services_Exception_Denied(tr('Reserved to payment administrators'));
}
$paymentlib = TikiLib::lib('payment');
$paymentlib->capture_payment($input->paymentId->int());
$access = TikiLib::lib('access');
$access->redirect($input->next->url());
}
}
|
<?php
// (c) Copyright 2002-2014 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: Controller.php 46965 2013-08-02 19:05:59Z jonnybradley $
class Services_Payment_Controller
{
function setUp()
{
Services_Exception_Disabled::check('payment_feature', 'wikiplugin_addtocart');
}
function action_addtocart($input)
{
$cartlib = TikiLib::lib('cart');
$params = $input->params->asArray();
return $cartlib->add_to_cart($params, $input);
}
function action_capture($input)
{
$perms = Perms::get();
if (! $perms->payment_admin) {
throw new Services_Exception_Denied(tr('Reserved to payment administrators'));
}
$paymentlib = TikiLib::lib('payment');
$paymentlib->capture_payment($input->paymentId->int());
$access = TikiLib::lib('access');
$access->redirect($input->next->url());
}
}
|
Fix tests for udata/datagouvfr backend
|
import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer',
'first_name': 'foobar',
'email': 'foobar@example.com'
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
'oauth_callback_confirmed': 'true'
})
user_data_body = json.dumps({})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
|
import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer'
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
'oauth_callback_confirmed': 'true'
})
user_data_body = json.dumps({})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
|
Fix static generator causing only one output at a time
|
<?php
namespace JLSalinas\RWGen;
trait GeneratorAggregateHack
{
protected $generator = null;
public function send($value)
{
if ($this->generator === null) {
if ($value === null) {
return;
}
$this->generator = $this->getGenerator();
}
$this->generator->send($value);
if ($value === null) {
$this->generator = null;
}
}
public function __destruct()
{
$this->send(null);
}
}
|
<?php
namespace JLSalinas\RWGen;
trait GeneratorAggregateHack
{
public function send($value)
{
static $generator = null;
if ($generator === null) {
if ($value === null) {
return;
}
$generator = $this->getGenerator();
}
$generator->send($value);
if ($value === null) {
$generator = null;
}
}
public function __destruct()
{
$this->send(null);
}
}
|
Add debug information when server starts
|
// Package main initializes a web server.
package main
import (
"fmt"
"net/http"
_ "net/http/pprof" // import for side effects
"os"
log "github.com/Sirupsen/logrus"
"github.com/hack4impact/transcribe4all/config"
"github.com/hack4impact/transcribe4all/web"
)
func init() {
log.SetOutput(os.Stderr)
if config.Config.Debug {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
}
func main() {
router := web.NewRouter()
middlewareRouter := web.ApplyMiddleware(router)
// serve http
http.Handle("/", middlewareRouter)
http.Handle("/static/", http.FileServer(http.Dir(".")))
log.Infof("Server is running at http://localhost:%d", config.Config.Port)
addr := fmt.Sprintf(":%d", config.Config.Port)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Error(err)
}
}
|
// Package main initializes a web server.
package main
import (
"net/http"
_ "net/http/pprof" // import for side effects
"os"
log "github.com/Sirupsen/logrus"
"github.com/hack4impact/transcribe4all/config"
"github.com/hack4impact/transcribe4all/web"
)
func init() {
log.SetOutput(os.Stderr)
if config.Config.Debug {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
}
func main() {
router := web.NewRouter()
middlewareRouter := web.ApplyMiddleware(router)
// serve http
http.Handle("/", middlewareRouter)
http.Handle("/static/", http.FileServer(http.Dir(".")))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Error(err)
}
}
|
Remove unnecessary modifiers to follow the convention
Change-Id: Ie8ff539252df6ed9df5ff827d639166a78fbf18d
|
/*
* Copyright 2014 Open Networking Laboratory
*
* 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.onosproject.store;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Opaque version structure.
* <p>
* Classes implementing this interface must also implement
* {@link #hashCode()} and {@link #equals(Object)}.
*/
public interface Timestamp extends Comparable<Timestamp> {
@Override
int hashCode();
@Override
boolean equals(Object obj);
/**
* Tests if this timestamp is newer than the specified timestamp.
*
* @param other timestamp to compare against
* @return true if this instance is newer
*/
default boolean isNewerThan(Timestamp other) {
return this.compareTo(checkNotNull(other)) > 0;
}
}
|
/*
* Copyright 2014 Open Networking Laboratory
*
* 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.onosproject.store;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Opaque version structure.
* <p>
* Classes implementing this interface must also implement
* {@link #hashCode()} and {@link #equals(Object)}.
*/
public interface Timestamp extends Comparable<Timestamp> {
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object obj);
/**
* Tests if this timestamp is newer than the specified timestamp.
*
* @param other timestamp to compare against
* @return true if this instance is newer
*/
public default boolean isNewerThan(Timestamp other) {
return this.compareTo(checkNotNull(other)) > 0;
}
}
|
Solve problem to detect linked list cycle
https://www.hackerrank.com/challenges/ctci-linked-list-cycle
|
# https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
"""
def has_cycle(node):
c = node
n = node.next
while n is not None:
if hasattr(c, 'visited'):
return True
c.visited = True
c = n.next
n = c.next
return False
# TEST CODE
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
first_case = Node(1)
three = Node(3)
two = Node(2, three)
one = Node(1, two)
three.next = two
second_case = one
x = Node('x')
y = Node('y', x)
third_case = Node('third_case', y)
print('has_cycle(first_case): {}'.format(has_cycle(first_case)))
print('has_cycle(second_case): {}'.format(has_cycle(second_case)))
print('has_cycle(second_case): {}'.format(has_cycle(third_case)))
|
# https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
"""
def has_cycle(node):
if hasattr(node, 'visited'):
return True
node.visited = True
if node.next is None:
return False
return has_cycle(node.next)
# TEST CODE
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
first_case = Node(1)
three = Node(3)
two = Node(2, three)
one = Node(1, two)
three.next = two
second_case = one
x = Node('x')
y = Node('y', x)
third_case = Node('third_case', y)
# print('has_cycle(first_case): {}'.format(has_cycle(first_case)))
print('has_cycle(second_case): {}'.format(has_cycle(second_case)))
# print('has_cycle(second_case): {}'.format(has_cycle(third_case)))
|
Add javadocs with info on encoding
|
package com.ft.membership.crypto.signature;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
public class Encoder {
private static final Base64.Encoder BASE_64_ENCODER = Base64.getUrlEncoder().withoutPadding();
private static final Base64.Decoder BASE_64_DECODER = Base64.getUrlDecoder();
/**
* Get Base64 encoded String of a byte array in UTF-8 charset
*
* @param bytes
* @return
*/
public static String getBase64EncodedString(final byte[] bytes) {
return new String(BASE_64_ENCODER.encode(bytes), StandardCharsets.UTF_8);
}
/**
* Get byte array in UTF-8 charset from Base64 encoded string
*
* @param encodedString
* @return
*/
public static Optional<byte[]> getBase64DecodedBytes(final String encodedString) {
try {
return Optional.of(BASE_64_DECODER.decode(encodedString.getBytes(StandardCharsets.UTF_8)));
} catch(IllegalArgumentException e) {
// We do not want a RuntimeException to be thrown when the string passed is not in valid Base64 scheme
// as bad input is possible to the lib methods.
return Optional.empty();
}
}
}
|
package com.ft.membership.crypto.signature;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
public class Encoder {
private static final Base64.Encoder BASE_64_ENCODER = Base64.getUrlEncoder().withoutPadding();
private static final Base64.Decoder BASE_64_DECODER = Base64.getUrlDecoder();
public static String getBase64EncodedString(final byte[] bytes) {
return new String(BASE_64_ENCODER.encode(bytes), StandardCharsets.UTF_8);
}
public static Optional<byte[]> getBase64DecodedBytes(final String encodedString) {
try {
return Optional.of(BASE_64_DECODER.decode(encodedString.getBytes(StandardCharsets.UTF_8)));
} catch(IllegalArgumentException e) {
// We do not want a RuntimeException to be thrown when the string passed is not in valid Base64 scheme
// as bad input is possible to the lib methods.
return Optional.empty();
}
}
}
|
Fix the bug of "Spelling error of a word"
The word "occured" should be spelled as "occurred".
So it is changed.
Change-Id: Ice5212dc8565edb0c5b5c55f979b27440eeeb9aa
Closes-Bug: #1505043
|
# Copyright (c) 2015 Mirantis, 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.
from oslo_log import log as logging
from pecan import hooks
import webob.exc
from neutron.api.v2 import base as v2base
LOG = logging.getLogger(__name__)
class ExceptionTranslationHook(hooks.PecanHook):
def on_error(self, state, e):
# if it's already an http error, just return to let it go through
if isinstance(e, webob.exc.WSGIHTTPException):
return
for exc_class, to_class in v2base.FAULT_MAP.items():
if isinstance(e, exc_class):
raise to_class(getattr(e, 'msg', e.message))
# leaked unexpected exception, convert to boring old 500 error and
# hide message from user in case it contained sensitive details
LOG.exception(_("An unexpected exception was caught: %s") % e)
raise webob.exc.HTTPInternalServerError(
_("An unexpected internal error occurred."))
|
# Copyright (c) 2015 Mirantis, 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.
from oslo_log import log as logging
from pecan import hooks
import webob.exc
from neutron.api.v2 import base as v2base
LOG = logging.getLogger(__name__)
class ExceptionTranslationHook(hooks.PecanHook):
def on_error(self, state, e):
# if it's already an http error, just return to let it go through
if isinstance(e, webob.exc.WSGIHTTPException):
return
for exc_class, to_class in v2base.FAULT_MAP.items():
if isinstance(e, exc_class):
raise to_class(getattr(e, 'msg', e.message))
# leaked unexpected exception, convert to boring old 500 error and
# hide message from user in case it contained sensitive details
LOG.exception(_("An unexpected exception was caught: %s") % e)
raise webob.exc.HTTPInternalServerError(
_("An unexpected internal error occured."))
|
Add files to the exported names.
|
"""Read resources contained within a package."""
import sys
__all__ = [
'Package',
'Resource',
'ResourceReader',
'contents',
'files',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
]
if sys.version_info >= (3,):
from importlib_resources._py3 import (
Package,
Resource,
contents,
files,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
from importlib_resources.abc import ResourceReader
else:
from importlib_resources._py2 import (
contents,
files,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
del __all__[:3]
__version__ = read_text('importlib_resources', 'version.txt').strip()
|
"""Read resources contained within a package."""
import sys
__all__ = [
'Package',
'Resource',
'ResourceReader',
'contents',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
]
if sys.version_info >= (3,):
from importlib_resources._py3 import (
Package,
Resource,
contents,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
from importlib_resources.abc import ResourceReader
else:
from importlib_resources._py2 import (
contents,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
del __all__[:3]
__version__ = read_text('importlib_resources', 'version.txt').strip()
|
Call the previous commit version 0.1.
And tag it as v0.1. Master is now 0.1.0.99, slated to become 0.1.1 when we feel
like labeling the next thing as a release.
|
from distutils.core import setup
__version__ = '0.1.0.99'
setup_args = {
'name': 'hera_librarian',
'author': 'HERA Team',
'license': 'BSD',
'packages': ['hera_librarian'],
'scripts': [
'scripts/add_librarian_file_event.py',
'scripts/add_obs_librarian.py',
'scripts/launch_librarian_copy.py',
'scripts/librarian_assign_sessions.py',
'scripts/librarian_delete_files.py',
'scripts/librarian_initiate_offload.py',
'scripts/librarian_locate_file.py',
'scripts/librarian_offload_helper.py',
'scripts/librarian_set_file_deletion_policy.py',
'scripts/librarian_stream_file_or_directory.sh',
'scripts/upload_to_librarian.py',
],
'version': __version__
}
if __name__ == '__main__':
apply(setup, (), setup_args)
|
from distutils.core import setup
__version__ = '0.1'
setup_args = {
'name': 'hera_librarian',
'author': 'HERA Team',
'license': 'BSD',
'packages': ['hera_librarian'],
'scripts': [
'scripts/add_librarian_file_event.py',
'scripts/add_obs_librarian.py',
'scripts/launch_librarian_copy.py',
'scripts/librarian_assign_sessions.py',
'scripts/librarian_delete_files.py',
'scripts/librarian_initiate_offload.py',
'scripts/librarian_locate_file.py',
'scripts/librarian_offload_helper.py',
'scripts/librarian_set_file_deletion_policy.py',
'scripts/librarian_stream_file_or_directory.sh',
'scripts/upload_to_librarian.py',
],
'version': __version__
}
if __name__ == '__main__':
apply(setup, (), setup_args)
|
Update py2app script for Qt 5.11
|
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
Remove requests and pyzmq from package dependencies
These will now have to be installed separately by the user depending on the
transport protocol required.
|
"""setup.py"""
#pylint:disable=line-too-long
from codecs import open as codecs_open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup #pylint:disable=import-error,no-name-in-module
with codecs_open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with codecs_open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name='jsonrpcclient',
version='2.0.1',
description='JSON-RPC client library.',
long_description=readme + '\n\n' + history,
author='Beau Barker',
author_email='beauinmelbourne@gmail.com',
url='https://jsonrpcclient.readthedocs.org/',
packages=['jsonrpcclient'],
package_data={'jsonrpcclient': ['response-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'future'],
tests_require=['tox'],
classifiers=[
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
"""setup.py"""
#pylint:disable=line-too-long
from codecs import open as codecs_open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup #pylint:disable=import-error,no-name-in-module
with codecs_open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with codecs_open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name='jsonrpcclient',
version='2.0.1',
description='JSON-RPC client library.',
long_description=readme + '\n\n' + history,
author='Beau Barker',
author_email='beauinmelbourne@gmail.com',
url='https://jsonrpcclient.readthedocs.org/',
packages=['jsonrpcclient'],
package_data={'jsonrpcclient': ['response-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'future', 'requests', 'pyzmq'],
tests_require=['tox'],
classifiers=[
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Add missing global & var declarations
|
/* globals JSLang, CurrentPage */
$(document).ready(function () {
$(".delete.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Delete_Title"]});
$(".search.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Show_Users_Title"]});
$(".users.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Show_MainUsers_Title"]});
$(".pagin").click(function () {
$(this).parent().attr("action", "?page=" + $(this).attr("name").replace("goto_", "")).submit();
});
$(".perPage").change(function () {
var AddPageAction;
var getPerPage = $(this).val();
if (CurrentPage > 1) {
AddPageAction = "page=" + CurrentPage + "&";
} else {
AddPageAction = "";
}
$(this).parent().parent().attr("action", "?" + AddPageAction + "pp=" + getPerPage).submit();
});
$("#CMD_DelAll").click(function () {
return confirm(JSLang["CMD_DelAll"]);
});
});
|
/* globals JSLang */
$(document).ready(function () {
$(".delete.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Delete_Title"]});
$(".search.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Show_Users_Title"]});
$(".users.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Show_MainUsers_Title"]});
$(".pagin").click(function () {
$(this).parent().attr("action", "?page=" + $(this).attr("name").replace("goto_", "")).submit();
});
$(".perPage").change(function () {
if (CurrentPage > 1) {
AddPageAction = "page=" + CurrentPage + "&";
} else {
AddPageAction = "";
}
getPerPage = $(this).val();
$(this).parent().parent().attr("action", "?" + AddPageAction + "pp=" + getPerPage).submit();
});
$("#CMD_DelAll").click(function () {
return confirm(JSLang["CMD_DelAll"]);
});
});
|
[rllib] Fix bad sample count assert
|
import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
|
import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
assert next_sample.count >= sample_batch_size * num_envs_per_worker
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
|
Add the first cut at a function to get the x and y intercepts of a hough line.
(Needs much testing and fixing!)
|
/*! 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/.
*/
'use strict';
// Pixel Manipulation Functions.
(function () {
window.getColor = function (data, x, y, width) {
var offset = (y * width + x) * 4;
return {
red: data[offset],
green: data[offset + 1],
blue: data[offset + 2],
alpha: data[offset + 3]
};
};
window.setColor = function (data, x, y, width, color) {
var offset = (y * width + x) * 4;
data[offset] = color.red;
data[offset + 1] = color.green;
data[offset + 2] = color.blue;
data[offset + 3] = color.alpha;
};
window.getIntercepts = function (rho, theta, canvas, log) {
var x = rho * Math.sin(theta);
var y = rho * Math.cos(theta);
if (log) {
console.log('Plotting ' + rho + '@' + (theta/Math.PI*180) + ' as '+ x + ',' + y);
}
var x1 = x + y / rho * canvas.width;
var y1 = y + x / rho * canvas.height;
return [{x:x, y:y}, {x:x1, y:y1}];
};
})();
|
/*! 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/.
*/
'use strict';
// Pixel Manipulation Functions.
(function () {
window.getColor = function (data, x, y, width) {
var offset = (y * width + x) * 4;
return {
red: data[offset],
green: data[offset + 1],
blue: data[offset + 2],
alpha: data[offset + 3]
};
};
window.setColor = function (data, x, y, width, color) {
var offset = (y * width + x) * 4;
data[offset] = color.red;
data[offset + 1] = color.green;
data[offset + 2] = color.blue;
data[offset + 3] = color.alpha;
};
})();
|
TST: Use itemgetter instead of lambda
|
from operator import itemgetter
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
|
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
|
Update GroupAttribute deduplication code to handle multi-value attributes.
|
"use strict";
import React from "react";
import SearchActions from "../actions/SearchActions.js";
function _dedupArray(arr, t, result) {
arr.forEach(function(item) {
if (Array.isArray(item)) {
_dedupArray(item, t, result);
return;
}
if (t.hasOwnProperty(item)) {
return;
}
t[item] = true;
result.push(item);
});
return result;
}
function dedupArray(arr) {
let t = {};
let result = [];
_dedupArray(arr, t, result);
return result;
}
function attributeLink(_this, x) {
return [
<a onClick={_this._onClickAttribute.bind(_this, x)}>{x}</a>,
<span className="bull">•</span>,
];
}
export default class GroupAttributes extends React.Component {
render() {
var _this = this;
var list = dedupArray(this.props.list);
list = list.map(function(attr) {
return attributeLink(_this, attr);
});
if (list.length > 0) {
list[list.length - 1].pop();
}
return (
<div className="attributes">
{list}
</div>
);
}
_onClickAttribute(attributeValue, evt) {
evt.stopPropagation();
SearchActions.search(attributeValue);
}
}
|
"use strict";
import React from "react";
import SearchActions from "../actions/SearchActions.js";
function dedupArray(arr) {
var t = {};
var result = [];
arr.forEach(function(item) {
if (t.hasOwnProperty(item)) {
return;
}
t[item] = true;
result.push(item);
});
return result;
}
function attributeLink(_this, x) {
return [
<a onClick={_this._onClickAttribute.bind(_this, x)}>{x}</a>,
<span className="bull">•</span>,
];
}
export default class GroupAttributes extends React.Component {
render() {
var _this = this;
var list = dedupArray(this.props.list);
list = list.map(function(attr) {
if (Array.isArray(attr)) {
return attr.map(function(x) {
return attributeLink(_this, x);
});
}
return attributeLink(_this, attr);
});
if (list.length > 0) {
list[list.length - 1].pop();
}
return (
<div className="attributes">
{list}
</div>
);
}
_onClickAttribute(attributeValue, evt) {
evt.stopPropagation();
SearchActions.search(attributeValue);
}
}
|
Remove vertical padding from nav button style
|
/**
* @flow
* A collection of common styles for navbar buttons
*/
import {StyleSheet, Platform} from 'react-native'
import * as c from '../colors'
export const commonStyles = StyleSheet.create({
button: {
flexDirection: 'row',
alignItems: 'center',
...Platform.select({
ios: {
paddingHorizontal: 18,
},
android: {
paddingVertical: 15.5,
paddingHorizontal: 16,
},
}),
},
text: {
fontSize: 17,
color: c.white,
...Platform.select({
android: {
marginTop: 1,
},
}),
},
})
export const rightButtonStyles = StyleSheet.create({
button: {
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 6,
...Platform.select({
ios: {
paddingRight: 16,
marginTop: 7,
},
android: {
paddingVertical: 16,
paddingRight: 16,
},
}),
},
icon: {
color: c.white,
...Platform.select({
ios: {
fontSize: 32,
},
android: {
fontSize: 24,
},
}),
},
})
|
/**
* @flow
* A collection of common styles for navbar buttons
*/
import {StyleSheet, Platform} from 'react-native'
import * as c from '../colors'
export const commonStyles = StyleSheet.create({
button: {
flexDirection: 'row',
alignItems: 'center',
...Platform.select({
ios: {
paddingVertical: 11,
paddingHorizontal: 18,
},
android: {
paddingVertical: 15.5,
paddingHorizontal: 16,
},
}),
},
text: {
fontSize: 17,
color: c.white,
...Platform.select({
android: {
marginTop: 1,
},
}),
},
})
export const rightButtonStyles = StyleSheet.create({
button: {
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 6,
...Platform.select({
ios: {
paddingRight: 16,
marginTop: 7,
},
android: {
paddingVertical: 16,
paddingRight: 16,
},
}),
},
icon: {
color: c.white,
...Platform.select({
ios: {
fontSize: 32,
},
android: {
fontSize: 24,
},
}),
},
})
|
Use opts to improve readability.
|
'use strict';
const process = require('process');
const puppeteer = require('puppeteer');
const debug = require('./debug');
let opts = {
args: []
};
if (debug.LOAD_IMAGES == true) {
opts.args.push('--blink-settings=imagesEnabled=false');
}
puppeteer.launch(opts).then(async browser => {
let url = process.argv[2];
let selector = process.argv[3];
let page = await browser.newPage();
page.setUserAgent(debug.USER_AGENT);
await page.setViewport({
width: debug.VIEWPORT_SIZE.width,
height: debug.VIEWPORT_SIZE.height
});
await page.goto(url, {waitUntil: 'load'});
let output = await page.$eval(selector, function(ss) {
return ss ? (ss.innerHTML || '').trim() : '';
});
console.log(output);
await page.close();
await browser.close();
});
|
'use strict';
const process = require('process');
const puppeteer = require('puppeteer');
const debug = require('./debug');
puppeteer.launch({
args: [debug.LOAD_IMAGES == true ? '--blink-settings=imagesEnabled=false': '']
}).then(async browser => {
let url = process.argv[2];
let selector = process.argv[3];
let page = await browser.newPage();
page.setUserAgent(debug.USER_AGENT);
await page.setViewport({
width: debug.VIEWPORT_SIZE.width,
height: debug.VIEWPORT_SIZE.height
});
await page.goto(url, {waitUntil: 'load'});
let output = await page.$eval(selector, function(ss) {
return ss ? (ss.innerHTML || '').trim() : '';
});
console.log(output);
await page.close();
await browser.close();
});
|
Modify solution to fit the exercise specifications more closely
|
/*
Suppose you have a lot of files in a directory that contain words
Exercisei_j, where i and j are digits. Write a program that pads a 0 before
i if i is a single digit and 0 before j if j is a single digit. For example,
the word Exercise2_1 in a file will be replaced by Exercise02_01. Use the
following command to run our program. Use the following command to run your
program.
java E12_27 *
*/
import java.io.File;
public class E12_27 {
public static void main(String[] args) {
for (String s: args) {
File file = new File(s);
StringBuilder sb = new StringBuilder(s);
if (s.matches("Exercise\\d_\\d")) {
sb.insert(8, "0");
sb.insert(11, "0");
} else if (s.matches("Exercise\\d_\\d+")) {
sb.insert(8, "0");
} else if (s.matches("Exercise\\d+_\\d")) {
sb.insert(11, "0");
}
File newName = new File(sb.toString());
file.renameTo(newName);
}
}
}
|
/*
Suppose you have a lot of files in a directory that contain words
Exercisei_j, where i and j are digits. Write a program that pads a 0 before
i if i is a single digit and 0 before j if j is a single digit. For example,
the word Exercise2_1 in a file will be replaced by Exercise02_01. Use the
following command to run our program. Use the following command to run your
program.
java E12_27 *
*/
import java.io.File;
public class E12_27 {
public static void main(String[] args) {
for (String s: args) {
File file = new File(s);
if (s.matches(".*Exercise\\d_\\d.*")) {
StringBuilder sb = new StringBuilder(s);
int index = sb.indexOf("Exercise");
sb.insert((index + 8), "0");
sb.insert((index + 11), "0");
File newName = new File(sb.toString());
file.renameTo(newName);
}
}
}
}
|
Fix bug where amount for stripe is not correctly converted
|
from decimal import Decimal
# FIXME: The amount should be dynamically calculated by payment's currency.
# For example, amount will wrong for JPY since JPY does not support cents
def get_amount_for_stripe(amount, currency):
"""Get appropriate amount for stripe.
Stripe is using currency's smallest unit such as cents for USD.
Stripe requires integer instead of decimal.
"""
# Using int(Decimal) directly may yield wrong result
# such as int(Decimal(24.24)) will equal to 2423
return int((amount * 100).to_integral_value())
def get_amount_from_stripe(amount, currency):
"""Get appropriate amount from stripe.
Stripe is using currency's smallest unit such as cents for USD.
Saleor requires decimal instead of float or integer.
"""
# Using Decimal(amount / 100.0) will convert to decimal from float
# which precision may be lost
return Decimal(amount) / Decimal(100)
def get_currency_for_stripe(currency):
"""Convert Saleor's currency format to Stripe's currency format.
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.lower()
def get_currency_from_stripe(currency):
"""Convert Stripe's currency format to Saleor's currency format.
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.upper()
|
from decimal import Decimal
# FIXME: The amount should be dynamically calculated by payment's currency.
# For example, amount will wrong for JPY since JPY does not support cents
def get_amount_for_stripe(amount, currency):
"""Get appropriate amount for stripe.
Stripe is using currency's smallest unit such as cents for USD.
Stripe requires integer instead of decimal.
"""
return int(amount * 100)
def get_amount_from_stripe(amount, currency):
"""Get appropriate amount from stripe.
Stripe is using currency's smallest unit such as cents for USD.
Saleor requires decimal instead of float or integer.
"""
return Decimal(amount / 100.0)
def get_currency_for_stripe(currency):
"""Convert Saleor's currency format to Stripe's currency format.
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.lower()
def get_currency_from_stripe(currency):
"""Convert Stripe's currency format to Saleor's currency format.
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.upper()
|
Switch to just icons for home and sign out in dashboard nav
|
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu">
<span class="sr-only">{{ Lang::get('cachet.dashboard.toggle_navigation') }}</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><span id="sidebar-toggle"></span> Cachet</a>
</div>
<div class="collapse navbar-collapse" id="menu">
<ul class="nav navbar-nav navbar-right">
<li><a class='' href="{{ URL::route('status-page') }}"><i class="fa fa-home"></i></a></li>
<li><a class='' href="{{ URL::route('logout') }}"><i class="fa fa-sign-out"></i></a></li>
</ul>
</div>
</div>
</nav>
|
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu">
<span class="sr-only">{{ Lang::get('cachet.dashboard.toggle_navigation') }}</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><span id="sidebar-toggle"></span> Cachet</a>
</div>
<div class="collapse navbar-collapse" id="menu">
<ul class="nav navbar-nav navbar-right">
<li><a href="{{ URL::route('status-page') }}"><i class="fa fa-exclamation-circle"></i> {{ Lang::get('cachet.dashboard.status_page') }}</a></li>
<li><a href="{{ URL::route('logout') }}"><i class="fa fa-sign-out"></i> {{ Lang::get('cachet.logout') }}</a></li>
</ul>
</div>
</div>
</nav>
|
Raise read-only filesystem when the user wants to chmod in /history.
|
import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
raise FuseOSError(EROFS)
def write(self, path, fh):
raise FuseOSError(EROFS)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
return 0
def flush(self, path, fh):
return 0
def release(self, path, fh):
return 0
def access(self, path, amode):
return 0
def mkdir(self, path, mode):
raise FuseOSError(EROFS)
def utimens(self, path, times=None):
raise FuseOSError(EROFS)
def chown(self, path, uid, gid):
raise FuseOSError(EROFS)
def chmod(self, path, mode):
raise FuseOSError(EROFS)
|
import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
raise FuseOSError(EROFS)
def write(self, path, fh):
raise FuseOSError(EROFS)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
return 0
def flush(self, path, fh):
return 0
def release(self, path, fh):
return 0
def access(self, path, amode):
return 0
def mkdir(self, path, mode):
raise FuseOSError(EROFS)
def utimens(self, path, times=None):
raise FuseOSError(EROFS)
def chown(self, path, uid, gid):
raise FuseOSError(EROFS)
|
Add installation requirements for developers
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oemof developer group',
author_email='windpowerlib@rl-institut.de',
license=None,
packages=['windpowerlib'],
package_data={
'windpowerlib': [os.path.join('data', '*.csv')]},
long_description=read('README.rst'),
zip_safe=False,
install_requires=['pandas >= 0.19.1',
'requests'],
extras_require={
'dev': ['sphinx_rtd_theme', 'pytest']})
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oemof developer group',
author_email='windpowerlib@rl-institut.de',
license=None,
packages=['windpowerlib'],
package_data={
'windpowerlib': [os.path.join('data', '*.csv')]},
long_description=read('README.rst'),
zip_safe=False,
install_requires=['pandas >= 0.19.1',
'requests'])
|
tests.backends: Test using DatabaseBackend instead of RedisBackend, as the latter requires the redis module to be installed.
|
import unittest2 as unittest
from celery import backends
from celery.backends.amqp import AMQPBackend
from celery.backends.database import DatabaseBackend
class TestBackends(unittest.TestCase):
def test_get_backend_aliases(self):
expects = [("amqp", AMQPBackend),
("database", DatabaseBackend)]
for expect_name, expect_cls in expects:
self.assertIsInstance(backends.get_backend_cls(expect_name)(),
expect_cls)
def test_get_backend_cahe(self):
backends._backend_cache = {}
backends.get_backend_cls("amqp")
self.assertIn("amqp", backends._backend_cache)
amqp_backend = backends.get_backend_cls("amqp")
self.assertIs(amqp_backend, backends._backend_cache["amqp"])
|
import unittest2 as unittest
from celery import backends
from celery.backends.amqp import AMQPBackend
from celery.backends.pyredis import RedisBackend
class TestBackends(unittest.TestCase):
def test_get_backend_aliases(self):
expects = [("amqp", AMQPBackend),
("redis", RedisBackend)]
for expect_name, expect_cls in expects:
self.assertIsInstance(backends.get_backend_cls(expect_name)(),
expect_cls)
def test_get_backend_cahe(self):
backends._backend_cache = {}
backends.get_backend_cls("amqp")
self.assertIn("amqp", backends._backend_cache)
amqp_backend = backends.get_backend_cls("amqp")
self.assertIs(amqp_backend, backends._backend_cache["amqp"])
|
Add more return types after fixing a typo in my script
|
<?php
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* Class BaseUser.
*/
class BaseUser
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $username;
private $enabled;
/**
* BaseUser constructor.
*/
public function __construct(int $id, string $username)
{
$this->id = $id;
$this->username = $username;
}
public function getId(): int
{
return $this->id;
}
public function getUsername(): string
{
return $this->username;
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$allowEmptyString = property_exists(Assert\Length::class, 'allowEmptyString') ? ['allowEmptyString' => true] : [];
$metadata->addPropertyConstraint('username', new Assert\Length([
'min' => 2,
'max' => 120,
'groups' => ['Registration'],
] + $allowEmptyString));
}
}
|
<?php
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* Class BaseUser.
*/
class BaseUser
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $username;
private $enabled;
/**
* BaseUser constructor.
*/
public function __construct(int $id, string $username)
{
$this->id = $id;
$this->username = $username;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
public function getUsername(): string
{
return $this->username;
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$allowEmptyString = property_exists(Assert\Length::class, 'allowEmptyString') ? ['allowEmptyString' => true] : [];
$metadata->addPropertyConstraint('username', new Assert\Length([
'min' => 2,
'max' => 120,
'groups' => ['Registration'],
] + $allowEmptyString));
}
}
|
Mark empty object as static
|
package com.alexstyl.specialdates.events.namedays.calendar.resource;
import com.alexstyl.specialdates.events.namedays.NamedayLocale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
class NamedayJSONResourceProvider {
private static final JSONArray EMPTY = new JSONArray();
private final NamedayJSONResourceLoader loader;
NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
this.loader = loader;
}
NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
JSONObject json = loader.loadJSON(locale);
JSONArray data = json.getJSONArray("data");
JSONArray special = getSpecialOf(json);
return new NamedayJSON(data, special);
}
private JSONArray getSpecialOf(JSONObject json) throws JSONException {
if (json.has("special")) {
return json.getJSONArray("special");
}
return EMPTY;
}
}
|
package com.alexstyl.specialdates.events.namedays.calendar.resource;
import com.alexstyl.specialdates.events.namedays.NamedayLocale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
class NamedayJSONResourceProvider {
private final NamedayJSONResourceLoader loader;
private final JSONArray jsonArray = new JSONArray();
NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
this.loader = loader;
}
NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
JSONObject json = loader.loadJSON(locale);
JSONArray data = json.getJSONArray("data");
JSONArray special = getSpecialOf(json);
return new NamedayJSON(data, special);
}
private JSONArray getSpecialOf(JSONObject json) throws JSONException {
if (json.has("special")) {
return json.getJSONArray("special");
}
return jsonArray;
}
}
|
Remove php old version check
|
<?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
if (STORE_PAGE_PARSE_TIME == 'true') {
$time_start = explode(' ', PAGE_PARSE_START_TIME);
$time_end = explode(' ', microtime());
$parse_time = number_format(($time_end[1] + $time_end[0] - ($time_start[1] + $time_start[0])), 3);
error_log(strftime(STORE_PARSE_DATE_TIME_FORMAT) . ' - ' . $_SERVER['REQUEST_URI'] . ' (' . $parse_time . 's)' . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
if (DISPLAY_PAGE_PARSE_TIME == 'true') {
echo '<span class="smallText">Parse Time: ' . $parse_time . 's</span>';
}
}
if ( (GZIP_COMPRESSION == 'true') && ($ext_zlib_loaded == true) && ($ini_zlib_output_compression < 1) ) {
tep_gzip_output(GZIP_LEVEL);
}
?>
|
<?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
if (STORE_PAGE_PARSE_TIME == 'true') {
$time_start = explode(' ', PAGE_PARSE_START_TIME);
$time_end = explode(' ', microtime());
$parse_time = number_format(($time_end[1] + $time_end[0] - ($time_start[1] + $time_start[0])), 3);
error_log(strftime(STORE_PARSE_DATE_TIME_FORMAT) . ' - ' . $_SERVER['REQUEST_URI'] . ' (' . $parse_time . 's)' . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
if (DISPLAY_PAGE_PARSE_TIME == 'true') {
echo '<span class="smallText">Parse Time: ' . $parse_time . 's</span>';
}
}
if ( (GZIP_COMPRESSION == 'true') && ($ext_zlib_loaded == true) && ($ini_zlib_output_compression < 1) ) {
if ( (PHP_VERSION < '4.0.4') && (PHP_VERSION >= '4') ) {
tep_gzip_output(GZIP_LEVEL);
}
}
?>
|
Fix GraphConvTensorGraph to GraphConvModel in tox21
|
"""
Script that trains graph-conv models on Tox21 dataset.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_tox21
from deepchem.models.tensorgraph.models.graph_models import GraphConvModel
model_dir = "/tmp/graph_conv"
# Load Tox21 dataset
tox21_tasks, tox21_datasets, transformers = load_tox21(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = tox21_datasets
print(train_dataset.data_dir)
print(valid_dataset.data_dir)
# Fit models
metric = dc.metrics.Metric(
dc.metrics.roc_auc_score, np.mean, mode="classification")
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(tox21_tasks), batch_size=batch_size, mode='classification')
model.fit(train_dataset, nb_epoch=10)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, [metric], transformers)
valid_scores = model.evaluate(valid_dataset, [metric], transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
|
"""
Script that trains graph-conv models on Tox21 dataset.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_tox21
from deepchem.models.tensorgraph.models.graph_models import GraphConvTensorGraph
model_dir = "/tmp/graph_conv"
# Load Tox21 dataset
tox21_tasks, tox21_datasets, transformers = load_tox21(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = tox21_datasets
print(train_dataset.data_dir)
print(valid_dataset.data_dir)
# Fit models
metric = dc.metrics.Metric(
dc.metrics.roc_auc_score, np.mean, mode="classification")
# Batch size of models
batch_size = 50
model = GraphConvTensorGraph(
len(tox21_tasks), batch_size=batch_size, mode='classification')
model.fit(train_dataset, nb_epoch=10)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, [metric], transformers)
valid_scores = model.evaluate(valid_dataset, [metric], transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
|
Remove redundant ast.fix_missing_locations call. Moved to transformer.
|
import ast
import sys
from data.logic import _grammar_transformer
from puzzle.problems import problem
class LogicProblem(problem.Problem):
@staticmethod
def score(lines):
if len(lines) <= 1:
return 0
program = '\n'.join(lines)
try:
parsed = ast.parse(program)
if isinstance(parsed, ast.Module):
return min(1, len(parsed.body) / 10)
except:
return 0
return sys.float_info.epsilon
def _parse(self):
return _grammar_transformer.transform('\n'.join(self.lines))
def _solve(self):
parsed = self._parse()
compiled = compile(parsed, '<string>', 'exec')
variables = {}
exec(compiled, variables)
model = variables['model']
solver = model.load('Mistral')
solver.solve()
solutions = model.get_solutions()
# TODO: Return valid solutions.
return solutions
|
import ast
import sys
from data.logic import _grammar_transformer
from puzzle.problems import problem
class LogicProblem(problem.Problem):
@staticmethod
def score(lines):
if len(lines) <= 1:
return 0
program = '\n'.join(lines)
try:
parsed = ast.parse(program)
if isinstance(parsed, ast.Module):
return min(1, len(parsed.body) / 10)
except:
return 0
return sys.float_info.epsilon
def _parse(self):
return _grammar_transformer.transform('\n'.join(self.lines))
def _solve(self):
parsed = self._parse()
ast.fix_missing_locations(parsed)
compiled = compile(parsed, '<string>', 'exec')
variables = {}
exec(compiled, variables)
model = variables['model']
solver = model.load('Mistral')
solver.solve()
solutions = model.get_solutions()
# TODO: Return valid solutions.
return solutions
|
Add a familiar warn to quickly access console.log
|
var round = function(num)
{
return (num + 0.5) | 0
}
var floor = function(num)
{
return num | 0
}
var ceil = function(num)
{
return (num | 0) == num ? num | 0 : (num + 1) | 0
}
var abs = Math.abs
var sqrt = Math.sqrt
var log = function(num)
{
var result = Math.log(num)
return result
}
var signed_log = function(num)
{
var sign = num < 0 ? -1 : 1;
var result = Math.log(abs(num))
return sign * result
}
var max = function(a, b)
{
return (a > b) ? a : b;
}
var min = function(a, b)
{
return (a < b) ? a : b;
}
var fix_all = function(old_all)
{
var new_all = []
for (var obj in old_all)
{
if (old_all[obj] != undefined)
{
new_all.push(old_all[obj])
}
}
return new_all;
}
var count_object_keys = function(obj)
{
var result = 0;
for (var prop in obj)
{
if (obj.hasOwnProperty(prop))
result++
}
return result
}
var warn = function()
{
console.log.apply(console, arguments)
}
|
var round = function(num)
{
return (num + 0.5) | 0
}
var floor = function(num)
{
return num | 0
}
var ceil = function(num)
{
return (num | 0) == num ? num | 0 : (num + 1) | 0
}
var abs = Math.abs
var sqrt = Math.sqrt
var log = function(num)
{
var result = Math.log(num)
return result
}
var signed_log = function(num)
{
var sign = num < 0 ? -1 : 1;
var result = Math.log(abs(num))
return sign * result
}
var max = function(a, b)
{
return (a > b) ? a : b;
}
var min = function(a, b)
{
return (a < b) ? a : b;
}
var fix_all = function(old_all)
{
var new_all = []
for (var obj in old_all)
{
if (old_all[obj] != undefined)
{
new_all.push(old_all[obj])
}
}
return new_all;
}
var count_object_keys = function(obj)
{
var result = 0;
for (var prop in obj)
{
if (obj.hasOwnProperty(prop))
result++
}
return result
}
|
Add privateroom table to db
|
const Sequelize = require('sequelize');
const sequelize = new Sequelize('tbd', 'root', '12345');
const users = sequelize.define('user', {
userName: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
facebookId: {
type: Sequelize.STRING
},
token: {
type: Sequelize.STRING
},
salt: {
type: Sequelize.STRING
}
}, {
tableName: 'users',
timestamps: false,
});
const privateRooms = sequelize.define('user', {
url: {
type: Sequelize.STRING
},
}, {
tableName: 'users',
timestamps: false,
});
sequelize
.sync({ force: false })
.then(() => {
console.log('It worked!');
}, err => {
console.log('An error occurred while creating the table:', err);
});
sequelize
.authenticate()
.then(err => {
console.log('sqlz Connection has been established successfully.');
})
.catch(err => {
console.log('sqlz Unable to connect to the database:', err);
});
module.exports = {
users,
privateRooms,
};
|
const Sequelize = require('sequelize');
const sequelize = new Sequelize('tbd', 'root', '12345');
const users = sequelize.define('user', {
userName: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
facebookId: {
type: Sequelize.STRING
},
token: {
type: Sequelize.STRING
},
salt: {
type: Sequelize.STRING
}
}, {
tableName: 'users',
timestamps: false,
});
sequelize
.sync({ force: false })
.then( () => {
console.log('It worked!');
}, err => {
console.log('An error occurred while creating the table:', err);
});
sequelize
.authenticate()
.then(err => {
console.log('sqlz Connection has been established successfully.');
})
.catch(err => {
console.log('sqlz Unable to connect to the database:', err);
});
module.exports.users=users;
|
Move log message to else block, incorrectly report null when not null
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.notification.email',
name: 'EmailServiceDAO',
extends: 'foam.dao.ProxyDAO',
requires: [
'foam.nanos.notification.email.EmailMessage',
'foam.nanos.notification.email.EmailService'
],
imports: [
'email?'
],
properties: [
{
name: 'emailService',
documentation: `This property determines how to process the email.`,
of: 'foam.nanos.notification.email.EmailService',
class: 'FObjectProperty',
javaFactory: `
return (EmailService)getEmail();
`
}
],
methods: [
{
name: 'put_',
javaCode:
`
EmailService service = getEmailService();
if ( service != null ) {
service.sendEmail(x, (EmailMessage)obj);
} else {
((foam.nanos.logger.Logger) x.get("logger")).debug("EmailServiceDAO emailService null");
}
return getDelegate().inX(x).put(obj);
`
}
]
});
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.notification.email',
name: 'EmailServiceDAO',
extends: 'foam.dao.ProxyDAO',
requires: [
'foam.nanos.notification.email.EmailMessage',
'foam.nanos.notification.email.EmailService'
],
imports: [
'email?'
],
properties: [
{
name: 'emailService',
documentation: `This property determines how to process the email.`,
of: 'foam.nanos.notification.email.EmailService',
class: 'FObjectProperty',
javaFactory: `
return (EmailService)getEmail();
`
}
],
methods: [
{
name: 'put_',
javaCode:
`
EmailService service = getEmailService();
if ( service != null ) {
((foam.nanos.logger.Logger) x.get("logger")).debug("EmailServiceDAO emailService null");
service.sendEmail(x, (EmailMessage)obj);
}
return getDelegate().inX(x).put(obj);
`
}
]
});
|
Remove spaces in computed properties
|
import fetch from 'isomorphic-fetch';
import url from 'url';
const baseUrlObj = {
protocol: 'https:',
host: 'api.github.com',
pathname: '/gists',
};
const baseUrlStr = url.format(baseUrlObj);
const FILENAME = 'playground.rs';
export function load(id) {
return fetch(`${baseUrlStr}/${id}`)
.then(response => response.json())
.then(gist => ({
id: id,
url: gist.html_url,
code: gist.files[FILENAME].content,
}));
}
const gistBody = code => ({
description: "Rust code shared from the playground",
public: true,
files: {
[FILENAME]: {
content: code,
},
},
});
export function save(code) {
return fetch(baseUrlStr, {
method: 'post',
body: JSON.stringify(gistBody(code)),
})
.then(response => response.json())
.then(response => {
let { id, html_url: url } = response;
return { id, url };
});
}
|
import fetch from 'isomorphic-fetch';
import url from 'url';
const baseUrlObj = {
protocol: 'https:',
host: 'api.github.com',
pathname: '/gists',
};
const baseUrlStr = url.format(baseUrlObj);
const FILENAME = 'playground.rs';
export function load(id) {
return fetch(`${baseUrlStr}/${id}`)
.then(response => response.json())
.then(gist => ({
id: id,
url: gist.html_url,
code: gist.files[FILENAME].content,
}));
}
const gistBody = code => ({
description: "Rust code shared from the playground",
public: true,
files: {
[ FILENAME ]: {
content: code,
},
},
});
export function save(code) {
return fetch(baseUrlStr, {
method: 'post',
body: JSON.stringify(gistBody(code)),
})
.then(response => response.json())
.then(response => {
let { id, html_url: url } = response;
return { id, url };
});
}
|
[SPARK-32095][SQL] Update documentation to reflect usage of updated statistics
### What changes were proposed in this pull request?
Update documentation to reflect changes in https://github.com/apache/spark/commit/faf220aad9051c224a630e678c54098861f6b482
I've changed the documentation to reflect updated statistics may be used to improve query plan.
### Why are the changes needed?
I believe the documentation is stale and misleading.
### Does this PR introduce _any_ user-facing change?
Yes, this is a javadoc documentation fix.
### How was this patch tested?
Doc fix.
Closes #28925 from emkornfield/spark-32095.
Authored-by: Micah Kornfield <ee238861fc7c420e3c40e16afaa0ba8ab6b504de@google.com>
Signed-off-by: Wenchen Fan <563f5923eae9a92c8a3f34a26b67fa348a303ed1@databricks.com>
|
/*
* 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 org.apache.spark.sql.connector.read;
import org.apache.spark.annotation.Evolving;
/**
* A mix in interface for {@link Scan}. Data sources can implement this interface to
* report statistics to Spark.
*
* As of Spark 3.0, statistics are reported to the optimizer after operators are pushed to the
* data source. Implementations may return more accurate statistics based on pushed operators
* which may improve query performance by providing better information to the optimizer.
*
* @since 3.0.0
*/
@Evolving
public interface SupportsReportStatistics extends Scan {
/**
* Returns the estimated statistics of this data source scan.
*/
Statistics estimateStatistics();
}
|
/*
* 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 org.apache.spark.sql.connector.read;
import org.apache.spark.annotation.Evolving;
/**
* A mix in interface for {@link Scan}. Data sources can implement this interface to
* report statistics to Spark.
*
* As of Spark 2.4, statistics are reported to the optimizer before any operator is pushed to the
* data source. Implementations that return more accurate statistics based on pushed operators will
* not improve query performance until the planner can push operators before getting stats.
*
* @since 3.0.0
*/
@Evolving
public interface SupportsReportStatistics extends Scan {
/**
* Returns the estimated statistics of this data source scan.
*/
Statistics estimateStatistics();
}
|
Replace strings comparison with regexp
|
document.addEventListener('beforeload', onBeforeLoad, true);
var config = [
{
source: 'source.js',
reSource: 'reSource.js'
}
];
function onBeforeLoad(event) {
if (event.srcElement.tagName == 'SCRIPT') {
for(var i = 0; i < config.length; i++) {
var regexp = new RegExp(config[i].source);
if (regexp.test(event.url)) {
event.preventDefault();
var script = document.createElement('script');
script.setAttribute('src', config[i].reSource);
event.srcElement.parentNode.replaceChild(script, event.srcElement);
return;
}
}
}
}
|
document.addEventListener('beforeload', onBeforeLoad, true);
var config = [
{
source: 'source.js',
reSource: 'reSource.js'
}
];
function onBeforeLoad(event) {
if (event.srcElement.tagName == 'SCRIPT') {
console.error(event.url);
for(var i = 0; i < config.length; i++) {
if (event.url == config[i].source) {
event.preventDefault();
var script = document.createElement('script');
script.setAttribute('src', config[i].reSource);
event.srcElement.parentNode.replaceChild(script, event.srcElement);
return;
}
}
}
}
|
Set "PHP" word to uppercase!
|
<?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Admin / Controller
*/
namespace PH7;
class InfoController extends Controller
{
private $sTitle;
public function index()
{
Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get(PH7_ADMIN_MOD, 'info', 'software'));
}
public function language()
{
$this->sTitle = t('PHP Information');
$this->view->page_title = $this->sTitle;
$this->view->h1_title = $this->sTitle;
$this->output();
}
public function software()
{
$this->sTitle = t('%software_name% Information');
$this->view->page_title = $this->sTitle;
$this->view->h1_title = $this->sTitle;
$this->view->release_date = $this->dateTime->get(Framework\Security\Version::KERNEL_RELASE_DATE)->date();
$this->output();
}
}
|
<?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Admin / Controller
*/
namespace PH7;
class InfoController extends Controller
{
private $sTitle;
public function index()
{
Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get(PH7_ADMIN_MOD, 'info', 'software'));
}
public function language()
{
$this->sTitle = t('Php Information');
$this->view->page_title = $this->sTitle;
$this->view->h1_title = $this->sTitle;
$this->output();
}
public function software()
{
$this->sTitle = t('%software_name% Information');
$this->view->page_title = $this->sTitle;
$this->view->h1_title = $this->sTitle;
$this->view->release_date = $this->dateTime->get(Framework\Security\Version::KERNEL_RELASE_DATE)->date();
$this->output();
}
public function __destruct()
{
unset($this->sTitle);
}
}
|
Fix end to end tests after password profile modifications
|
var assert = require("assert");
module.exports = {
"User set saved profile": function(browser) {
browser
.url(browser.launch_url)
.waitForElementVisible(".fa-sign-in")
.click(".fa-sign-in")
.setValue("#email", "test@lesspass.com")
.setValue("#passwordField", "test@lesspass.com")
.waitForElementVisible("#encryptMasterPassword__btn")
.click("#encryptMasterPassword__btn")
.waitForElementVisible("#signInButton")
.click("#signInButton")
.waitForElementVisible(".fa-key")
.click(".fa-key")
.waitForElementVisible(".passwordProfile__meta")
.click(".passwordProfile__meta")
.waitForElementVisible("#site")
.assert.value("#site", "example.org")
.assert.value("#login", "contact@example.org");
browser.end();
}
};
|
var assert = require("assert");
module.exports = {
"User set saved profile": function(browser) {
browser
.url(browser.launch_url)
.waitForElementVisible(".fa-sign-in")
.click(".fa-sign-in")
.setValue("#email", "test@lesspass.com")
.setValue("#passwordField", "test@lesspass.com")
.waitForElementVisible("#encryptMasterPassword__btn")
.click("#encryptMasterPassword__btn")
.waitForElementVisible("#signInButton")
.click("#signInButton")
.waitForElementVisible(".fa-key")
.click(".fa-key")
.waitForElementVisible(".passwordProfile__site")
.click(".passwordProfile__site")
.waitForElementVisible("#site")
.assert.value("#site", "example.org")
.assert.value("#login", "contact@example.org");
browser.end();
}
};
|
Work on Recently-Used Database tab.
|
package org.reldb.dbrowser.ui.content.recent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.reldb.dbrowser.ui.DbTab;
public class RecentPanel extends Composite {
/**
* Create the composite.
*
* @param parent
* @param style
*/
public RecentPanel(Composite parent, DbTab dbTab, int style) {
super(parent, style);
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 5;
formLayout.marginHeight = 5;
setLayout(formLayout);
Label lblConvert = new Label(this, SWT.NONE);
FormData fd_lblConvert = new FormData();
fd_lblConvert.top = new FormAttachment(0);
fd_lblConvert.left = new FormAttachment(0);
fd_lblConvert.right = new FormAttachment(100);
lblConvert.setLayoutData(fd_lblConvert);
lblConvert.setText("Recently-used database options go here.");
}
}
|
package org.reldb.dbrowser.ui.content.recent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.reldb.dbrowser.ui.DbTab;
public class RecentPanel extends Composite {
private Label lblConvert;
/**
* Create the composite.
*
* @param parent
* @param style
*/
public RecentPanel(Composite parent, DbTab dbTab, int style) {
super(parent, style);
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 5;
formLayout.marginHeight = 5;
setLayout(formLayout);
lblConvert = new Label(this, SWT.NONE);
FormData fd_lblConvert = new FormData();
fd_lblConvert.top = new FormAttachment(0);
fd_lblConvert.left = new FormAttachment(0);
fd_lblConvert.right = new FormAttachment(100);
lblConvert.setLayoutData(fd_lblConvert);
lblConvert.setText("Recently-used database options go here.");
}
}
|
Fix Stateless functional components + HOC
|
// @flow
import React, { Component } from 'react'
import { lifecycle } from 'recompose'
import type { Alert as AlertType } from '../types/application'
import type { clearAlert } from '../types/actions'
type Props = {
alert: AlertType,
clearAlert: clearAlert
}
const Alert = ({ alert, clearAlert }: Props) => {
if (alert.messages.length == 0) {
return null
}
const messages = alert.messages.map((message, i) => {
return (<div key={`message-${i + 1}`} className="Alert-message">{message}</div>)
})
if (alert.type == null) {
return null
}
return (
<div className={`Alert is-${alert.type}`}>
<div className="Alert-messages">{messages}</div>
</div>
)
}
export default lifecycle({
componentDidUpdate() {
if (this.props.alert.messages.length == 0) {
return
}
setTimeout(() => {
this.props.clearAlert()
}, 5000)
}
})(Alert)
|
// @flow
import React, { Component } from 'react'
import type { Alert as AlertType } from '../types/application'
import type { clearAlert } from '../types/actions'
type Props = {
alert: AlertType,
clearAlert: clearAlert
}
export default class Alert extends Component {
props: Props
componentDidUpdate() {
if (this.props.alert.messages.length == 0) {
return
}
setTimeout(() => {
this.props.clearAlert()
}, 5000)
}
render() {
if (this.props.alert.messages.length == 0) {
return null
}
const messages = this.props.alert.messages.map((message, i) => {
return (<div key={`message-${i + 1}`} className="Alert-message">{message}</div>)
})
if (this.props.alert.type == null) {
return null
}
return (
<div className={`Alert is-${this.props.alert.type}`}>
<div className="Alert-messages">{messages}</div>
</div>
)
}
}
|
Add post modifier to version
|
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
__version__ = '2.7.0.a1.post0'
__author__ = 'Ansible, Inc.'
__codename__ = 'In the Light'
|
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
__version__ = '2.7.0.a1'
__author__ = 'Ansible, Inc.'
__codename__ = 'In the Light'
|
Fix indent and don't decode input command.
|
import os
import shlex
import sys
from canaryd_packages import six
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug('Executing command: {0}'.format(command))
if (
not kwargs.get('shell', False)
and not isinstance(command, (list, tuple))
):
command = shlex.split(command)
output = check_output( # noqa
command,
close_fds=True,
stderr=STDOUT, # noqa
*args, **kwargs
)
if isinstance(output, six.binary_type):
output = output.decode()
return output
|
import os
import shlex
import sys
from canaryd_packages import six
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug('Executing command: {0}'.format(command))
if isinstance(command, six.binary_type):
command = command.decode()
if (
not kwargs.get('shell', False)
and not isinstance(command, (list, tuple))
):
command = shlex.split(command)
output = check_output( # noqa
command,
close_fds=True,
stderr=STDOUT, # noqa
*args, **kwargs
)
if isinstance(output, six.binary_type):
output = output.decode()
return output
|
Fix Js error on tab refresh in element view
|
function bootstrap_tab_bookmark (selector) {
if (selector == undefined) {
selector = "";
}
var bookmark_switch = function () {
url = document.location.href.split('#');
if(url[1] != undefined) {
$(selector + '[href="#'+url[1]+'"]').tab('show');
}
}
/* Automagically jump on good tab based on anchor */
$(document).ready(bookmark_switch);
$(window).bind('hashchange', bookmark_switch);
var update_location = function (event) {
document.location.hash = this.getAttribute("href");
}
/* Update hash based on tab */
$(selector + "[data-toggle=pill]").click(update_location);
$(selector + "[data-toggle=tab]").click(update_location);
}
|
function bootstrap_tab_bookmark (selector) {
if (selector == undefined) {
selector = "";
}
var bookmark_switch = function () {
url = document.location.href.split('#');
if(url[1] != undefined) {
$(selector + '[href=#'+url[1]+']').tab('show');
}
}
/* Automagically jump on good tab based on anchor */
$(document).ready(bookmark_switch);
$(window).bind('hashchange', bookmark_switch);
var update_location = function (event) {
document.location.hash = this.getAttribute("href");
}
/* Update hash based on tab */
$(selector + "[data-toggle=pill]").click(update_location);
$(selector + "[data-toggle=tab]").click(update_location);
}
|
Remove origin from meme model
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
meme = memes.Genome()
self.add(meme)
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
meme = memes.Mimeme()
self.add(meme)
assert meme.type == "mimeme"
assert meme.contents is None
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
node = models.Node()
meme = memes.Genome(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
node = models.Node()
meme = memes.Mimeme(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "mimeme"
assert meme.contents is None
|
Fix problem with the proxy activator when using the blueprint bundle
git-svn-id: 212869a37fe990abe2323f86150f3c4d5a6279c2@1033177 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 org.apache.aries.blueprint.uberbundle;
import org.apache.aries.blueprint.container.BlueprintExtender;
import org.apache.aries.proxy.impl.ProxyManagerActivator;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class UberActivator implements BundleActivator
{
private BlueprintExtender blueprintActivator = new BlueprintExtender();
private ProxyManagerActivator proxyActivator = new ProxyManagerActivator();
public void start(BundleContext context)
{
proxyActivator.start(context);
blueprintActivator.start(context);
}
public void stop(BundleContext context)
{
blueprintActivator.stop(context);
proxyActivator.stop(context);
}
}
|
/*
* 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 org.apache.aries.blueprint.uberbundle;
import org.apache.aries.blueprint.container.BlueprintExtender;
import org.apache.aries.proxy.impl.ProxyManagerActivator;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class UberActivator implements BundleActivator
{
private BlueprintExtender blueprintActivator = new BlueprintExtender();
private ProxyManagerActivator proxyActivator = new ProxyManagerActivator();
public void start(BundleContext context)
{
proxyActivator.start(context);
blueprintActivator.start(context);
}
public void stop(BundleContext arg0)
{
blueprintActivator.stop(arg0);
proxyActivator.start(arg0);
}
}
|
Add 'large' size to the prop types
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Bullet extends PureComponent {
render() {
const { className, color, size, borderColor, borderTint, ...others } = this.props;
const classNames = cx(
theme['bullet'],
theme[color],
theme[size],
{
[theme[`border-${borderColor}-${borderTint}`]]: borderColor && borderTint,
[theme[`border-${borderColor}`]]: borderColor && !borderTint,
},
className,
);
return <Box data-teamleader-ui="bullet" className={classNames} element="span" {...others} />;
}
}
Bullet.propTypes = {
/** A border color to give to the counter */
borderColor: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']),
/** A border tint to give to the counter */
borderTint: PropTypes.oneOf(['darkest', 'dark', 'light', 'lightest']),
/** A class name for the wrapper to give custom styles. */
className: PropTypes.string,
/** The color of the bullet. */
color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']),
/** The size of the bullet. */
size: PropTypes.oneOf(['small', 'medium', 'large']),
};
Bullet.defaultProps = {
color: 'neutral',
size: 'medium',
};
export default Bullet;
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Bullet extends PureComponent {
render() {
const { className, color, size, borderColor, borderTint, ...others } = this.props;
const classNames = cx(
theme['bullet'],
theme[color],
theme[size],
{
[theme[`border-${borderColor}-${borderTint}`]]: borderColor && borderTint,
[theme[`border-${borderColor}`]]: borderColor && !borderTint,
},
className,
);
return <Box data-teamleader-ui="bullet" className={classNames} element="span" {...others} />;
}
}
Bullet.propTypes = {
/** A border color to give to the counter */
borderColor: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']),
/** A border tint to give to the counter */
borderTint: PropTypes.oneOf(['darkest', 'dark', 'light', 'lightest']),
/** A class name for the wrapper to give custom styles. */
className: PropTypes.string,
/** The color of the bullet. */
color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']),
/** The size of the bullet. */
size: PropTypes.oneOf(['small', 'medium']),
};
Bullet.defaultProps = {
color: 'neutral',
size: 'medium',
};
export default Bullet;
|
Fix bug in AddObjects() RPC: new objects were not being counted.
|
package rpcd
import (
"encoding/gob"
"github.com/Symantec/Dominator/lib/srpc"
"github.com/Symantec/Dominator/proto/objectserver"
"io"
"runtime"
)
func (t *srpcType) AddObjects(conn *srpc.Conn) {
defer runtime.GC() // An opportune time to take out the garbage.
defer conn.Flush()
decoder := gob.NewDecoder(conn)
encoder := gob.NewEncoder(conn)
numAdded := 0
numObj := 0
for ; ; numObj++ {
var request objectserver.AddObjectRequest
var response objectserver.AddObjectResponse
if err := decoder.Decode(&request); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
response.Error = err
} else if request.Length < 1 {
break
} else {
response.Hash, response.Added, response.Error =
t.objectServer.AddObject(
conn, request.Length, request.ExpectedHash)
if response.Added {
numAdded++
}
}
encoder.Encode(response)
if response.Error != nil {
return
}
}
t.logger.Printf("AddObjects(): %d of %d are new objects", numAdded, numObj)
}
|
package rpcd
import (
"encoding/gob"
"github.com/Symantec/Dominator/lib/srpc"
"github.com/Symantec/Dominator/proto/objectserver"
"io"
"runtime"
)
func (t *srpcType) AddObjects(conn *srpc.Conn) {
defer runtime.GC() // An opportune time to take out the garbage.
defer conn.Flush()
decoder := gob.NewDecoder(conn)
encoder := gob.NewEncoder(conn)
numAdded := 0
numObj := 0
for ; ; numObj++ {
var request objectserver.AddObjectRequest
var response objectserver.AddObjectResponse
if err := decoder.Decode(&request); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
response.Error = err
} else if request.Length < 1 {
break
} else {
var added bool
response.Hash, response.Added, response.Error =
t.objectServer.AddObject(
conn, request.Length, request.ExpectedHash)
if added {
numAdded++
}
}
encoder.Encode(response)
if response.Error != nil {
return
}
}
t.logger.Printf("AddObjects(): %d of %d are new objects", numAdded, numObj)
}
|
Set propper mimetype for image attachment
|
from email.mime.image import MIMEImage
from django.contrib.staticfiles import finders
from .base import EmailBase
class PlatformEmailMixin:
"""
Attaches the static file images/logo.png so it can be used in an html
email.
"""
def get_attachments(self):
attachments = super().get_attachments()
filename = (
finders.find('images/email_logo.png')
or finders.find('images/email_logo.svg')
)
if filename:
if filename.endswith('.png'):
imagetype = 'png'
else:
imagetype = 'svg+xml'
with open(filename, 'rb') as f:
logo = MIMEImage(f.read(), imagetype)
logo.add_header('Content-ID', '<{}>'.format('logo'))
return attachments + [logo]
return attachments
class SyncEmailMixin(EmailBase):
"""Send Emails synchronously."""
@classmethod
def send(cls, object, *args, **kwargs):
"""Call dispatch immediately"""
return cls().dispatch(object, *args, **kwargs)
|
from email.mime.image import MIMEImage
from django.contrib.staticfiles import finders
from .base import EmailBase
class PlatformEmailMixin:
"""
Attaches the static file images/logo.png so it can be used in an html
email.
"""
def get_attachments(self):
attachments = super().get_attachments()
filename = (
finders.find('images/email_logo.png')
or finders.find('images/email_logo.svg')
)
if filename:
with open(filename, 'rb') as f:
logo = MIMEImage(f.read())
logo.add_header('Content-ID', '<{}>'.format('logo'))
return attachments + [logo]
return attachments
class SyncEmailMixin(EmailBase):
"""Send Emails synchronously."""
@classmethod
def send(cls, object, *args, **kwargs):
"""Call dispatch immediately"""
return cls().dispatch(object, *args, **kwargs)
|
Make sure to specify the length of the map before copy to avoid new allocations
|
// Copyright 2017 The Serulian Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package compilerutil
// ImmutableMap defines an immutable map struct, where Set-ing a new key returns a new ImmutableMap.
type ImmutableMap interface {
// Get returns the value found at the given key, if any.
Get(key string) (interface{}, bool)
// Set returns a new ImmutableMap which is a copy of this map, but with the given key set
// to the given value.
Set(key string, value interface{}) ImmutableMap
}
// NewImmutableMap creates a new, empty immutable map.
func NewImmutableMap() ImmutableMap {
return immutableMap{
internalMap: map[string]interface{}{},
}
}
type immutableMap struct {
internalMap map[string]interface{}
}
func (i immutableMap) Get(key string) (interface{}, bool) {
value, ok := i.internalMap[key]
return value, ok
}
func (i immutableMap) Set(key string, value interface{}) ImmutableMap {
newMap := make(map[string]interface{}, len(i.internalMap))
for existingKey, value := range i.internalMap {
newMap[existingKey] = value
}
newMap[key] = value
return immutableMap{newMap}
}
|
// Copyright 2017 The Serulian Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package compilerutil
// ImmutableMap defines an immutable map struct, where Set-ing a new key returns a new ImmutableMap.
type ImmutableMap interface {
// Get returns the value found at the given key, if any.
Get(key string) (interface{}, bool)
// Set returns a new ImmutableMap which is a copy of this map, but with the given key set
// to the given value.
Set(key string, value interface{}) ImmutableMap
}
// NewImmutableMap creates a new, empty immutable map.
func NewImmutableMap() ImmutableMap {
return immutableMap{
internalMap: map[string]interface{}{},
}
}
type immutableMap struct {
internalMap map[string]interface{}
}
func (i immutableMap) Get(key string) (interface{}, bool) {
value, ok := i.internalMap[key]
return value, ok
}
func (i immutableMap) Set(key string, value interface{}) ImmutableMap {
newMap := map[string]interface{}{}
for existingKey, value := range i.internalMap {
newMap[existingKey] = value
}
newMap[key] = value
return immutableMap{newMap}
}
|
Reduce the test wait time to 20s
Signed-off-by: Julien Viet <5c682c2d1ec4073e277f9ba9f4bdf07e5794dabe@julienviet.com>
|
package io.vertx.ext.web.client;
import static io.vertx.core.Future.failedFuture;
import static io.vertx.core.Future.succeededFuture;
import static io.vertx.core.http.HttpHeaders.AUTHORIZATION;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.Test;
import io.vertx.core.Future;
import io.vertx.core.buffer.Buffer;
public class WebClientSessionTest extends WebClientTestBase {
@Test
public void testRequestHeaders() throws Exception {
WebClientSession session = WebClientSession.create(webClient).addHeader(AUTHORIZATION, "v3rtx");
HttpRequest<Buffer> request = session.get(DEFAULT_TEST_URI);
server.requestHandler(serverRequest -> {
int authHeaderCount = serverRequest.headers().getAll(AUTHORIZATION).size();
serverRequest.response().end(Integer.toString(authHeaderCount));
});
startServer();
Supplier<Future<Void>> requestAndverifyResponse = () -> request.send()
.compose(response -> "1".equals(response.bodyAsString()) ? succeededFuture()
: failedFuture("Request contains Authorization header multiple times " + response.bodyAsString()));
requestAndverifyResponse.get().compose(v -> requestAndverifyResponse.get()).onSuccess(resp -> complete())
.onFailure(t -> fail(t));
await(20, TimeUnit.SECONDS);
}
}
|
package io.vertx.ext.web.client;
import static io.vertx.core.Future.failedFuture;
import static io.vertx.core.Future.succeededFuture;
import static io.vertx.core.http.HttpHeaders.AUTHORIZATION;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.Test;
import io.vertx.core.Future;
import io.vertx.core.buffer.Buffer;
public class WebClientSessionTest extends WebClientTestBase {
@Test
public void testRequestHeaders() throws Exception {
WebClientSession session = WebClientSession.create(webClient).addHeader(AUTHORIZATION, "v3rtx");
HttpRequest<Buffer> request = session.get(DEFAULT_TEST_URI);
server.requestHandler(serverRequest -> {
int authHeaderCount = serverRequest.headers().getAll(AUTHORIZATION).size();
serverRequest.response().end(Integer.toString(authHeaderCount));
});
startServer();
Supplier<Future<Void>> requestAndverifyResponse = () -> request.send()
.compose(response -> "1".equals(response.bodyAsString()) ? succeededFuture()
: failedFuture("Request contains Authorization header multiple times " + response.bodyAsString()));
requestAndverifyResponse.get().compose(v -> requestAndverifyResponse.get()).onSuccess(resp -> complete())
.onFailure(t -> fail(t));
await(200, TimeUnit.SECONDS);
}
}
|
Modify comparator to ensure `namespace` packages are given priority
|
'use strict';
// FUNCTIONS //
/**
* Returns a comparison result. If `-1`, `a` comes before `b`. If `1`, `b` comes before `a`. If `0`, the order stays the same.
*
* @private
* @param {string} a - first string
* @param {string} b - second string
* @returns {boolean} comparison result
*/
function comparator( a, b ) {
if ( a === '__namespace__' ) {
return -1;
}
if ( a[ 0 ] === '_' && b[ 0 ] === '_' ) {
return comparator( a.substring( 1 ), b.substring( 1 ) );
}
if ( a[ 0 ] === '_' ) {
return 1;
}
if ( b[ 0 ] === '_' ) {
return -1;
}
if ( a < b ) {
return -1;
}
if ( a > b ) {
return 1;
}
return 0;
} // end FUNCTION comparator()
// MAIN //
/**
* Sorts tree keys.
*
* @private
* @param {StringArray} keys - keys
* @returns {StringArray} sorted keys
*/
function sort( keys ) {
return keys.sort( comparator );
} // end FUNCTION sort()
// EXPORTS //
module.exports = sort;
|
'use strict';
// FUNCTIONS //
/**
* Returns a comparison result. If `-1`, `a` comes before `b`. If `1`, `b` comes before `a`. If `0`, the order stays the same.
*
* @private
* @param {string} a - first string
* @param {string} b - second string
* @returns {boolean} comparison result
*/
function comparator( a, b ) {
if ( a[ 0 ] === '_' && b[ 0 ] === '_' ) {
return comparator( a.substring( 1 ), b.substring( 1 ) );
}
if ( a[ 0 ] === '_' ) {
return 1;
}
if ( b[ 0 ] === '_' ) {
return -1;
}
if ( a < b ) {
return -1;
}
if ( a > b ) {
return 1;
}
return 0;
} // end FUNCTION comparator()
// MAIN //
/**
* Sorts tree keys.
*
* @private
* @param {StringArray} keys - keys
* @returns {StringArray} sorted keys
*/
function sort( keys ) {
return keys.sort( comparator );
} // end FUNCTION sort()
// EXPORTS //
module.exports = sort;
|
Add MultiScreenService to Default platforms
|
package com.connectsdk;
import java.util.HashMap;
public class DefaultPlatform {
public DefaultPlatform() {
}
public static HashMap<String, String> getDeviceServiceMap() {
HashMap<String, String> devicesList = new HashMap<String, String>();
devicesList.put("com.connectsdk.service.WebOSTVService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.NetcastTVService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.DLNAService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.DIALService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.RokuService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.CastService", "com.connectsdk.discovery.provider.CastDiscoveryProvider");
devicesList.put("com.connectsdk.service.AirPlayService", "com.connectsdk.discovery.provider.ZeroconfDiscoveryProvider");
devicesList.put("com.connectsdk.service.MultiScreenService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
return devicesList;
}
}
|
package com.connectsdk;
import java.util.HashMap;
public class DefaultPlatform {
public DefaultPlatform() {
}
public static HashMap<String, String> getDeviceServiceMap() {
HashMap<String, String> devicesList = new HashMap<String, String>();
devicesList.put("com.connectsdk.service.WebOSTVService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.NetcastTVService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.DLNAService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.DIALService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.RokuService", "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
devicesList.put("com.connectsdk.service.CastService", "com.connectsdk.discovery.provider.CastDiscoveryProvider");
devicesList.put("com.connectsdk.service.AirPlayService", "com.connectsdk.discovery.provider.ZeroconfDiscoveryProvider");
return devicesList;
}
}
|
Tweak ECDC scraper to strip whitespace
|
#!/usr/bin/env python
import requests
import lxml.html
import pandas as pd
import sys
URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx"
columns_old = [
"country",
"affected_past_nine_months",
"affected_past_two_months"
]
columns_new = [
"country",
"affected_past_two_months",
"affected_past_nine_months"
]
def scrape():
html = requests.get(URL).content
dom = lxml.html.fromstring(html)
table = dom.cssselect(".ms-rteTable-1")[0]
rows = table.cssselect("tr")[1:]
data = [ [ td.text_content().strip()
for td in tr.cssselect("td, th") ]
for tr in rows ]
df = pd.DataFrame(data, columns=columns_new)[columns_old]
return df
if __name__ == "__main__":
df = scrape()
df.to_csv(sys.stdout, index=False, encoding="utf-8")
|
#!/usr/bin/env python
import requests
import lxml.html
import pandas as pd
import sys
URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx"
columns_old = [
"country",
"affected_past_nine_months",
"affected_past_two_months"
]
columns_new = [
"country",
"affected_past_two_months",
"affected_past_nine_months"
]
def scrape():
html = requests.get(URL).content
dom = lxml.html.fromstring(html)
table = dom.cssselect(".ms-rteTable-1")[0]
rows = table.cssselect("tr")[1:]
data = [ [ td.text_content()
for td in tr.cssselect("td, th") ]
for tr in rows ]
df = pd.DataFrame(data, columns=columns_new)[columns_old]
return df
if __name__ == "__main__":
df = scrape()
df.to_csv(sys.stdout, index=False, encoding="utf-8")
|
Change version to 1.0.0 to match organizational versioning scheme.
|
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "django-premis-event-service",
version = "1.0.0",
packages = find_packages(),
include_package_data = True,
package_data = {
'': ['*.html'],
},
# metadata (used during PyPI upload)
license = "BSD",
description = "A Django application for storing and querying PREMIS Events",
long_description=README,
keywords = "django PREMIS preservation",
author = "University of North Texas Libraries",
url = "https://github.com/unt-libraries/django-premis-event-service",
classifiers = [
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
)
|
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "django-premis-event-service",
version = "1.0",
packages = find_packages(),
include_package_data = True,
package_data = {
'': ['*.html'],
},
# metadata (used during PyPI upload)
license = "BSD",
description = "A Django application for storing and querying PREMIS Events",
long_description=README,
keywords = "django PREMIS preservation",
author = "University of North Texas Libraries",
url = "https://github.com/unt-libraries/django-premis-event-service",
classifiers = [
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
)
|
Upgrade to latest Symfony2 conventions
|
<?php
namespace Bundle\MarkdownBundle\DependencyInjection;
use Symfony\Components\DependencyInjection\Loader\LoaderExtension;
use Symfony\Components\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Components\DependencyInjection\BuilderConfiguration;
class MarkdownExtension extends LoaderExtension
{
public function parserLoad($config, $configuration)
{
$loader = new XmlFileLoader(__DIR__.'/../Resources/config');
$configuration->merge($loader->load('parser.xml'));
}
public function helperLoad($config, $configuration)
{
$loader = new XmlFileLoader(__DIR__.'/../Resources/config');
$configuration->merge($loader->load('parser.xml'));
}
/**
* Returns the base path for the XSD files.
*
* @return string The XSD base path
*/
public function getXsdValidationBasePath()
{
return null;
}
public function getNamespace()
{
return 'http://www.symfony-project.org/schema/dic/symfony';
}
public function getAlias()
{
return 'markdown';
}
}
|
<?php
namespace Bundle\MarkdownBundle\DependencyInjection;
use Symfony\Components\DependencyInjection\Loader\LoaderExtension;
use Symfony\Components\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Components\DependencyInjection\BuilderConfiguration;
class MarkdownExtension extends LoaderExtension
{
public function parserLoad($config)
{
$configuration = new BuilderConfiguration();
$loader = new XmlFileLoader(__DIR__.'/../Resources/config');
$configuration->merge($loader->load('parser.xml'));
return $configuration;
}
public function helperLoad($config)
{
$configuration = new BuilderConfiguration();
$loader = new XmlFileLoader(__DIR__.'/../Resources/config');
$configuration->merge($loader->load('helper.xml'));
return $configuration;
}
/**
* Returns the base path for the XSD files.
*
* @return string The XSD base path
*/
public function getXsdValidationBasePath()
{
return null;
}
public function getNamespace()
{
return 'http://www.symfony-project.org/schema/dic/symfony';
}
public function getAlias()
{
return 'markdown';
}
}
|
Add more tests to the Hamming function.
|
package tests
import (
"fmt"
"testing"
"github.com/xrash/smetrics"
)
func TestHamming(t *testing.T) {
cases := []hammingcase{
{"a", "a", 0},
{"a", "b", 1},
{"AAAA", "AABB", 2},
{"BAAA", "AAAA", 1},
{"BAAA", "CCCC", 4},
{"karolin", "kathrin", 3},
{"karolin", "kerstin", 3},
{"1011101", "1001001", 2},
{"2173896", "2233796", 3},
}
for _, c := range cases {
r, err := smetrics.Hamming(c.a, c.b)
if err != nil {
t.Fatalf("got error from hamming err=%s", err)
}
if r != c.diff {
fmt.Println(r, "instead of", c.diff)
t.Fail()
}
}
}
func TestHammingError(t *testing.T) {
res, err := smetrics.Hamming("a", "bbb")
if err == nil {
t.Fatalf("expected error from 'a' and 'bbb' on hamming")
}
if res != -1 {
t.Fatalf("erroring response wasn't -1, but %d", res)
}
}
|
package tests
import (
"fmt"
"testing"
"github.com/xrash/smetrics"
)
func TestHamming(t *testing.T) {
cases := []hammingcase{
{"a", "a", 0},
{"a", "b", 1},
{"AAAA", "AABB", 2},
{"BAAA", "AAAA", 1},
{"BAAA", "CCCC", 4},
}
for _, c := range cases {
r, err := smetrics.Hamming(c.a, c.b)
if err != nil {
t.Fatalf("got error from hamming err=%s", err)
}
if r != c.diff {
fmt.Println(r, "instead of", c.diff)
t.Fail()
}
}
}
func TestHammingError(t *testing.T) {
res, err := smetrics.Hamming("a", "bbb")
if err == nil {
t.Fatalf("expected error from 'a' and 'bbb' on hamming")
}
if res != -1 {
t.Fatalf("erroring response wasn't -1, but %d", res)
}
}
|
Remove separate execute mif command.
|
from sim import Sim
from mesh import Mesh
from exchange import Exchange
from demag import Demag
from zeeman import Zeeman
# Mesh specification.
lx = ly = lz = 50e-9 # x, y, and z dimensions (m)
dx = dy = dz = 5e-9 # x, y, and z cell dimensions (m)
Ms = 8e5 # saturation magnetisation (A/m)
A = 1e-11 # exchange energy constant (J/m)
H = (1e6, 0, 0) # external magnetic field (A/m)
m_init = (0, 0, 1) # initial magnetisation
t_sim = 1e-9 # simulation time (s)
# Create a mesh.
mesh = Mesh((lx, ly, lz), (dx, dy, dz))
# Create a simulation object.
sim = Sim(mesh, Ms, name='small_example')
# Add energies.
sim.add(Exchange(A))
sim.add(Demag())
sim.add(Zeeman(H))
# Set initial magnetisation.
sim.set_m(m_init)
# Run simulation.
sim.run_until(t_sim)
|
from sim import Sim
from mesh import Mesh
from exchange import Exchange
from demag import Demag
from zeeman import Zeeman
# Mesh specification.
lx = ly = lz = 50e-9 # x, y, and z dimensions (m)
dx = dy = dz = 5e-9 # x, y, and z cell dimensions (m)
Ms = 8e5 # saturation magnetisation (A/m)
A = 1e-11 # exchange energy constant (J/m)
H = (1e6, 0, 0) # external magnetic field (A/m)
m_init = (0, 0, 1) # initial magnetisation
t_sim = 1e-9 # simulation time (s)
# Create a mesh.
mesh = Mesh((lx, ly, lz), (dx, dy, dz))
# Create a simulation object.
sim = Sim(mesh, Ms, name='small_example')
# Add energies.
sim.add(Exchange(A))
sim.add(Demag())
sim.add(Zeeman(H))
# Set initial magnetisation.
sim.set_m(m_init)
# Run simulation.
sim.run_until(t_sim)
#sim.execute_mif()
|
Add bootstrap-js and bootstrap-fonts tasks
|
var gulp = require('gulp');
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
var sourcemaps = require('gulp-sourcemaps');
// The default Gulp.js task
gulp.task('default', ['bootstrap-fonts', 'bootstrap-js', 'less', 'watch']);
// Rebuild CSS from LESS
gulp.task('less', function () {
return gulp.src('assets/less/**/style.less')
.pipe(sourcemaps.init())
.pipe(less())
.pipe(cleanCSS({
compatibility: 'ie8'
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('assets/css'));
});
// Copy Bootstrap js assets in assets/js
gulp.task('bootstrap-js', function () {
return gulp.src('node_modules/bootstrap/dist/js/bootstrap.min.js')
.pipe(gulp.dest('assets/js'));
});
// Copy Bootstrap font files in assets/fonts
gulp.task('bootstrap-fonts', function () {
return gulp.src('node_modules/bootstrap/dist/fonts/*')
.pipe(gulp.dest('assets/fonts/'));
});
// Watch for LESS and JS file changes
gulp.task('watch', function () {
gulp.watch(['assets/**/*.less'], ['less']);
// gulp.watch(['assets/js/*.js'], ['js']);
});
|
var gulp = require('gulp');
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('default', ['less', 'watch']);
gulp.task('less', function () {
return gulp.src('assets/less/**/style.less')
.pipe(sourcemaps.init())
.pipe(less())
.pipe(cleanCSS({
compatibility: 'ie8'
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('assets/css'));
});
gulp.task('watch', function () {
gulp.watch(['assets/**/*.less'], ['less']);
// gulp.watch(['assets/js/inc/*.js'], ['js']);
});
|
Add offloader helper method for multiple
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.tool;
import android.support.annotation.Nullable;
import timber.log.Timber;
public final class OffloaderHelper {
private OffloaderHelper() {
throw new RuntimeException("No instances");
}
public static void cancel(@Nullable ExecutedOffloader offloader) {
if (offloader == null) {
Timber.w("Offloader is NULL");
return;
}
if (!offloader.isCancelled()) {
offloader.cancel();
}
}
public static void cancel(@Nullable ExecutedOffloader... offloaders) {
if (offloaders == null) {
Timber.w("Offloaders are NULL");
return;
}
for (final ExecutedOffloader offloader : offloaders) {
cancel(offloader);
}
}
}
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.tool;
import android.support.annotation.Nullable;
import timber.log.Timber;
public final class OffloaderHelper {
private OffloaderHelper() {
throw new RuntimeException("No instances");
}
public static void cancel(@Nullable ExecutedOffloader offloader) {
if (offloader == null) {
Timber.w("Offloader is NULL");
return;
}
if (!offloader.isCancelled()) {
offloader.cancel();
}
}
}
|
Extend component class with React.Component in one more file from examples
|
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Connector } from 'redux/react';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/TodoActions';
export default class TodoApp extends Component {
render() {
return (
<Connector select={state => ({ todos: state.todos })}>
{this.renderChild}
</Connector>
);
}
renderChild({ todos, dispatch }) {
const actions = bindActionCreators(TodoActions, dispatch);
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { Connector } from 'redux/react';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/TodoActions';
export default class TodoApp {
render() {
return (
<Connector select={state => ({ todos: state.todos })}>
{this.renderChild}
</Connector>
);
}
renderChild({ todos, dispatch }) {
const actions = bindActionCreators(TodoActions, dispatch);
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
|
fix:docs: Fix sitemap generator to use doc.id instead of doc.name
doc.id should be used instead of doc.name, otherwise links are wrongly
generated
|
exports.SiteMap = SiteMap;
/**
* @see http://www.sitemaps.org/protocol.php
*
* @param docs
* @returns {SiteMap}
*/
function SiteMap(docs){
this.render = function(){
var map = [];
map.push('<?xml version="1.0" encoding="UTF-8"?>');
map.push('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
docs.forEach(function(doc){
map.push(' <url><loc>http://docs.angularjs.org/#!/' +
encode(doc.section) + '/' +
encode(doc.id) +
'</loc><changefreq>weekly</changefreq></url>');
});
map.push('</urlset>');
map.push('');
return map.join('\n');
};
function encode(text){
return text
.replace(/&/mg, '&')
.replace(/</mg, '<')
.replace(/>/mg, '>')
.replace(/'/mg, ''')
.replace(/"/mg, '"');
}
}
|
exports.SiteMap = SiteMap;
/**
* @see http://www.sitemaps.org/protocol.php
*
* @param docs
* @returns {SiteMap}
*/
function SiteMap(docs){
this.render = function(){
var map = [];
map.push('<?xml version="1.0" encoding="UTF-8"?>');
map.push('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
docs.forEach(function(doc){
map.push(' <url><loc>http://docs.angularjs.org/#!/' +
encode(doc.section) + '/' +
encode(doc.name) +
'</loc><changefreq>weekly</changefreq></url>');
});
map.push('</urlset>');
map.push('');
return map.join('\n');
};
function encode(text){
return text
.replace(/&/mg, '&')
.replace(/</mg, '<')
.replace(/>/mg, '>')
.replace(/'/mg, ''')
.replace(/"/mg, '"');
}
}
|
Add a user getter on UD
|
<?php
/**
* @license MIT
* @copyright 2014-2017 Tim Gunter
*/
namespace Kaecyra\ChatBot\Bot\Command;
use Kaecyra\ChatBot\Bot\DestinationInterface;
use Kaecyra\ChatBot\Bot\UserInterface;
/**
* User Destination
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package chatbot
*/
class UserDestination {
/**
* @var UserInterface
*/
protected $user;
/**
* @var DestinationInterface
*/
protected $destination;
/**
* @var string
*/
protected $id;
/**
* UserDestination constructor
*
* @param UserInterface $user
* @param DestinationInterface $destination
*/
public function __construct(UserInterface $user, DestinationInterface $destination) {
$this->user = $user;
$this->destination = $destination;
$this->id = sprintf('%s/%s', $user->getID(), $destination->getID());
}
/**
*
* @return string
*/
public function getKey(): string {
return $this->id;
}
/**
* @return UserInterface
*/
public function getUser(): UserInterface {
return $this->user;
}
}
|
<?php
/**
* @license MIT
* @copyright 2014-2017 Tim Gunter
*/
namespace Kaecyra\ChatBot\Bot\Command;
use Kaecyra\ChatBot\Bot\DestinationInterface;
use Kaecyra\ChatBot\Bot\UserInterface;
/**
* User Destination
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package chatbot
*/
class UserDestination {
/**
* @var UserInterface
*/
protected $user;
/**
* @var DestinationInterface
*/
protected $destination;
/**
* @var string
*/
protected $id;
/**
* UserDestination constructor
*
* @param UserInterface $user
* @param DestinationInterface $destination
*/
public function __construct(UserInterface $user, DestinationInterface $destination) {
$this->user = $user;
$this->destination = $destination;
$this->id = sprintf('%s/%s', $user->getID(), $destination->getID());
}
/**
*
* @return string
*/
public function getKey(): string {
return $this->id;
}
}
|
Fix parent synonym for Location model
|
# -*- coding: utf-8 -*-
from . import db, BaseScopedNameMixin
from flask import url_for
from .board import Board
__all__ = ['Location']
class Location(BaseScopedNameMixin, db.Model):
"""
A location where jobs are listed, using geonameid for primary key. Scoped to a board
"""
__tablename__ = 'location'
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
geonameid = db.synonym('id')
board_id = db.Column(None, db.ForeignKey('board.id'), nullable=False, primary_key=True, index=True)
board = db.relationship(Board, backref=db.backref('locations', lazy='dynamic', cascade='all, delete-orphan'))
parent = db.synonym('board')
#: Landing page description
description = db.Column(db.UnicodeText, nullable=True)
__table_args__ = (db.UniqueConstraint('board_id', 'name'),)
def url_for(self, action='view', **kwargs):
subdomain = self.board.name if self.board.not_root else None
if action == 'view':
return url_for('browse_by_location', location=self.name, subdomain=subdomain, **kwargs)
elif action == 'edit':
return url_for('location_edit', name=self.name, subdomain=subdomain, **kwargs)
@classmethod
def get(cls, name, board):
return cls.query.filter_by(name=name, board=board).one_or_none()
|
# -*- coding: utf-8 -*-
from . import db, BaseScopedNameMixin
from flask import url_for
from .board import Board
__all__ = ['Location']
class Location(BaseScopedNameMixin, db.Model):
"""
A location where jobs are listed, using geonameid for primary key. Scoped to a board
"""
__tablename__ = 'location'
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
geonameid = db.synonym('id')
board_id = db.Column(None, db.ForeignKey('board.id'), nullable=False, primary_key=True, index=True)
parent = db.synonym('board_id')
board = db.relationship(Board, backref=db.backref('locations', lazy='dynamic', cascade='all, delete-orphan'))
#: Landing page description
description = db.Column(db.UnicodeText, nullable=True)
__table_args__ = (db.UniqueConstraint('board_id', 'name'),)
def url_for(self, action='view', **kwargs):
subdomain = self.board.name if self.board.not_root else None
if action == 'view':
return url_for('browse_by_location', location=self.name, subdomain=subdomain, **kwargs)
elif action == 'edit':
return url_for('location_edit', name=self.name, subdomain=subdomain, **kwargs)
@classmethod
def get(cls, name, board):
return cls.query.filter_by(name=name, board=board).one_or_none()
|
Fix test on Java 10
git-svn-id: c1447309447e562cc43d70ade9fe6c70ff9b4cec@1830541 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.
*/
/* $Id$ */
package org.apache.xmlgraphics.image.loader;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* Tests for error behaviour with corrupt images.
*/
public class CorruptImagesTestCase {
private MockImageContext imageContext = MockImageContext.getInstance();
@Test
public void testCorruptPNG() throws Exception {
String uri = "corrupt-image.png";
ImageSessionContext sessionContext = imageContext.newSessionContext();
ImageManager manager = imageContext.getImageManager();
try {
manager.preloadImage(uri, sessionContext);
fail("Expected an ImageException!");
} catch (Exception ie) {
//Expected exception
assertNotNull(ie.getMessage());
}
}
}
|
/*
* 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.
*/
/* $Id$ */
package org.apache.xmlgraphics.image.loader;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* Tests for error behaviour with corrupt images.
*/
public class CorruptImagesTestCase {
private MockImageContext imageContext = MockImageContext.getInstance();
@Test
public void testCorruptPNG() throws Exception {
String uri = "corrupt-image.png";
ImageSessionContext sessionContext = imageContext.newSessionContext();
ImageManager manager = imageContext.getImageManager();
try {
manager.preloadImage(uri, sessionContext);
fail("Expected an ImageException!");
} catch (ImageException ie) {
//Expected exception
assertNotNull(ie.getMessage());
}
}
}
|
Fix address prefixes, add dogecoin/litecoin BIP32 versions
|
// https://en.bitcoin.it/wiki/List_of_address_prefixes
// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
module.exports = {
bitcoin: {
bip32: {
pub: 0x0488b21e,
priv: 0x0488ade4
},
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80
},
dogecoin: {
bip32: {
pub: 0x02facafd,
priv: 0x02fac398
},
pubKeyHash: 0x1e,
scriptHash: 0x16,
wif: 0x9e
},
litecoin: {
bip32: {
pub: 0x019da462,
priv: 0x019d9cfe
},
pubKeyHash: 0x30,
scriptHash: 0x05,
wif: 0xb0
},
testnet: {
bip32: {
pub: 0x043587cf,
priv: 0x04358394
},
pubKeyHash: 0x6f,
scriptHash: 0xc4,
wif: 0xef
}
}
|
// https://en.bitcoin.it/wiki/List_of_address_prefixes
module.exports = {
bitcoin: {
bip32: {
pub: 0x0488b21e,
priv: 0x0488ade4
},
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80
},
dogecoin: {
pubKeyHash: 0x30,
scriptHash: 0x20,
wif: 0x9e
},
litecoin: {
scriptHash: 0x30,
},
testnet: {
bip32: {
pub: 0x043587cf,
priv: 0x04358394
},
pubKeyHash: 0x6f,
scriptHash: 0xc4,
wif: 0xef
}
}
|
Make it DRYer for people
|
from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
# Helpers for people wanting to control response class
def test_logged_in(self, *args, **kwargs):
return self.request.user.is_authenticated()
def test_staff(self, *args, **kwargs):
return self.request.user.is_staff
permit_logged_in = permit(test_logged_in)
permit_staff = permit(test_staff)
def permit_groups(*groups, response_class=http.Forbidden):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups, response_class=response_class)
|
from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
|
Allow MySQL versions > 5 (like MariaDB)
|
<?php
function dbconnect() {
global $hostname,$database,$dbuser,$dbpass,$db;
$db = mysql_connect($hostname,$dbuser,$dbpass) or die("Database error");
mysql_select_db($database, $db);
mysql_set_charset('utf8mb4',$db);
mysql_query("set sql_mode='ALLOW_INVALID_DATES'");
}
function dbclose() {
global $db;
mysql_close($db);
}
function dbserver_has_utf8mb4_support() {
global $hostname,$database,$dbuser,$dbpass;
$dbt = new PDO("mysql:host=$hostname;dbname=$database", $dbuser, $dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "set sql_mode='ALLOW_INVALID_DATES'"));
$version = $dbt->getAttribute(PDO::ATTR_SERVER_VERSION);
if (preg_match("/([0-9]*)\.([0-9]*)\.([0-9]*)/", $version, $matches)) {
$maj = $matches[1]; $min = $matches[2]; $upd = $matches[3];
if ($maj > 5 || ($maj >= 5 && $min >= 5 && $upd >= 3)) {
return true;
}
}
return false;
}
?>
|
<?php
function dbconnect() {
global $hostname,$database,$dbuser,$dbpass,$db;
$db = mysql_connect($hostname,$dbuser,$dbpass) or die("Database error");
mysql_select_db($database, $db);
mysql_set_charset('utf8mb4',$db);
mysql_query("set sql_mode='ALLOW_INVALID_DATES'");
}
function dbclose() {
global $db;
mysql_close($db);
}
function dbserver_has_utf8mb4_support() {
global $hostname,$database,$dbuser,$dbpass;
$dbt = new PDO("mysql:host=$hostname;dbname=$database", $dbuser, $dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "set sql_mode='ALLOW_INVALID_DATES'"));
$version = $dbt->getAttribute(PDO::ATTR_SERVER_VERSION);
if (preg_match("/([0-9]*)\.([0-9]*)\.([0-9]*)/", $version, $matches)) {
$maj = $matches[1]; $min = $matches[2]; $upd = $matches[3];
if ($maj >= 5 && $min >= 5 && $upd >= 3) {
return true;
}
}
return false;
}
?>
|
Change the default to be geofencing with high accuracy at 30 sec intervals
|
package edu.berkeley.eecs.emission.cordova.tracker.location;
import android.content.Context;
import android.location.Location;
import com.google.android.gms.location.LocationRequest;
import edu.berkeley.eecs.emission.cordova.tracker.Constants;
/**
* Created by shankari on 10/20/15.
*
* TODO: Change this to read the value from the usercache instead of the hardcoded value.
*/
public class LocationTrackingConfig {
private Context cachedContext;
protected LocationTrackingConfig(Context ctxt) {
this.cachedContext = ctxt;
}
public static LocationTrackingConfig getConfig(Context context) {
return new LocationTrackingConfig(context);
}
public boolean isDutyCycling() {
return true;
}
public int getDetectionInterval() {
return Constants.THIRTY_SECONDS;
}
public int getAccuracy() {
return LocationRequest.PRIORITY_HIGH_ACCURACY;
}
public int getRadius() {
return Constants.TRIP_EDGE_THRESHOLD;
}
public int getAccuracyThreshold() { return 200; }
public int getResponsiveness() {
return 5 * Constants.MILLISECONDS;
}
}
|
package edu.berkeley.eecs.emission.cordova.tracker.location;
import android.content.Context;
import android.location.Location;
import com.google.android.gms.location.LocationRequest;
import edu.berkeley.eecs.emission.cordova.tracker.Constants;
/**
* Created by shankari on 10/20/15.
*
* TODO: Change this to read the value from the usercache instead of the hardcoded value.
*/
public class LocationTrackingConfig {
private Context cachedContext;
protected LocationTrackingConfig(Context ctxt) {
this.cachedContext = ctxt;
}
public static LocationTrackingConfig getConfig(Context context) {
return new LocationTrackingConfig(context);
}
public boolean isDutyCycling() {
return false;
}
public int getDetectionInterval() {
return Constants.THIRTY_SECONDS;
}
public int getAccuracy() {
return LocationRequest.PRIORITY_HIGH_ACCURACY;
}
public int getRadius() {
return Constants.TRIP_EDGE_THRESHOLD;
}
public int getAccuracyThreshold() { return 200; }
public int getResponsiveness() {
return 5 * Constants.MILLISECONDS;
}
}
|
Add setFreq/setColor methods for FlashingBox
|
from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush
class FlashingBox(QOpenGLWidget):
def __init__(self, parent, freq=1, color=Qt.black):
super(FlashingBox, self).__init__(parent)
self.freq = freq
self.brushes = [QBrush(Qt.black), QBrush(color)]
self.index = 0
self.enabled = False
def setFreq(self, freq):
self.freq = freq
def setColor(self, color):
self.brushes[1] = QBrush(color)
def timerEvent(self, event):
if self.enabled:
self.index = (self.index + 1) % 2
else:
self.index = 0
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(event.rect(), self.brushes[self.index])
def startFlashing(self):
self.index = 0
self.enabled = True
delay = int(1000/(2 * self.freq)) #in mSec
self._timer = self.startTimer(delay, Qt.PreciseTimer)
def stopFlashing(self):
self.killTimer(self._timer)
self.enabled=False
self.index = 0
self.update()
|
from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush
class FlashingBox(QOpenGLWidget):
def __init__(self, parent, freq, color):
super(FlashingBox, self).__init__(parent)
self.freq = freq
self.brushes = [QBrush(Qt.black), QBrush(color)]
self.index = 0
self.enabled = False
def timerEvent(self, event):
if self.enabled:
self.index = (self.index + 1) % 2
else:
self.index = 0
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(event.rect(), self.brushes[self.index])
def suspendFlashing(self):
self.killTimer(self._timer)
self.enabled=False
self.index = 0
self.update()
def startFlashing(self):
self.index = 0
self.enabled = True
delay = int(1000/(2 * self.freq)) #in mSec
self._timer = self.startTimer(delay, Qt.PreciseTimer)
|
Fix bug affecting relative genome paths in sessions
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.
*/
package org.broad.igv.session;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Jim Robinson
* @date 1/12/12
*/
public interface SessionReader {
void loadSession(InputStream inputStream, Session session, String sessionPath) throws IOException;
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.
*/
package org.broad.igv.session;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Jim Robinson
* @date 1/12/12
*/
public interface SessionReader {
void loadSession(InputStream inputStream, Session session, String sessionName) throws IOException;
}
|
Update fb js to v2.12
|
// https://dev.twitter.com/web/javascript/loading
window.twttr = (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function (f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
// https://developers.facebook.com/docs/plugins/share-button
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.12';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
|
// https://dev.twitter.com/web/javascript/loading
window.twttr = (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function (f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
// https://developers.facebook.com/docs/plugins/share-button
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.11&appId=366384430479764';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
|
Remove transition labels on converting PN to STG.
|
package org.workcraft.plugins.stg.tools;
import java.util.Map;
import org.workcraft.dom.math.MathNode;
import org.workcraft.dom.visual.VisualComponent;
import org.workcraft.gui.graph.tools.DefaultModelConverter;
import org.workcraft.plugins.petri.Place;
import org.workcraft.plugins.petri.Transition;
import org.workcraft.plugins.petri.VisualPetriNet;
import org.workcraft.plugins.stg.DummyTransition;
import org.workcraft.plugins.stg.STGPlace;
import org.workcraft.plugins.stg.VisualDummyTransition;
import org.workcraft.plugins.stg.VisualSTG;
import org.workcraft.plugins.stg.VisualSignalTransition;
public class PetriNetToStgConverter extends DefaultModelConverter<VisualPetriNet, VisualSTG> {
public PetriNetToStgConverter(VisualPetriNet srcModel, VisualSTG dstModel) {
super(srcModel, dstModel);
}
@Override
public Map<Class<? extends MathNode>, Class<? extends MathNode>> getComponentClassMap() {
Map<Class<? extends MathNode>, Class<? extends MathNode>> result = super.getComponentClassMap();
result.put(Place.class, STGPlace.class);
result.put(Transition.class, DummyTransition.class);
return result;
}
@Override
public VisualComponent convertComponent(VisualComponent srcComponent) {
VisualComponent dstComponent = super.convertComponent(srcComponent);
if ( (dstComponent instanceof VisualDummyTransition) || (dstComponent instanceof VisualSignalTransition) ) {
dstComponent.setLabel("");
}
return dstComponent;
}
}
|
package org.workcraft.plugins.stg.tools;
import java.util.Map;
import org.workcraft.dom.math.MathNode;
import org.workcraft.gui.graph.tools.DefaultModelConverter;
import org.workcraft.plugins.petri.Place;
import org.workcraft.plugins.petri.Transition;
import org.workcraft.plugins.petri.VisualPetriNet;
import org.workcraft.plugins.stg.DummyTransition;
import org.workcraft.plugins.stg.STGPlace;
import org.workcraft.plugins.stg.VisualSTG;
public class PetriNetToStgConverter extends DefaultModelConverter<VisualPetriNet, VisualSTG> {
public PetriNetToStgConverter(VisualPetriNet srcModel, VisualSTG dstModel) {
super(srcModel, dstModel);
}
@Override
public Map<Class<? extends MathNode>, Class<? extends MathNode>> getComponentClassMap() {
Map<Class<? extends MathNode>, Class<? extends MathNode>> result = super.getComponentClassMap();
result.put(Place.class, STGPlace.class);
result.put(Transition.class, DummyTransition.class);
return result;
}
}
|
Remove redundant company create step
|
const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
const { set, get, assign } = require('lodash')
defineSupportCode(({ When }) => {
const Company = client.page.Company()
When(/^the Account management details are updated$/, async function () {
await Company
.updateAccountManagement((accountManagement) => {
const company = get(this.state, 'company')
set(this.state, 'company', assign({}, company, accountManagement))
})
})
When(/^the Exports details are updated$/, async function () {
await Company
.updateExports((exports) => {
const company = get(this.state, 'company')
set(this.state, 'company', assign({}, company, exports))
})
})
})
|
const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
const { set, get, assign } = require('lodash')
defineSupportCode(({ Given, When }) => {
const Company = client.page.Company()
Given(/^a company is created$/, async function () {
await client
.url(this.urls.companies.search)
await Company
.createUkNonPrivateOrNonPublicLimitedCompany({}, (company) => {
set(this.state, 'company', company)
})
.wait() // wait for backend to sync
})
When(/^the Account management details are updated$/, async function () {
await Company
.updateAccountManagement((accountManagement) => {
const company = get(this.state, 'company')
set(this.state, 'company', assign({}, company, accountManagement))
})
})
When(/^the Exports details are updated$/, async function () {
await Company
.updateExports((exports) => {
const company = get(this.state, 'company')
set(this.state, 'company', assign({}, company, exports))
})
})
})
|
Add support for flake8 3.0
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import flake8
if flake8.__version_info__ < (3,):
from flake8.engine import get_style_guide
else:
from flake8.api.legacy import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.path.join(cur_dir, '..', 'tox.ini')
def run():
"""
Runs flake8 lint
:return:
A bool - if flake8 did not find any errors
"""
print('Running flake8')
flake8_style = get_style_guide(config_file=config_file)
paths = []
for root, _, filenames in os.walk('asn1crypto'):
for filename in filenames:
if not filename.endswith('.py'):
continue
paths.append(os.path.join(root, filename))
report = flake8_style.check_files(paths)
success = report.total_errors == 0
if success:
print('OK')
return success
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
from flake8.engine import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.path.join(cur_dir, '..', 'tox.ini')
def run():
"""
Runs flake8 lint
:return:
A bool - if flake8 did not find any errors
"""
print('Running flake8')
flake8_style = get_style_guide(config_file=config_file)
paths = []
for root, _, filenames in os.walk('asn1crypto'):
for filename in filenames:
if not filename.endswith('.py'):
continue
paths.append(os.path.join(root, filename))
report = flake8_style.check_files(paths)
success = report.total_errors == 0
if success:
print('OK')
return success
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.