text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix double items showing up in workflow waiting for me
|
<?php
namespace Concrete\Core\Notification\View\Menu;
use Concrete\Core\Application\UserInterface\ContextMenu\DropdownMenu;
use Concrete\Core\Application\UserInterface\ContextMenu\Item\DividerItem;
use Concrete\Core\Application\UserInterface\ContextMenu\Item\ItemInterface;
use Concrete\Core\Application\UserInterface\ContextMenu\Item\LinkItem;
use HtmlObject\Element;
class WorkflowProgressListViewMenu extends DropdownMenu
{
public function getMenuElement()
{
$menu = parent::getMenuElement();
$menu->appendChild((new DividerItem())->getItemElement());
$item = new LinkItem(
'#',
tc('Verb', 'Archive'),
['data-notification-action' => 'archive']
);
$menu->appendChild($item->getItemElement());
return $menu;
}
}
|
<?php
namespace Concrete\Core\Notification\View\Menu;
use Concrete\Core\Application\UserInterface\ContextMenu\DropdownMenu;
use Concrete\Core\Application\UserInterface\ContextMenu\Item\DividerItem;
use Concrete\Core\Application\UserInterface\ContextMenu\Item\ItemInterface;
use Concrete\Core\Application\UserInterface\ContextMenu\Item\LinkItem;
use HtmlObject\Element;
class WorkflowProgressListViewMenu extends DropdownMenu
{
public function getMenuElement()
{
$menu = parent::getMenuElement();
foreach ($this->items as $item) {
/* @var ItemInterface $item */
$menu->appendChild($item->getItemElement());
}
$menu->appendChild((new DividerItem())->getItemElement());
$item = new LinkItem(
'#',
tc('Verb', 'Archive'),
['data-notification-action' => 'archive']
);
$menu->appendChild($item->getItemElement());
return $menu;
}
}
|
Fix celery config to respect the host configured on settings
|
import os
from django.conf import settings
REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379')
BROKER_URL = os.getenv(
'DBAAS_NOTIFICATION_BROKER_URL', 'redis://{}:{}/0'.format(settings.REDIS_HOST, REDIS_PORT))
CELERYD_TASK_TIME_LIMIT = 10800
CELERY_TRACK_STARTED = True
CELERY_IGNORE_RESULT = False
CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheBackend'
CELERYBEAT_MAX_LOOP_INTERVAL = 5
CELERY_TIMEZONE = os.getenv('DJANGO_TIME_ZONE', 'America/Sao_Paulo')
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERYD_LOG_FORMAT = "[%(asctime)s: %(processName)s %(name)s %(levelname)s] %(message)s"
CELERY_ALWAYS_EAGER = False
CELERYD_LOG_COLOR = False
CELERYD_PREFETCH_MULTIPLIER = 1
|
import os
REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379')
BROKER_URL = os.getenv(
'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT)
CELERYD_TASK_TIME_LIMIT = 10800
CELERY_TRACK_STARTED = True
CELERY_IGNORE_RESULT = False
CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheBackend'
CELERYBEAT_MAX_LOOP_INTERVAL = 5
CELERY_TIMEZONE = os.getenv('DJANGO_TIME_ZONE', 'America/Sao_Paulo')
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERYD_LOG_FORMAT = "[%(asctime)s: %(processName)s %(name)s %(levelname)s] %(message)s"
CELERY_ALWAYS_EAGER = False
CELERYD_LOG_COLOR = False
CELERYD_PREFETCH_MULTIPLIER = 1
|
Drop parent() its not used, and may not be exposed on all logging systems directly.
|
/*
* Copyright (C) 2010 the original author or authors.
*
* 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.sonatype.gshell.logging;
/**
* Represents a logger.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @since 2.5
*/
public interface Logger
{
String getName();
Level getLevel();
void setLevel(Level level);
void setLevel(String level);
boolean isRoot();
}
|
/*
* Copyright (C) 2010 the original author or authors.
*
* 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.sonatype.gshell.logging;
/**
* Represents a logger.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @since 2.5
*/
public interface Logger
{
String getName();
Level getLevel();
void setLevel(Level level);
void setLevel(String level);
Logger parent();
boolean isRoot();
}
|
Remove logging. It will just break travis.
|
from api.caching.tasks import ban_url, logger
from framework.guid.model import Guid
from framework.tasks.handlers import enqueue_task
from modularodm import signals
@signals.save.connect
def log_object_saved(sender, instance, fields_changed, cached_data):
abs_url = None
if hasattr(instance, 'absolute_api_v2_url'):
abs_url = instance.absolute_api_v2_url
else:
# I don't think this should ever happen, but ... just in case.
guid_obj = Guid.load(instance._id)
if guid_obj is not None:
typedModel = guid_obj.referent
if hasattr(typedModel, 'absolute_api_v2_url'):
abs_url = typedModel.absolute_api_v2_url
if abs_url is not None:
enqueue_task(ban_url.s(abs_url))
|
from api.caching.tasks import ban_url, logger
from framework.guid.model import Guid
from framework.tasks.handlers import enqueue_task
from modularodm import signals
@signals.save.connect
def log_object_saved(sender, instance, fields_changed, cached_data):
abs_url = None
if hasattr(instance, 'absolute_api_v2_url'):
abs_url = instance.absolute_api_v2_url
else:
# I don't think this should ever happen, but ... just in case.
guid_obj = Guid.load(instance._id)
if guid_obj is not None:
typedModel = guid_obj.referent
if hasattr(typedModel, 'absolute_api_v2_url'):
abs_url = typedModel.absolute_api_v2_url
if abs_url is not None:
enqueue_task(ban_url.s(abs_url))
else:
logger.error('Cannot ban None url for {} with id {}'.format(instance._name, instance._id))
|
Make migration reverse no-op a valid SQL query
When using a PostgreSQL database with Django 1.7 empty reverse query
statements in DB migrations cause an error, so we replace the empty
no-op statement with a valid query that still does nothing so the
reverse migration will work in this case.
This problem doesn't seem to affect Django 1.8, which must be smarter
about accepted but not actually running empty statements in DB
migrations.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_events', '0011_event_show_in_calendar'),
]
operations = [
migrations.AlterModelTable(
name='event',
table=None,
),
migrations.AlterModelTable(
name='recurrencerule',
table=None,
),
migrations.RunSQL(
"UPDATE django_content_type SET app_label='icekit_events' WHERE app_label='eventkit'",
# No-op: I haven't yet found a way to make this reversible in the
# way you would expect without unique constraint DB errors, whereas
# it works (according to unit tests at least) with a no-op.
"UPDATE django_content_type SET app_label=app_label WHERE app_label='NONE!'",
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_events', '0011_event_show_in_calendar'),
]
operations = [
migrations.AlterModelTable(
name='event',
table=None,
),
migrations.AlterModelTable(
name='recurrencerule',
table=None,
),
migrations.RunSQL(
"UPDATE django_content_type SET app_label='icekit_events' WHERE app_label='eventkit'",
# No-op: I haven't yet found a way to make this reversible in the
# way you would expect without unique constraint DB errors, whereas
# it works (according to unit tests at least) with a no-op.
"",
),
]
|
Add command to allow reset with longpress on both a and b.
|
var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
//var e = nobleEmitter.connect(peripheralUuid, serviceUuid, characteristicUuid);
var e = (process.env.DEVICE) ?
require('./serialport')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a'); // single click
},
1: function () {
emitScore('b'); // single click
},
2: function () {
emitUndo('a'); // double click
},
3: function () {
emitUndo('b'); // double click
},
4: function () {
hardware.emit('restart'); // long press
},
5: function () {
hardware.emit('restart'); // long press
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
|
var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
//var e = nobleEmitter.connect(peripheralUuid, serviceUuid, characteristicUuid);
var e = (process.env.DEVICE) ?
require('./serialport')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a');
},
1: function () {
emitScore('b');
},
2: function () {
emitUndo('a');
},
3: function () {
emitUndo('b');
},
4: function () {
hardware.emit('restart');
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
|
Modify abstract parameter to match its children
All instances of this already accept the parameter, so we should codify
it as part of the spec.
|
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class DocumentStore(object):
"""
Very basic implementation of a document store.
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_document(self, doc_id):
pass
@abstractmethod
def save_document(self, doc_id, document):
pass
@abstractmethod
def delete_document(self, doc_id):
pass
def iter_document_ids(self, last_id=None):
# todo: can convert to @abstractmethod once subclasses handle it
raise NotImplementedError('this function not yet implemented')
def iter_documents(self, ids):
# todo: can convert to @abstractmethod once subclasses handle it
raise NotImplementedError('this function not yet implemented')
class ReadOnlyDocumentStore(DocumentStore):
def save_document(self, doc_id, document):
raise NotImplementedError('This document store is read only!')
def delete_document(self, doc_id):
raise NotImplementedError('This document store is read only!')
|
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class DocumentStore(object):
"""
Very basic implementation of a document store.
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_document(self, doc_id):
pass
@abstractmethod
def save_document(self, doc_id, document):
pass
@abstractmethod
def delete_document(self, doc_id):
pass
def iter_document_ids(self):
# todo: can convert to @abstractmethod once subclasses handle it
raise NotImplementedError('this function not yet implemented')
def iter_documents(self, ids):
# todo: can convert to @abstractmethod once subclasses handle it
raise NotImplementedError('this function not yet implemented')
class ReadOnlyDocumentStore(DocumentStore):
def save_document(self, doc_id, document):
raise NotImplementedError('This document store is read only!')
def delete_document(self, doc_id):
raise NotImplementedError('This document store is read only!')
|
Set state.video value to undefined
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
const YT_API = 'AIzaSyDqL_re6cE8YhtNr_O7GvX1SX3aQo1clyg';
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: undefined };
YTSearch({ key: YT_API, term: 'coc'}, (videos) => {
this.setState({ videos });
});
}
render() {
return (
<div>
<SearchBar />
<VideoList videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
const YT_API = 'AIzaSyDqL_re6cE8YhtNr_O7GvX1SX3aQo1clyg';
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: [] };
YTSearch({ key: YT_API, term: 'coc'}, (videos) => {
this.setState({ videos });
});
}
render() {
return (
<div>
<SearchBar />
<VideoList videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
|
Stop referencing Item and Items from view data.
|
<?php echo '<?xml version="1.0" encoding="utf-8"?>'; ?>
<feed xmlns="http://www.w3.org/2005/Atom"
xml:lang="en"
xml:base="<?= PROTOCOL_HOST_PORT . \CWA\APP_ROOT ?>">
<id><?= 'tag:' . DOMAIN . ',2015:' . $ControllerURL . ':feed/atom' ?></id>
<link rel="self" type="<?= \CWA\Net\HTTP\HttpResponse::getContentType() ?>" href="<?= $ControllerURL ?>?format=atom" />
<link rel="alternate" type="text/html" href="<?= $ControllerURL ?>" />
<updated><?= $LastUpdated->format(DateTime::ATOM) ?></updated>
<title><?= SITE_NAME ?></title>
<subtitle><?= SITE_SLOGAN ?></subtitle>
<author>
<name><?= SITE_AUTHOR ?></name>
<uri><?= PROTOCOL_HOST_PORT ?></uri>
</author>
<rights>Copyright (c) 2014-<?= date('Y') . ', ' . SITE_AUTHOR ?></rights>
<?php
$idPrefix = 'tag:' . DOMAIN . ',2015:' . $ModelType . ':';
require_once $this->pathToPartial;
?>
</feed>
|
<?php echo '<?xml version="1.0" encoding="utf-8"?>'; ?>
<feed xmlns="http://www.w3.org/2005/Atom"
xml:lang="en"
xml:base="<?= PROTOCOL_HOST_PORT . \CWA\APP_ROOT ?>">
<id><?= 'tag:' . DOMAIN . ',2015:' . $ControllerURL . ':feed/atom' ?></id>
<link rel="self" type="<?= \CWA\Net\HTTP\HttpResponse::getContentType() ?>" href="<?= $ControllerURL ?>?format=atom" />
<link rel="alternate" type="text/html" href="<?= $ControllerURL ?>" />
<updated><?php
$lastUpdated = null;
$field = $Items[0]->getUpdatedFieldName();
foreach ($Items as $item) { // Use the timestamp of the most recently updated item. -- cwells
if ($item->$field > $lastUpdated) $lastUpdated = $item->$field;
}
$lastUpdated = new DateTime($lastUpdated);
echo $lastUpdated->format(DateTime::ATOM);
?></updated>
<title><?= SITE_NAME ?></title>
<subtitle><?= SITE_SLOGAN ?></subtitle>
<author>
<name><?= SITE_AUTHOR ?></name>
<uri><?= PROTOCOL_HOST_PORT ?></uri>
</author>
<rights>Copyright (c) 2014-<?= date('Y') . ', ' . SITE_AUTHOR ?></rights>
<?php
$idPrefix = 'tag:' . DOMAIN . ',2015:' . $ModelType . ':';
require_once $this->pathToPartial;
?>
</feed>
|
Use embedded enum in alembic revision
Unlikely to matter here but like this it will work correctly even in a
future where someone may add new sources to the original enum (in that
case this particular revision should not add those newer ones, which
would be the case when using the imported enum)
|
"""Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
class _ProfilePictureSource(int, Enum):
standard = 0
identicon = 1
gravatar = 2
custom = 3
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
|
"""Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
from indico.modules.users.models.users import ProfilePictureSource
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
|
Test checking to deliberately break the build
|
package com.fenixinfotech.ehcache.playpen;
import net.sf.ehcache.CacheManager;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class CustomEhCacheTest
{
private static final Logger logger = LoggerFactory.getLogger(CustomEhCacheTest.class);
@Test
public void testCache()
{
assertTrue(false);
String testCacheName = "testCache";
int maxCacheEntries = 10;
CustomEhCache customEhCache = new CustomEhCache();
// Store some data
for (int i=1; i<=maxCacheEntries; i++)
{
customEhCache.putInCache(testCacheName, i, String.format("value %d", i));
}
// Check cache content
for (int i=1; i<=maxCacheEntries; i++)
{
Object cachedValue = customEhCache.getFromCache(testCacheName, i);
assertNotNull(cachedValue);
assertEquals(String.format("value %d", i), cachedValue);
}
}
}
|
package com.fenixinfotech.ehcache.playpen;
import net.sf.ehcache.CacheManager;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class CustomEhCacheTest
{
private static final Logger logger = LoggerFactory.getLogger(CustomEhCacheTest.class);
@Test
public void testCache()
{
String testCacheName = "testCache";
int maxCacheEntries = 10;
CustomEhCache customEhCache = new CustomEhCache();
// Store some data
for (int i=1; i<=maxCacheEntries; i++)
{
customEhCache.putInCache(testCacheName, i, String.format("value %d", i));
}
// Check cache content
for (int i=1; i<=maxCacheEntries; i++)
{
Object cachedValue = customEhCache.getFromCache(testCacheName, i);
assertNotNull(cachedValue);
assertEquals(String.format("value %d", i), cachedValue);
}
}
}
|
Test if the resource directory exists before reading it
|
const fs = require('fs-extra');
const RESOURCE_FOLDER = __dirname + '/../resources/';
const DESTINATION_FOLDER = __dirname + '/../out/';
/**
* Gives the list of resources defined for a preset.
*
* @param {String} presetName - Name of the preset
* @return {Array.<String>} List of the resources defined for this preset
*/
function availableResources(presetName) {
if (!fs.existsSync(RESOURCE_FOLDER + presetName)) {
return [];
}
return fs.readdirSync(RESOURCE_FOLDER + presetName);
}
/**
* Copy the given list of resources for the given preset
*
* @param {String} presetName - Name of the preset
* @param {Array.<String>} resourceNames - Names of the resources which should be added
*/
function copyResources(presetName, resourceNames) {
if (!fs.existsSync(DESTINATION_FOLDER + presetName)) {
fs.mkdirSync(DESTINATION_FOLDER + presetName);
}
resourceNames.forEach(resourceName => fs.copySync(RESOURCE_FOLDER + presetName + '/' + resourceName, DESTINATION_FOLDER + presetName + '/' + resourceName));
}
module.exports = {
availableResources,
copyResources,
};
|
const fs = require('fs-extra');
const RESOURCE_FOLDER = __dirname + '/../resources/';
const DESTINATION_FOLDER = __dirname + '/../out/';
/**
* Gives the list of resources defined for a preset.
*
* @param {String} presetName - Name of the preset
* @return {Array.<String>} List of the resources defined for this preset
*/
function availableResources(presetName) {
return fs.readdirSync(RESOURCE_FOLDER + presetName).filter(fileName => fileName !== '.DS_Store');
}
/**
* Copy the given list of resources for the given preset
*
* @param {String} presetName - Name of the preset
* @param {Array.<String>} resourceNames - Names of the resources which should be added
*/
function copyResources(presetName, resourceNames) {
if (!fs.existsSync(DESTINATION_FOLDER + presetName)) {
fs.mkdirSync(DESTINATION_FOLDER + presetName);
}
resourceNames.forEach(resourceName => fs.copySync(RESOURCE_FOLDER + presetName + '/' + resourceName, DESTINATION_FOLDER + presetName + '/' + resourceName));
}
module.exports = {
availableResources,
copyResources,
};
|
Add request to inside of try
|
import requests
import os
class UnauthorizedToken(Exception):
pass
class UdacityConnection:
def __init__(self):
self.certifications_url = 'https://review-api.udacity.com/api/v1/me/certifications.json'
token = os.environ.get('UDACITY_AUTH_TOKEN')
self.headers = {'Authorization': token, 'Content-Length': '0'}
def certifications(self):
try:
raw_response = requests.get(self.certifications_url, headers=self.headers)
response = raw_response.json()
certifications_list = [item['project_id'] for item in response if item['status'] == 'certified']
return certifications_list
except requests.exceptions.HTTPError:
raise UnauthorizedToken
|
import requests
import os
class UnauthorizedToken(Exception):
pass
class UdacityConnection:
def __init__(self):
self.certifications_url = 'https://review-api.udacity.com/api/v1/me/certifications.json'
token = os.environ.get('UDACITY_AUTH_TOKEN')
self.headers = {'Authorization': token, 'Content-Length': '0'}
def certifications(self):
raw_response = requests.get(self.certifications_url, headers=self.headers)
try:
response = raw_response.json()
certifications_list = [item['project_id'] for item in response if item['status'] == 'certified']
return certifications_list
except requests.exceptions.HTTPError:
raise UnauthorizedToken
|
Hide debug logs by default
|
package behave.tools;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
//TODO use some proper logging framework
public class Log {
private static boolean m_logDebug = false;
private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss:SSS");
public static void debug(String msg) {
if (m_logDebug)
print("debug", msg);
}
public static void info(String msg) {
print("info", msg);
}
public static void warning(String msg) {
print("warning", msg);
}
public static void error(String msg) {
print("error", msg);
}
private static void print(String level, String msg) {
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now) + " [" + level + "] : " + msg);
}
}
|
package behave.tools;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
//TODO use some proper logging framework
public class Log {
private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss:SSS");
public static void debug(String msg) {
print("debug", msg);
}
public static void info(String msg) {
print("info", msg);
}
public static void warning(String msg) {
print("warning", msg);
}
public static void error(String msg) {
print("error", msg);
}
private static void print(String level, String msg) {
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now) + " [" + level + "] : " + msg);
}
}
|
Rename package oracle-paas -> nodeconductor-paas-oracle
|
#!/usr/bin/env python
from setuptools import setup, find_packages
dev_requires = [
'Sphinx==1.2.2',
]
install_requires = [
'nodeconductor>=0.95.0',
]
setup(
name='nodeconductor-paas-oracle',
version='0.1.0',
author='OpenNode Team',
author_email='info@opennodecloud.com',
url='http://nodeconductor.com',
description='Plugin for custom Oracle PaaS',
long_description=open('README.rst').read(),
package_dir={'': 'src'},
packages=find_packages('src', exclude=['*.tests', '*.tests.*', 'tests.*', 'tests']),
install_requires=install_requires,
zip_safe=False,
extras_require={
'dev': dev_requires,
},
entry_points={
'nodeconductor_extensions': (
'oracle_paas = oracle_paas.extension:OracleExtension',
),
},
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: Apache v2',
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
dev_requires = [
'Sphinx==1.2.2',
]
install_requires = [
'nodeconductor>=0.95.0',
]
setup(
name='oracle-paas',
version='0.1.0',
author='OpenNode Team',
author_email='info@opennodecloud.com',
url='http://nodeconductor.com',
description='Plugin for custom Oracle PaaS',
long_description=open('README.rst').read(),
package_dir={'': 'src'},
packages=find_packages('src', exclude=['*.tests', '*.tests.*', 'tests.*', 'tests']),
install_requires=install_requires,
zip_safe=False,
extras_require={
'dev': dev_requires,
},
entry_points={
'nodeconductor_extensions': (
'oracle_paas = oracle_paas.extension:OracleExtension',
),
},
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: Apache v2',
],
)
|
Remove unused machines and prefix vars
|
package etcd
import (
"errors"
"github.com/coreos/go-etcd/etcd"
"github.com/kelseyhightower/confd/config"
"path/filepath"
"strings"
)
func GetValues(keys []string) (map[string]interface{}, error) {
vars := make(map[string]interface{})
c := etcd.NewClient()
success := c.SetCluster(config.EtcdNodes())
if !success {
return vars, errors.New("cannot connect to etcd cluster")
}
r := strings.NewReplacer("/", "_")
for _, key := range keys {
values, err := c.Get(filepath.Join(config.Prefix(), key))
if err != nil {
return vars, err
}
for _, v := range values {
key := strings.TrimPrefix(v.Key, config.Prefix())
key = strings.TrimPrefix(key, "/")
new_key := r.Replace(key)
vars[new_key] = v.Value
}
}
return vars, nil
}
|
package etcd
import (
"errors"
"github.com/coreos/go-etcd/etcd"
"github.com/kelseyhightower/confd/config"
"path/filepath"
"strings"
)
var machines = []string{
"http://127.0.0.1:4001",
}
var prefix string = "/"
func GetValues(keys []string) (map[string]interface{}, error) {
vars := make(map[string]interface{})
c := etcd.NewClient()
success := c.SetCluster(config.EtcdNodes())
if !success {
return vars, errors.New("cannot connect to etcd cluster")
}
r := strings.NewReplacer("/", "_")
for _, key := range keys {
values, err := c.Get(filepath.Join(config.Prefix(), key))
if err != nil {
return vars, err
}
for _, v := range values {
key := strings.TrimPrefix(v.Key, config.Prefix())
key = strings.TrimPrefix(key, "/")
new_key := r.Replace(key)
vars[new_key] = v.Value
}
}
return vars, nil
}
|
Add CombatHelper class and getters/setters for modifiers.
|
const Type = require('./type').Type;
/*
* These functions take an entity (npc/player)
* and return the correct method or property
* depending on type.
*/
const getName = entity => Type.isPlayer(entity) ?
entity.getName() :
entity.getShortDesc('en');
const getSpeed = entity => entity.getAttackSpeed;
const getWeapon = entity => Type.isPlayer(entity) ?
entity.getEquipped('wield', true) :
entity.getAttack('en');
const getOffhand = entity => Type.isPlayer(entity) ?
entity.getEquipped('offhand', true) :
null; //TODO: allow for dual attacks for npcs
const getBodyParts = entity => Type.isPlayer(entity) ?
playerBodyParts :
entity.getBodyParts();
function CombatHelper(entity) {
this.entity = entity;
/*
* Example: { 'berserk': damage => damage * 2 }
*/
this.speedMods = {};
this.damageMods = {};
this.toHitMods = {};
this.addSpeedMod = addMod('speedMods');
this.addDamageMod = addMod('damageMods');
this.addToHitMod = addMod('toHitMods');
function addMod(type) {
return modifier => this[type][modifier.name] = modifier.effect;
}
this.removeSpeedMod = deleteMod('speedMods');
this.removeDamageMod = deleteMod('damageMods');
this.removeToHitMod = deleteMod('toHitMods');
function deleteMod(type) {
return name => delete this[type][name];
}
return this;
}
function get(entity) {
return new CombatHelper(entity);
}
exports.CombatUtil = { get };
|
const Type = require('./type').Type;
/*
* These functions take an entity (npc/player)
* and return the correct method or property
* depending on type.
*/
const getName = entity => Type.isPlayer(entity) ?
entity.getName() :
entity.getShortDesc('en');
const getSpeed = entity => entity.getAttackSpeed;
const getWeapon = entity => Type.isPlayer(entity) ?
entity.getEquipped('wield', true) :
entity.getAttack('en');
const getOffhand = entity => Type.isPlayer(entity) ?
entity.getEquipped('offhand', true) :
null; //TODO: allow for dual attacks for npcs
const getBodyParts = entity => Type.isPlayer(entity) ?
playerBodyParts :
entity.getBodyParts();
function get(entity) {
const name = getName(entity);
const getSpeed = getSpeed(entity);
const weapon = getWeapon(entity);
const offhand = getOffhand(entity);
const locations = getBodyParts(entity);
return {
name,
getSpeed,
weapon,
offhand,
locations
};
}
exports.CombatUtil = { get };
|
[tests] Remove test for deprecated createmultsig option
|
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], []]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses")
# assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()])
# self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()])
#
# There are currently no deprecated RPC methods in master, so this
# test is currently empty.
pass
if __name__ == '__main__':
DeprecatedRpcTest().main()
|
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], ["-deprecatedrpc=createmultisig"]]
def run_test(self):
self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses")
assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()])
self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()])
if __name__ == '__main__':
DeprecatedRpcTest().main()
|
Add console script and test requirements.
|
from distutils.core import setup
import os
setup(
name='python-jambel',
version='0.1',
py_module=['jambel'],
url='http://github.com/jambit/python-jambel',
license='UNKNOWN',
author='Sebastian Rahlf',
author_email='sebastian.rahlf@jambit.com',
description="Interface to jambit's project traffic lights.",
long_description=open(os.path.join(os.path.dirname(__file__), 'README.txt')).read(),
test_requires=['pytest'],
entry_points={
'console_scripts': [
'jambel = jambel:main',
]
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: Other/Proprietary License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
]
)
|
from distutils.core import setup
import os
setup(
name='python-jambel',
version='0.1',
py_module=['jambel'],
url='http://github.com/jambit/python-jambel',
license='UNKNOWN',
author='Sebastian Rahlf',
author_email='sebastian.rahlf@jambit.com',
description="Interface to jambit's project traffic lights.",
long_description=open(os.path.join(os.path.dirname(__file__), 'README.txt')).read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: Other/Proprietary License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
]
)
|
Fix provideConfig() in configure using event.type instead of event.name
|
const { next, hookStart, hookEnd } = require('hooter/effects')
const assignDefaults = require('./assignDefaults')
const validateConfig = require('./validateConfig')
const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error']
module.exports = function* configurePlugin() {
let schema, config
function* provideConfig(...args) {
let event = this.name
if (!config && event !== 'error') {
throw new Error(
`The config must already be defined at the beginning of "${event}"`
)
}
return yield next(config, ...args)
}
yield hookEnd('schema', function* (_schema) {
schema = yield next(_schema).or(_schema)
return schema
})
yield hookStart('configure', function* (_config) {
return yield next(schema, _config)
})
yield hookStart('configure', function* (_schema, _config) {
_config = assignDefaults(_schema, _config)
return yield next(_schema, _config)
})
yield hookEnd('configure', function* (_schema, _config) {
validateConfig(_schema, _config)
config = yield next(_schema, _config).or(_config)
return config
})
for (let event of EVENTS_WITH_CONFIG) {
yield hookStart(event, provideConfig)
}
}
|
const { next, hookStart, hookEnd } = require('hooter/effects')
const assignDefaults = require('./assignDefaults')
const validateConfig = require('./validateConfig')
const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error']
module.exports = function* configurePlugin() {
let schema, config
function* provideConfig(...args) {
let event = this.type
if (!config && event !== 'error') {
throw new Error(
`The config must already be defined at the beginning of "${event}"`
)
}
return yield next(config, ...args)
}
yield hookEnd('schema', function* (_schema) {
schema = yield next(_schema).or(_schema)
return schema
})
yield hookStart('configure', function* (_config) {
return yield next(schema, _config)
})
yield hookStart('configure', function* (_schema, _config) {
_config = assignDefaults(_schema, _config)
return yield next(_schema, _config)
})
yield hookEnd('configure', function* (_schema, _config) {
validateConfig(_schema, _config)
config = yield next(_schema, _config).or(_config)
return config
})
for (let event of EVENTS_WITH_CONFIG) {
yield hookStart(event, provideConfig)
}
}
|
Replace Array.includes with utility function for IE11 compat 🐲
|
import { entries } from '../utils/object-utils';
import { contains } from '../utils/array-utils';
export const VALID_ATTRIBUTES = [
'data-md-text-align'
];
/*
* A "mixin" to add section attribute support
* to markup and list sections.
*/
export function attributable(ctx) {
ctx.attributes = {};
ctx.setAttribute = (key, value) => {
if (!contains(VALID_ATTRIBUTES, key)) {
throw new Error(`Invalid attribute "${key}" was passed. Constrain attributes to the spec-compliant whitelist.`);
}
ctx.attributes[key] = value;
};
ctx.removeAttribute = key => {
delete ctx.attributes[key];
};
ctx.getAttribute = key => ctx.attributes[key];
ctx.eachAttribute = cb => {
entries(ctx.attributes).forEach(([k,v]) => cb(k,v));
};
}
|
import { entries } from '../utils/object-utils';
export const VALID_ATTRIBUTES = [
'data-md-text-align'
];
/*
* A "mixin" to add section attribute support
* to markup and list sections.
*/
export function attributable(ctx) {
ctx.attributes = {};
ctx.setAttribute = (key, value) => {
if (!VALID_ATTRIBUTES.includes(key)) {
throw new Error(`Invalid attribute "${key}" was passed. Constrain attributes to the spec-compliant whitelist.`);
}
ctx.attributes[key] = value;
};
ctx.removeAttribute = key => {
delete ctx.attributes[key];
};
ctx.getAttribute = key => ctx.attributes[key];
ctx.eachAttribute = cb => {
entries(ctx.attributes).forEach(([k,v]) => cb(k,v));
};
}
|
Update Mobile Oxford views to reflect use of app framework in
molly.maps.
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
from molly.conf import applications
admin.autodiscover()
urlpatterns = patterns('',
(r'adm/(.*)', admin.site.root),
# These are how we expect all applications to be eventually.
(r'^contact/', applications.contact.urls),
(r'^service-status/', applications.service_status.urls),
(r'^weather/', applications.weather.urls),
(r'^library/', applications.library.urls),
(r'^weblearn/', applications.weblearn.urls),
(r'^podcasts/', applications.podcasts.urls),
(r'^webcams/', applications.webcams.urls),
(r'^results/', applications.results.urls),
(r'^auth/', applications.auth.urls),
(r'^search/', applications.search.urls),
(r'^geolocation/', applications.geolocation.urls),
(r'^places/', applications.places.urls),
# These ones still need work
(r'^osm/', include('molly.osm.urls', 'osm', 'osm')),
(r'', include('molly.core.urls', 'core', 'core')),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site-media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.SITE_MEDIA_PATH})
)
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
from molly.conf import applications
admin.autodiscover()
urlpatterns = patterns('',
(r'adm/(.*)', admin.site.root),
# These are how we expect all applications to be eventually.
(r'^contact/', applications.contact.urls),
(r'^service-status/', applications.service_status.urls),
(r'^weather/', applications.weather.urls),
(r'^library/', applications.library.urls),
(r'^weblearn/', applications.weblearn.urls),
(r'^podcasts/', applications.podcasts.urls),
(r'^webcams/', applications.webcams.urls),
(r'^results/', applications.results.urls),
(r'^auth/', applications.auth.urls),
(r'^search/', applications.search.urls),
(r'^geolocation/', applications.geolocation.urls),
# These ones still need work
(r'^maps/', include('molly.maps.urls', 'maps', 'maps')),
(r'^osm/', include('molly.osm.urls', 'osm', 'osm')),
(r'', include('molly.core.urls', 'core', 'core')),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site-media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.SITE_MEDIA_PATH})
)
|
Remove unnecessary Hello World println
Change-Id: If4575dbbcd99c064fab3bc4d76c3f317c6c95c9a
|
/******************************************************************************
* Copyright Lajos Katona
*
* 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.
*****************************************************************************/
public class TheoremOfSummary {
public static int summary() {
return new TheoremOfSummary().summary(1, 10);
}
public static int summary(int start, int end) {
int sum = 0;
for(int i = start; i <= end; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
System.out.println(new TheoremOfSummary().summary());
}
}
|
/******************************************************************************
* Copyright Lajos Katona
*
* 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.
*****************************************************************************/
public class TheoremOfSummary {
public static int summary() {
return new TheoremOfSummary().summary(1, 10);
}
public static int summary(int start, int end) {
int sum = 0;
for(int i = start; i <= end; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
System.out.println("Hello, World");
System.out.println(new TheoremOfSummary().summary());
}
}
|
Support for completion callback with error
|
var exec = require('child_process').exec;
var self = module.exports;
/**
* Eject the specified disk drive.
* @param {int|string} id Locator for the disk drive.
* @param {Function} callback Optional callback for disk drive ejection completion / error.
*/
self.eject = function(id, callback) {
// are we running on mac?
if (process.platform === 'darwin') {
// setup optional argument, on mac, will default to 1
id = (typeof id === 'undefined') ? 1 : id;
exec('drutil tray eject ' + id, function(err, stdout, stderr) {
if (err && callback) {
// error occurred and callback exists
callback(err);
} else if (callback) {
// no error, but callback for completion
callback(null);
}
});
// are we running on linux?
} else if (process.platform === 'linux') {
// setup optional argument, on linux, will default to '' (empty string)
id = (typeof id === 'undefined') ? '' : id;
exec('eject ' + id, function(err, stdout, stderr) {
if (err && callback) {
callback(err);
} else if (callback) {
// no error, callback for completion
callback(null);
}
});
} else {
process.nextTick(callback.bind(null, 'unsupported platform: ' + process.platform));
}
};
|
var exec = require('child_process').exec;
var self = module.exports;
self.eject = function(id) {
// are we running on mac?
if (process.platform === 'darwin') {
// setup optional argument, on mac, will default to 1
id = (typeof id === 'undefined') ? 1 : id;
exec('drutil tray eject ' + id, function(err, stdout, stderr) {
if (err) {
console.log('ERROR: DiskDrive, when executing bash cmd: ' + err);
return;
}
// if it came here, it went all perfectly and it ejected.
});
// are we running on linux?
} else if (process.platform === 'linux') {
// setup optional argument, on linux, will default to '' (empty string)
id = (typeof id === 'undefined') ? '' : id;
exec('eject ' + id, function(err, stdout, stderr) {
if (err) {
console.log('ERROR: DiskDrive, when executing bash cmd: ' + err);
return;
}
// if it came here, it went all perfectly and it ejected.
});
} else {
console.log('ERROR: Unsupported DiskDrive platform (' + process.platform + ').');
}
};
|
Add error and detail field to captcha errors
|
from functools import wraps
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from rest_framework_captcha.models import Captcha
from rest_framework_captcha.helpers import get_settings, get_request_from_args
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
def protected_view(func):
@wraps(func)
def wrapper(*args, **kwargs):
request = get_request_from_args(*args)
uuid = request.META.get("HTTP_X_CAPTCHA_UUID", None)
secret = request.META.get("HTTP_X_CAPTCHA_SECRET", None)
time_limit = get_settings().get("EXPIRE_IN", 5*60)
if not uuid or not secret:
return Response({"error": True, "detail": "invalid_captcha_headers", "message": "This view is protected by captcha. You have to set headers X-Captcha-UUID and X-Captcha-Secret with valid values."}, status=400)
try:
captcha = Captcha.objects.get(uuid=uuid, secret__iexact=secret, fresh=True, created_at__gte=timezone.now() - relativedelta(seconds=time_limit))
except (Captcha.DoesNotExist, ValueError):
return Response({"error": True, "detail": "invalid_captcha", "message": "Invalid/expired captcha or incorrect secret."}, status=400)
captcha.fresh = False
captcha.save()
return func(*args, **kwargs)
return wrapper
|
from functools import wraps
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from rest_framework_captcha.models import Captcha
from rest_framework_captcha.helpers import get_settings, get_request_from_args
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
def protected_view(func):
@wraps(func)
def wrapper(*args, **kwargs):
request = get_request_from_args(*args)
uuid = request.META.get("HTTP_X_CAPTCHA_UUID", None)
secret = request.META.get("HTTP_X_CAPTCHA_SECRET", None)
time_limit = get_settings().get("EXPIRE_IN", 5*60)
if not uuid or not secret:
return Response({"message": "This view is protected by captcha. You have to set headers X-Captcha-UUID and X-Captcha-Secret with valid values."}, status=400)
try:
captcha = Captcha.objects.get(uuid=uuid, secret__iexact=secret, fresh=True, created_at__gte=timezone.now() - relativedelta(seconds=time_limit))
except (Captcha.DoesNotExist, ValueError):
return Response({"message": "Invalid/expired captcha or incorrect secret."}, status=400)
captcha.fresh = False
captcha.save()
return func(*args, **kwargs)
return wrapper
|
Fix KeyboardInterrupt exception filtering.
Add exception information and not just the stack trace.
Make the url easier to change at runtime.
Review URL: http://codereview.chromium.org/2109001
git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@47179 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
import socket
import sys
# Configure these values.
DEFAULT_URL = 'http://chromium-status.appspot.com/breakpad'
def SendStack(last_tb, stack, url=None):
if not url:
url = DEFAULT_URL
print 'Sending crash report ...'
try:
params = {
'args': sys.argv,
'stack': stack,
'user': getpass.getuser(),
'exception': last_tb,
}
request = urllib.urlopen(url, urllib.urlencode(params))
print request.read()
request.close()
except IOError:
print('There was a failure while trying to send the stack trace. Too bad.')
def CheckForException():
last_value = getattr(sys, 'last_value', None)
if last_value and not isinstance(last_value, KeyboardInterrupt):
last_tb = getattr(sys, 'last_traceback', None)
if last_tb:
SendStack(repr(last_value), ''.join(traceback.format_tb(last_tb)))
if (not 'test' in sys.modules['__main__'].__file__ and
socket.gethostname().endswith('.google.com')):
# Skip unit tests and we don't want anything from non-googler.
atexit.register(CheckForException)
|
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
import socket
import sys
def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
print 'Sending crash report ...'
try:
params = {
'args': sys.argv,
'stack': stack,
'user': getpass.getuser(),
}
request = urllib.urlopen(url, urllib.urlencode(params))
print request.read()
request.close()
except IOError:
print('There was a failure while trying to send the stack trace. Too bad.')
def CheckForException():
last_tb = getattr(sys, 'last_traceback', None)
if last_tb and sys.last_type is not KeyboardInterrupt:
SendStack(''.join(traceback.format_tb(last_tb)))
if (not 'test' in sys.modules['__main__'].__file__ and
socket.gethostname().endswith('.google.com')):
# Skip unit tests and we don't want anything from non-googler.
atexit.register(CheckForException)
|
Reset input if value is ""
|
Validator = {};
Validator.addValidator = function (index, el) { // This function is called in $().each(). The first arg will be an index. Though we dont need it
$el = $(el);
// Add function by tag name.
switch ($el.prop('tagName')) {
case 'INPUT':
switch ($el.attr('type')) {
case 'number': $el.change(Validator.validateNumber);
}
break;
case 'SELECT':
$el.change(Validator.validateSelection); break;
}
}
Validator.validateNumber = function () {
var $this = $(this);
var val = parseInt($this.val(),10);
if (isNaN(val)) val = $this.data('default');
var min = parseInt($this.attr('min')) || 0;
var max = parseInt($this.attr('max')) || 0;
if (val < min) val = min;
else if (val > max) val = max;
$this.val(val);
}
Validator.validateSelection = function () {
$this = $(this);
var val = $this.val();
var invalid = true;
var validOptions = $this.children().map(function(i,o){return $(o).val();});
for (var i = 0; i < validOptions.length && invalid; i++) {
if (val === validOptions[i]) invalid = false;
}
if (invalid) $this.val($this.data('default'));
}
|
Validator = {};
Validator.addValidator = function (index, el) { // This function is called in $().each(). The first arg will be an index. Though we dont need it
$el = $(el);
// Add function by tag name.
switch ($el.prop('tagName')) {
case 'INPUT':
switch ($el.attr('type')) {
case 'number': $el.change(Validator.validateNumber);
}
break;
case 'SELECT':
$el.change(Validator.validateSelection); break;
}
}
Validator.validateNumber = function () {
var $this = $(this);
var val = parseInt($this.val(),10) || 0;
var min = parseInt($this.attr('min')) || 0;
var max = parseInt($this.attr('max')) || 0;
if (val < min) val = min;
else if (val > max) val = max;
else return true;
$this.val(val);
}
Validator.validateSelection = function () {
$this = $(this);
var val = $this.val();
var invalid = true;
var validOptions = $this.children().map(function(i,o){return $(o).val();});
for (var i = 0; i < validOptions.length && invalid; i++) {
if (val === validOptions[i]) invalid = false;
}
if (invalid) $this.val($this.data('default'));
}
|
Remove junk code and comments.
|
var runway = require('./runway.js')
module.exports = runway
document.onclick = function(event) {
event = event || window.event // IE specials
var target = event.target || event.srcElement // IE specials
if (target.tagName === 'A') {
event.preventDefault()
processLink.call(target)
}
}
function processLink(){
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
goForward(href)
doRoute(href)
return false
}
return true
}
function doRoute(href){
var ctrl = runway.finder(href)
if (ctrl) ctrl()
}
function goForward(url){
if (history.pushState) history.pushState({url:url}, null, url)
else location.assign(url)
}
window.onpopstate = function(event){ doRoute(event.state.url) }
function init(){
// history.replaceState( {url:location.pathname}, null, location.pathname )
doRoute(location.pathname)
}
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init)
|
var runway = require('./runway.js')
module.exports = runway
document.onclick = function(event) {
event = event || window.event // IE specials
var target = event.target || event.srcElement // IE specials
if (target.tagName === 'A') {
event.preventDefault()
processLink.call(target)
}
}
function processLink(){
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
goForward(href)
doRoute(href)
return false
}
return true
}
function doRoute(href){
var ctrl = runway.finder(href)
if (ctrl) ctrl()
}
function goForward(url){
var title = Math.random().toString().split('.')[1]
if (history.pushState) history.pushState({url:url, title:title}, null, url)
else location.assign(url)
}
window.addEventListener('popstate',function(event){
doRoute(event.state.url)
})
window.onpopstate = function(event){
// doRoute(event.state.url)
// console.log( event )
// window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
}
function init(){
history.replaceState( {url:location.pathname}, null, location.pathname )
var ctrl = runway.finder(location.pathname)
if (ctrl) ctrl()
}
// setTimeout(init,100)
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init)
|
Make uids valid for use in URLs
|
/**
* Module dependencies
*/
var crypto = require('crypto');
/**
* The size ratio between a base64 string and the equivalent byte buffer
*/
var ratio = Math.log(64) / Math.log(256);
/**
* Make a Base64 string ready for use in URLs
*
* @param {String}
* @returns {String}
* @api private
*/
function urlReady(str) {
return str.replace(/\+/g, '_').replace(/\//g, '-');
}
/**
* Generate an Unique Id
*
* @param {Number} length The number of chars of the uid
* @param {Number} cb (optional) Callback for async uid generation
* @api public
*/
function uid(length, cb) {
var numbytes = Math.ceil(length * ratio);
if (typeof cb === 'undefined') {
return urlReady(crypto.randomBytes(numbytes).toString('base64').slice(0, length));
} else {
crypto.randomBytes(numbytes, function(err, bytes) {
if (err) return cb(err);
cb(null, urlReady(bytes.toString('base64').slice(0, length)));
})
}
}
/**
* Exports
*/
module.exports = uid;
|
/**
* Module dependencies
*/
var crypto = require('crypto');
/**
* The size ratio between a base64 string and the equivalent byte buffer
*/
var ratio = Math.log(64) / Math.log(256);
/**
* Generate an Unique Id
*
* @param {Number} length The number of chars of the uid
* @param {Number} cb (optional) Callback for async uid generation
* @api public
*/
function uid(length, cb) {
var numbytes = Math.ceil(length * ratio);
if (typeof cb === 'undefined') {
return crypto.randomBytes(numbytes).toString('base64').slice(0, length);
} else {
crypto.randomBytes(numbytes, function(err, bytes) {
if (err) return cb(err);
cb(null, bytes.toString('base64').slice(0, length));
})
}
}
/**
* Exports
*/
module.exports = uid;
|
Improve ui responsiveness if urls.path is databound
|
var m = angular.module("routeUrls", []);
m.factory("urls", function($route) {
var pathsByName = {};
angular.forEach($route.routes, function (route, path) {
if (route.name) {
pathsByName[route.name] = path;
}
});
var regexs = {};
var path = function (name, params) {
var url = pathsByName[name] || "/";
angular.forEach(params || {}, function (value, key) {
var regex = regexs[key];
if (regex === undefined) {
regex = regexs[key] = new RegExp(":" + key + "(/|$)");
}
url = url.replace(regex, value);
});
return url;
};
return {
path: path,
href: function (name, params) {
return "#" + path(name, params);
}
};
});
|
var m = angular.module("routeUrls", []);
m.factory("urls", function($route) {
var pathsByName = {};
angular.forEach($route.routes, function (route, path) {
if (route.name) {
pathsByName[route.name] = path;
}
});
var path = function (name, params) {
var url = pathsByName[name] || "/";
angular.forEach(params || {}, function (value, key) {
url = url.replace(new RegExp(":" + key + "(?=/|$)"), value);
});
return url;
};
return {
path: path,
href: function (name, params) {
return "#" + path(name, params);
}
};
});
|
Disable forgotten returns for server promises
|
require('babel-register');
require('babel-polyfill');
const Bluebird = require('bluebird');
const WebpackIsomorphicTools = require('webpack-isomorphic-tools');
const config = require('../common/config');
const rootDir = require('path').resolve(__dirname, '..', '..');
const webpackIsomorphicAssets = require('../../webpack/assets');
if (!process.env.NODE_ENV) {
throw new Error(
'Environment variable NODE_ENV must be set to development or production.'
);
}
// http://bluebirdjs.com/docs/why-bluebird.html
global.Promise = Bluebird;
Promise.config({
warnings: {
// Disables forgotten return statements warnings when await is used.
// "Warning: a promise was created in a handler but was not returned from it"
wForgottenReturn: false
}
});
// http://formatjs.io/guides/runtime-environments/#polyfill-node
if (global.Intl) {
// We don't have to check whether Node runtime supports specific language,
// because without special build it does support only english anyway.
require('intl');
global.Intl.NumberFormat = global.IntlPolyfill.NumberFormat;
global.Intl.DateTimeFormat = global.IntlPolyfill.DateTimeFormat;
} else {
global.Intl = require('intl');
}
global.webpackIsomorphicTools = new WebpackIsomorphicTools(webpackIsomorphicAssets)
.development(!config.isProduction)
.server(rootDir, () => {
require('./main');
});
|
require('babel-register');
require('babel-polyfill');
const Bluebird = require('bluebird');
const WebpackIsomorphicTools = require('webpack-isomorphic-tools');
const config = require('../common/config');
const rootDir = require('path').resolve(__dirname, '..', '..');
const webpackIsomorphicAssets = require('../../webpack/assets');
if (!process.env.NODE_ENV) {
throw new Error(
'Environment variable NODE_ENV must be set to development or production.'
);
}
// http://bluebirdjs.com/docs/why-bluebird.html
global.Promise = Bluebird;
// http://formatjs.io/guides/runtime-environments/#polyfill-node
if (global.Intl) {
// We don't have to check whether Node runtime supports specific language,
// because without special build it does support only english anyway.
require('intl');
global.Intl.NumberFormat = global.IntlPolyfill.NumberFormat;
global.Intl.DateTimeFormat = global.IntlPolyfill.DateTimeFormat;
} else {
global.Intl = require('intl');
}
global.webpackIsomorphicTools = new WebpackIsomorphicTools(webpackIsomorphicAssets)
.development(!config.isProduction)
.server(rootDir, () => {
require('./main');
});
|
Fix duplicated key not copying ID correctly
|
package net.mcft.copy.betterstorage;
import net.mcft.copy.betterstorage.items.ItemKey;
import net.mcft.copy.betterstorage.items.ItemLock;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.ICraftingHandler;
/** Handles key and lock crafting. */
public class CraftingHandler implements ICraftingHandler {
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) {
// If item crafted is a key, set its damage value to ..
if (item.getItem() instanceof ItemKey) {
int damage;
// .. another key's damage value, if it was crafted with one ..
ItemStack stack = craftMatrix.getStackInSlot(6);
if (stack == null) stack = craftMatrix.getStackInSlot(7);
if (stack != null && stack.getItem() instanceof ItemKey)
damage = stack.getItemDamage();
// .. or a random value, if not.
else damage = -32000 + BetterStorage.random.nextInt(64000);
item.setItemDamage(damage);
}
// If item crafted is a lock, copy the damage value from the key.
if (item.getItem() instanceof ItemLock)
item.setItemDamage(craftMatrix.getStackInSlot(4).getItemDamage());
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item) { }
}
|
package net.mcft.copy.betterstorage;
import net.mcft.copy.betterstorage.items.ItemKey;
import net.mcft.copy.betterstorage.items.ItemLock;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.ICraftingHandler;
/** Handles key and lock crafting. */
public class CraftingHandler implements ICraftingHandler {
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) {
// If item crafted is a key, set its damage value to ..
if (item.getItem() instanceof ItemKey) {
int damage;
// .. another key's damage value, if it was crafted with one.
ItemStack stack = craftMatrix.getStackInSlot(6);
if (stack != null && stack.getItem() instanceof ItemKey)
damage = stack.getItemDamage();
// .. a random value, if not.
else damage = -32000 + BetterStorage.random.nextInt(64000);
item.setItemDamage(damage);
}
// If item crafted is a lock, copy the damage value from the key.
if (item.getItem() instanceof ItemLock)
item.setItemDamage(craftMatrix.getStackInSlot(4).getItemDamage());
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item) { }
}
|
Add some additional logging for ajax failures.
|
// Common ajax-handling functions for dashboard-like pages. Looks for <reload/>
// elements to reload the page, and reports errors or failures via alerts.
g_action_url = "action.php";
// Note that this doesn't run if the $.ajax call has a 'success:' callback that
// generates an error.
$(document).ajaxSuccess(function(event, xhr, options, xmldoc) {
var fail = xmldoc.documentElement.getElementsByTagName("failure");
if (fail && fail.length > 0) {
console.log(xmldoc);
alert("Action failed: " + fail[0].textContent);
}
});
// <reload/> element
$(document).ajaxSuccess(function(event, xhr, options, xmldoc) {
var reload = xmldoc.documentElement.getElementsByTagName("reload");
if (reload && reload.length > 0) {
console.log('ajaxSuccess event: reloading page');
location.reload(true);
}
});
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
console.log("ajaxError: " + thrownError);
console.log(thrownError);
console.log(jqXHR);
console.log("Response text: " + jqXHR.responseText);
console.log("ReadyState: " + jqXHR.readyState);
console.log("status: " + jqXHR.status);
console.log(event);
alert("Ajax error: " + thrownError);
});
|
// Common ajax-handling functions for dashboard-like pages. Looks for <reload/>
// elements to reload the page, and reports errors or failures via alerts.
g_action_url = "action.php";
// Note that this doesn't run if the $.ajax call has a 'success:' callback that
// generates an error.
$(document).ajaxSuccess(function(event, xhr, options, xmldoc) {
var fail = xmldoc.documentElement.getElementsByTagName("failure");
if (fail && fail.length > 0) {
console.log(xmldoc);
alert("Action failed: " + fail[0].textContent);
}
});
// <reload/> element
$(document).ajaxSuccess(function(event, xhr, options, xmldoc) {
var reload = xmldoc.documentElement.getElementsByTagName("reload");
if (reload && reload.length > 0) {
console.log('ajaxSuccess event: reloading page');
location.reload(true);
}
});
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
console.log("ajaxError: " + thrownError);
console.log(thrownError);
console.log(jqXHR);
console.log(jqXHR.responseText);
console.log(event);
alert("Ajax error: " + thrownError);
});
|
Correct link to start controller in routing
|
'use strict';
angular.module('repicbro', ['repicbro.controllers',
'repicbro.services',
'repicbro.filters',
'ngRoute',
'ngTouch'])
.config(function ($routeProvider, $locationProvider, constants) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/views/start.html',
controller: 'StartCtrl'
})
.when('/r/:subreddit', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
angular.module('repicbro.controllers', ['repicbro.services']);
angular.module('repicbro.services', ['repicbro.constants']);
angular.module('repicbro.constants', []);
angular.module('repicbro.filters', []);
|
'use strict';
angular.module('repicbro', ['repicbro.controllers',
'repicbro.services',
'repicbro.filters',
'ngRoute',
'ngTouch'])
.config(function ($routeProvider, $locationProvider, constants) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/views/start.html',
controller: 'MainCtrl'
})
.when('/r/:subreddit', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
angular.module('repicbro.controllers', ['repicbro.services']);
angular.module('repicbro.services', ['repicbro.constants']);
angular.module('repicbro.constants', []);
angular.module('repicbro.filters', []);
|
Create and modify lines in same loop
|
import numpy as np
from lxml.etree import fromstring, XMLSyntaxError
def parse_lines(lines):
for line in lines:
try:
xml_line = fromstring(line.encode('utf-8'))
except XMLSyntaxError:
attrs = []
else:
attrs = [thing.tag for thing in xml_line.getiterator()]
line = list(xml_line.getiterator())[-1].text
yield line, attrs
def render_header_to(font, ax, sy, lines, sx=0.5):
calc = lambda q: q / 20
y_points = map(calc, np.arange(sy, 0, -0.5))
for y, (text, attrs) in zip(y_points, parse_lines(lines)):
line = ax.figure.text(sx, y, text, ha='center')
if 'b' in attrs:
line.set_weight('extra bold')
line.set_font_properties(font)
line.set_fontsize(25)
if 'i' in attrs:
line.set_style('italic')
return ax
|
from operator import itemgetter
import numpy as np
from lxml.etree import fromstring, XMLSyntaxError
def parse_lines(lines):
for line in lines:
try:
xml_line = fromstring(line.encode('utf-8'))
except XMLSyntaxError:
attrs = []
else:
attrs = [thing.tag for thing in xml_line.getiterator()]
line = list(xml_line.getiterator())[-1].text
yield line, attrs
def render_header_to(font, ax, sy, lines, sx=0.5):
calc = lambda q: q / 20
y_points = map(calc, np.arange(sy, 0, -0.5))
parsed = list(parse_lines(lines))
lines = map(itemgetter(0), parsed)
line_attrs = map(itemgetter(1), parsed)
lines = [
ax.figure.text(sx, y, text, ha='center')
for y, text in zip(y_points, lines)
]
for line, attrs in zip(lines, line_attrs):
if 'b' in attrs:
line.set_weight('extra bold')
line.set_font_properties(font)
line.set_fontsize(25)
if 'i' in attrs:
line.set_style('italic')
return ax
|
Use the new api for stringifying the box
|
// Dependencies
var Box = require("../lib");
// Create a simple box
var b1 = Box("20x10");
console.log(b1.toString());
// Set custom marks
var b2 = new Box({
w: 10
, h: 10
, stringify: false
, marks: {
nw: "╔"
, n: "══"
, ne: "╗"
, e: "║"
, se: "╝"
, s: "══"
, sw: "╚"
, w: "║"
, b: "░░"
}
});
console.log(b2.stringify());
// Box with text and use the stringify
var b3 = Box("20x10", "I will be \u001b[31mdis\u001b[0mplayed inside! \n A\u001b[34mnd I'm in a\u001b[0m new line!");
console.log(b3);
// Box with aligned text to top-right
var b4 = Box("30x20", {
text: "Box content"
, stretch: true
, autoEOL: true
, vAlign: "top"
, hAlign: "right"
});
console.log(b4);
// Full screen box
var b5 = Box({fullscreen: true, marks: {}}, "Hello World!");
console.log(b5.toString());
|
// Dependencies
var Box = require("../lib");
// Create a simple box
var b1 = new Box("20x10");
console.log(b1.toString());
// Set custom marks
var b2 = new Box({
w: 10
, h: 10
, marks: {
nw: "╔"
, n: "══"
, ne: "╗"
, e: "║"
, se: "╝"
, s: "══"
, sw: "╚"
, w: "║"
, b: "░░"
}
});
console.log(b2.toString());
// Box with text
var b3 = new Box("20x10", "I will be \u001b[31mdis\u001b[0mplayed inside! \n A\u001b[34mnd I'm in a\u001b[0m new line!");
console.log(b3.toString());
// Box with aligned text to top-right
var b4 = new Box("30x20", {
text: "Box content"
, stretch: true
, autoEOL: true
, vAlign: "top"
, hAlign: "right"
});
console.log(b4.toString());
// Full screen box
var b5 = new Box({fullscreen: true, marks: {}}, "Hello World!");
console.log(b5.toString());
|
Fix require for node v5
|
const assert = require('assert');
const crypto = require('./config').crypto;
const config = require('./config').config;
describe("WebCrypto", () => {
it("get random values", () => {
var buf = new Uint8Array(16);
var check = new Buffer(buf).toString("base64");
assert.notEqual(new Buffer(crypto.getRandomValues(buf)).toString("base64"), check, "Has no random values");
})
it("get random values with large buffer", () => {
var buf = new Uint8Array(65600);
assert.throws(() => {
crypto.getRandomValues(buf);
}, Error);
})
it("reset", (done) => {
const currentHandle = crypto.session.handle.toString("hex");
crypto.reset()
.then(() => {
crypto.login(config.pin);
const newHandle = crypto.session.handle.toString("hex");
assert(currentHandle !== newHandle, true, "handle of session wasn't changed");
})
.then(done, done);
})
})
|
const assert = require('assert');
const { crypto, config } = require('./config');
describe("WebCrypto", () => {
it("get random values", () => {
var buf = new Uint8Array(16);
var check = new Buffer(buf).toString("base64");
assert.notEqual(new Buffer(crypto.getRandomValues(buf)).toString("base64"), check, "Has no random values");
})
it("get random values with large buffer", () => {
var buf = new Uint8Array(65600);
assert.throws(() => {
crypto.getRandomValues(buf);
}, Error);
})
it("reset", (done) => {
const currentHandle = crypto.session.handle.toString("hex");
crypto.reset()
.then(() => {
crypto.login(config.pin);
const newHandle = crypto.session.handle.toString("hex");
assert(currentHandle !== newHandle, true, "handle of session wasn't changed");
})
.then(done, done);
})
})
|
Remove route54 provider because the driver is not finished yet.
git-svn-id: 9ad005ce451fa0ce30ad6352b03eb45b36893355@1340889 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.
from libcloud.utils.misc import get_driver as get_provider_driver
from libcloud.dns.types import Provider
DRIVERS = {
Provider.DUMMY:
('libcloud.dns.drivers.dummy', 'DummyDNSDriver'),
Provider.LINODE:
('libcloud.dns.drivers.linode', 'LinodeDNSDriver'),
Provider.ZERIGO:
('libcloud.dns.drivers.zerigo', 'ZerigoDNSDriver'),
Provider.RACKSPACE_US:
('libcloud.dns.drivers.rackspace', 'RackspaceUSDNSDriver'),
Provider.RACKSPACE_UK:
('libcloud.dns.drivers.rackspace', 'RackspaceUKDNSDriver')
}
def get_driver(provider):
return get_provider_driver(DRIVERS, provider)
|
# 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.
from libcloud.utils.misc import get_driver as get_provider_driver
from libcloud.dns.types import Provider
DRIVERS = {
Provider.DUMMY:
('libcloud.dns.drivers.dummy', 'DummyDNSDriver'),
Provider.LINODE:
('libcloud.dns.drivers.linode', 'LinodeDNSDriver'),
Provider.ZERIGO:
('libcloud.dns.drivers.zerigo', 'ZerigoDNSDriver'),
Provider.RACKSPACE_US:
('libcloud.dns.drivers.rackspace', 'RackspaceUSDNSDriver'),
Provider.RACKSPACE_UK:
('libcloud.dns.drivers.rackspace', 'RackspaceUKDNSDriver'),
Provider.ROUTE53:
('libcloud.dns.drivers.route53', 'Route53DNSDriver')
}
def get_driver(provider):
return get_provider_driver(DRIVERS, provider)
|
Fix handling of hidden form field values via AJAX
See #3053
|
<?php
namespace wcf\system\form\builder\field;
/**
* Implementation of a form field for a hidden input field that is not visible in the rendered form.
*
* @author Matthias Schmidt
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Form\Builder\Field
* @since 5.2
*/
class HiddenFormField extends AbstractFormField {
/**
* @inheritDoc
*/
protected $javaScriptDataHandlerModule = 'WoltLabSuite/Core/Form/Builder/Field/Value';
/**
* @inheritDoc
*/
protected $templateName = '__hiddenFormField';
/**
* @inheritDoc
*/
public function readValue() {
if ($this->getDocument()->hasRequestData($this->getPrefixedId())) {
$this->value = $this->getDocument()->getRequestData($this->getPrefixedId());
}
return $this;
}
}
|
<?php
namespace wcf\system\form\builder\field;
/**
* Implementation of a form field for a hidden input field that is not visible in the rendered form.
*
* @author Matthias Schmidt
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Form\Builder\Field
* @since 5.2
*/
class HiddenFormField extends AbstractFormField {
/**
* @inheritDoc
*/
protected $templateName = '__hiddenFormField';
/**
* @inheritDoc
*/
public function readValue() {
if ($this->getDocument()->hasRequestData($this->getPrefixedId())) {
$this->value = $this->getDocument()->getRequestData($this->getPrefixedId());
}
return $this;
}
}
|
Store OpenSeadragon.Viewer instantiation object handle
|
//= require openseadragon
(function($) {
var __osd_counter = 0;
function generateOsdId() {
__osd_counter++;
return "Openseadragon" + __osd_counter;
}
function initOpenSeadragon() {
$('picture[data-openseadragon]').each(function() {
var $picture = $(this);
if (typeof $picture.attr('id') === "undefined") {
$picture.attr('id', generateOsdId());
}
var collectionOptions = $picture.data('openseadragon');
var sources = $picture.find('source[media="openseadragon"]');
var tilesources = $.map(sources, function(e) {
if ($(e).data('openseadragon')) {
return $(e).data('openseadragon');
} else {
return $(e).attr('src');
}
});
$picture.css("display", "block");
$picture.css("height", "500px");
$picture.data('osdViewer', OpenSeadragon(
$.extend({ id: $picture.attr('id') }, collectionOptions, { tileSources: tilesources })
));
});
};
window.onload = initOpenSeadragon;
document.addEventListener("page:load", initOpenSeadragon);
})(jQuery);
|
//= require openseadragon
(function($) {
var __osd_counter = 0;
function generateOsdId() {
__osd_counter++;
return "Openseadragon" + __osd_counter;
}
function initOpenSeadragon() {
$('picture[data-openseadragon]').each(function() {
var $picture = $(this);
if (typeof $picture.attr('id') === "undefined") {
$picture.attr('id', generateOsdId());
}
var collectionOptions = $picture.data('openseadragon');
var sources = $picture.find('source[media="openseadragon"]');
var tilesources = $.map(sources, function(e) {
if ($(e).data('openseadragon')) {
return $(e).data('openseadragon');
} else {
return $(e).attr('src');
}
});
$picture.css("display", "block");
$picture.css("height", "500px");
OpenSeadragon(
$.extend({ id: $picture.attr('id') }, collectionOptions, { tileSources: tilesources })
);
});
};
window.onload = initOpenSeadragon;
document.addEventListener("page:load", initOpenSeadragon);
})(jQuery);
|
Hide (instead of fade out) badge on iPhone
|
$(document).ready(function() {
function updateAssessmentFormState() {
var numberOfQuestions = $('#assessment .legend').length;
var numberOfCheckedAnswers = $('#assessment input:checked').length;
var numberOfUnansweredQuestions = numberOfQuestions - numberOfCheckedAnswers;
var unansweredQuestionsBadge = $('#assessment .badge');
if (numberOfUnansweredQuestions > 0) {
var unansweredQuestionsBadgeText = numberOfUnansweredQuestions + ' unanswered question';
if (numberOfUnansweredQuestions > 1) {
unansweredQuestionsBadgeText += 's';
}
unansweredQuestionsBadge.text(unansweredQuestionsBadgeText);
} else {
$('.touch #assessment .badge').hide();
unansweredQuestionsBadge.fadeOut();
$('#assessment input[type=submit]').removeAttr('disabled');
$('.touch #assessment .span4').addClass('collapse-height');
}
}
$('#assessment').on('click', 'input[type=radio]', updateAssessmentFormState);
var cancelButton = $('#assessment input[type=button]');
cancelButton.click(function() {
location.href = cancelButton.attr('data-course-path');
});
$('.touch #assessment label').click(function() {
$(this).children('input').attr('checked', 'checked');
updateAssessmentFormState();
});
});
|
$(document).ready(function() {
function updateAssessmentFormState() {
var numberOfQuestions = $('#assessment .legend').length;
var numberOfCheckedAnswers = $('#assessment input:checked').length;
var numberOfUnansweredQuestions = numberOfQuestions - numberOfCheckedAnswers;
var unansweredQuestionsBadge = $('#assessment .badge');
if (numberOfUnansweredQuestions > 0) {
var unansweredQuestionsBadgeText = numberOfUnansweredQuestions + ' unanswered question';
if (numberOfUnansweredQuestions > 1) {
unansweredQuestionsBadgeText += 's';
}
unansweredQuestionsBadge.text(unansweredQuestionsBadgeText);
} else {
unansweredQuestionsBadge.fadeOut();
$('#assessment input[type=submit]').removeAttr('disabled');
$('.touch #assessment .span4').addClass('collapse-height');
}
}
$('#assessment').on('click', 'input[type=radio]', updateAssessmentFormState);
var cancelButton = $('#assessment input[type=button]');
cancelButton.click(function() {
location.href = cancelButton.attr('data-course-path');
});
$('.touch #assessment label').click(function() {
$(this).children('input').attr('checked', 'checked');
updateAssessmentFormState();
});
});
|
Fix browser conflicts for test suite
|
var env = require('./environment.js');
// A small suite to make sure the cucumber framework works.
exports.config = {
seleniumAddress: env.seleniumAddress,
framework: 'custom',
frameworkPath: '../index.js',
// Spec patterns are relative to this directory.
specs: [
'cucumber/*.feature'
],
multiCapabilities: [
{
browserName: (process.env.TEST_BROWSER_NAME || 'chrome'),
version: (process.env.TEST_BROWSER_VERSION || 'ANY'),
cucumberOpts: {
tags: '@dev',
format: 'pretty'
}
}
],
baseUrl: env.baseUrl,
cucumberOpts: {
require: 'cucumber/**/stepDefinitions.js',
tags: '@failing',
format: 'progress',
profile: false,
'no-source': true
}
};
|
var env = require('./environment.js');
// A small suite to make sure the cucumber framework works.
exports.config = {
seleniumAddress: env.seleniumAddress,
framework: 'custom',
frameworkPath: '../index.js',
// Spec patterns are relative to this directory.
specs: [
'cucumber/*.feature'
],
multiCapabilities: [
{
browserName: 'chrome',
version: 'ANY',
cucumberOpts: {
tags: '@dev',
format: 'pretty'
}
}
],
baseUrl: env.baseUrl,
cucumberOpts: {
require: 'cucumber/**/stepDefinitions.js',
tags: '@failing',
format: 'progress',
profile: false,
'no-source': true
}
};
|
Allow modules to set base dir name
|
<?php
namespace ATP;
class Module
{
protected $_moduleName = "";
protected $_moduleBaseDir = "vendor";
public function onBootstrap(\Zend\Mvc\MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new \Zend\Mvc\ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include "{$this->_moduleBaseDir}/{$this->_moduleName}/config/module.config.php";
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
$this->_moduleName => "{$this->_moduleBaseDir}/{$this->_moduleName}/src/{$this->_moduleName}",
),
),
);
}
}
|
<?php
namespace ATP;
class Module
{
protected $_moduleName = "";
public function onBootstrap(\Zend\Mvc\MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new \Zend\Mvc\ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include "module/{$this->_moduleName}/config/module.config.php";
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
$this->_moduleName => "module/{$this->_moduleName}/src/{$this->_moduleName}",
),
),
);
}
}
|
Update to new alabaster-driven nav sidebar
|
from datetime import datetime
import os
import sys
import alabaster
# Alabaster theme
html_theme_path = [alabaster.get_path()]
# Paths relative to invoking conf.py - not this shared file
html_static_path = ['../_shared_static']
html_theme = 'alabaster'
html_theme_options = {
'description': "A Python implementation of SSHv2.",
'github_user': 'paramiko',
'github_repo': 'paramiko',
'gittip_user': 'bitprophet',
'analytics_id': 'UA-18486793-2',
'extra_nav_links': {
"API Docs": 'http://docs.paramiko.org',
},
'link': '#3782BE',
'link_hover': '#3782BE',
}
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'searchbox.html',
'donate.html',
]
}
# Regular settings
project = u'Paramiko'
year = datetime.now().year
copyright = u'2013-%d Jeff Forcier, 2003-2012 Robey Pointer' % year
master_doc = 'index'
templates_path = ['_templates']
exclude_trees = ['_build']
source_suffix = '.rst'
default_role = 'obj'
|
from datetime import datetime
import os
import sys
import alabaster
# Alabaster theme
html_theme_path = [alabaster.get_path()]
# Paths relative to invoking conf.py - not this shared file
html_static_path = ['../_shared_static']
html_theme = 'alabaster'
html_theme_options = {
'description': "A Python implementation of SSHv2.",
'github_user': 'paramiko',
'github_repo': 'paramiko',
'gittip_user': 'bitprophet',
'analytics_id': 'UA-18486793-2',
'link': '#3782BE',
'link_hover': '#3782BE',
}
html_sidebars = {
# Landing page (no ToC)
'index': [
'about.html',
'searchbox.html',
'donate.html',
],
# Inner pages get a ToC
'**': [
'about.html',
'localtoc.html',
'searchbox.html',
'donate.html',
]
}
# Regular settings
project = u'Paramiko'
year = datetime.now().year
copyright = u'2013-%d Jeff Forcier, 2003-2012 Robey Pointer' % year
master_doc = 'index'
templates_path = ['_templates']
exclude_trees = ['_build']
source_suffix = '.rst'
default_role = 'obj'
|
Add new fields to the task model
|
from django.db import models
from django.utils import timezone
class Task(models.Model):
EQUALS_CHECK = 'EQ'
REGEX_CHECK = 'RE'
CHECK_CHOICES = (
(EQUALS_CHECK, 'Equals'),
(REGEX_CHECK, 'Regex'),
)
title_ru = models.CharField(null=False, blank=False, max_length=256)
title_en = models.CharField(null=False, blank=False, max_length=256)
category = models.CharField(null=False, blank=False, max_length=256)
cost = models.IntegerField(null=False, blank=False)
desc_ru = models.TextField(null=False, blank=False)
desc_en = models.TextField(null=False, blank=False)
writeup_ru = models.TextField(null=False, blank=False)
writeup_en = models.TextField(null=False, blank=False)
flag = models.CharField(max_length=1024)
is_case_insensitive_check = models.BooleanField(default=False)
is_trimmed_check = models.BooleanField(default=False)
check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES)
created_at = models.DateTimeField(null=False, blank=True)
def save(self, *args, **kwargs):
if self.pk is None:
self.created_at = timezone.now()
return super(Task, self).save(*args, **kwargs)
|
from django.db import models
from django.utils import timezone
class Task(models.Model):
EQUALS_CHECK = 'EQ'
REGEX_CHECK = 'RE'
CHECK_CHOICES = (
(EQUALS_CHECK, 'Equals'),
(REGEX_CHECK, 'Regex'),
)
title_ru = models.CharField(null=False, blank=False, max_length=256)
title_en = models.CharField(null=False, blank=False, max_length=256)
desc_ru = models.TextField(null=False, blank=False)
desc_en = models.TextField(null=False, blank=False)
writeup_ru = models.TextField(null=False, blank=False)
writeup_en = models.TextField(null=False, blank=False)
flag = models.CharField(max_length=1024)
is_case_insensitive_check = models.BooleanField(default=False)
is_trimmed_check = models.BooleanField(default=False)
check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES)
created_at = models.DateTimeField(null=False, blank=True)
def save(self, *args, **kwargs):
if self.pk is None:
self.created_at = timezone.now()
return super(Task, self).save(*args, **kwargs)
|
[Fix] Fix EventWeather not triggering properly
|
package me.deftware.mixin.mixins;
import me.deftware.client.framework.event.events.EventWeather;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.LightmapTextureManager;
import net.minecraft.client.render.WorldRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(WorldRenderer.class)
public class MixinWorldRenderer {
@Inject(method = "method_22713", at = @At("HEAD"), cancellable = true)
private void renderRain(Camera camera, CallbackInfo ci) {
EventWeather event = new EventWeather(EventWeather.WeatherType.Rain);
event.broadcast();
if (event.isCanceled()) {
ci.cancel();
}
}
@Inject(method = "renderWeather", at = @At("HEAD"), cancellable = true)
private void renderWeather(LightmapTextureManager manager, float f, double d, double e, double g, CallbackInfo ci) {
EventWeather event = new EventWeather(EventWeather.WeatherType.Rain);
event.broadcast();
if (event.isCanceled()) {
ci.cancel();
}
}
}
|
package me.deftware.mixin.mixins;
import me.deftware.client.framework.event.events.EventWeather;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.WorldRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(WorldRenderer.class)
public class MixinWorldRenderer {
@Inject(method = "method_22713", at = @At("HEAD"), cancellable = true)
private void renderRain(Camera camera, CallbackInfo ci) {
EventWeather event = new EventWeather(EventWeather.WeatherType.Rain);
event.broadcast();
if (event.isCanceled()) {
ci.cancel();
}
}
}
|
Update Django requirements for 1.8
|
#!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='django-elect',
version='0.1',
description='A simple voting app for Django',
license='BSD',
author='Mason Malone',
author_email='mason.malone@gmail.com',
url='http://bitbucket.org/MasonM/django-elect/',
packages=find_packages(exclude=['example_project', 'example_project.*']),
include_package_data=True,
tests_require=[
'django>=1.8,<1.9',
'freezegun',
'unittest2',
],
test_suite='runtests.runtests',
install_requires=[
'django>=1.8,<1.9',
'setuptools',
],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: JavaScript',
'Topic :: Internet :: WWW/HTTP :: Site Management'],
)
|
#!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='django-elect',
version='0.1',
description='A simple voting app for Django',
license='BSD',
author='Mason Malone',
author_email='mason.malone@gmail.com',
url='http://bitbucket.org/MasonM/django-elect/',
packages=find_packages(exclude=['example_project', 'example_project.*']),
include_package_data=True,
tests_require=[
'django>=1.6,<1.8',
'freezegun',
'unittest2',
],
test_suite='runtests.runtests',
install_requires=[
'django>=1.6,<1.8',
'setuptools',
],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: JavaScript',
'Topic :: Internet :: WWW/HTTP :: Site Management'],
)
|
Fix addAssets for production builds
|
const createConfig = require('./base')
const addAssets = require('./assets')
const addDevelopment = require('./development')
const addProduction = require('./production')
const addHot = require('./hot')
const addStory = require('./story')
/**
* Build Webpack configuration
* @param {Object} options - Options
* @param {string} options.source - Source path to read source code from
* @param {string} options.destination - Destination path to write assets out
* @param {string} options.assets - Assets path to read static assets from
* @return {Object} Webpack configuration
*/
module.exports = ({
source,
destination,
assets,
}) => {
// Create base configuration and export
const config = createConfig({source, destination})
// Add to configuration based on environment
switch(process.env.NODE_ENV) {
case 'storybook':
addStory(config)
addDevelopment(config)
console.info('--- webpack: using storybook configuration')
case 'development':
addAssets(config, {assets})
addDevelopment(config)
console.info('--- webpack: using development configuration')
break
case 'production':
addAssets(config, {assets})
addProduction(config)
console.info('--- webpack: using production configuration')
break
default:
throw new Error('NODE_ENV is not set or is an unsupported environment')
}
// Add hot reload support if explicitly specified
if(process.env.HOT_MODULES === 'true') {
addHot(config)
console.info('--- webpack: using hot modules configuration')
}
return config
}
|
const createConfig = require('./base')
const addAssets = require('./assets')
const addDevelopment = require('./development')
const addProduction = require('./production')
const addHot = require('./hot')
const addStory = require('./story')
/**
* Build Webpack configuration
* @param {Object} options - Options
* @param {string} options.source - Source path to read source code from
* @param {string} options.destination - Destination path to write assets out
* @param {string} options.assets - Assets path to read static assets from
* @return {Object} Webpack configuration
*/
module.exports = ({
source,
destination,
assets,
}) => {
// Create base configuration and export
const config = createConfig({source, destination})
// Add to configuration based on environment
switch(process.env.NODE_ENV) {
case 'storybook':
addStory(config)
addDevelopment(config)
console.info('--- webpack: using storybook configuration')
case 'development':
addAssets(config, {assets})
addDevelopment(config)
console.info('--- webpack: using development configuration')
break
case 'production':
addAssets(config)
addProduction(config)
console.info('--- webpack: using production configuration')
break
default:
throw new Error('NODE_ENV is not set or is an unsupported environment')
}
// Add hot reload support if explicitly specified
if(process.env.HOT_MODULES === 'true') {
addHot(config)
console.info('--- webpack: using hot modules configuration')
}
return config
}
|
Add leading slash to path if not provided
|
var st = require('st')
, http = require('http')
, js = require('atomify-js')
, css = require('atomify-css')
, open = require('open')
module.exports = function (args) {
var mount = st(args.server.st || process.cwd())
, port = args.server.port || 1337
, launch = args.server.open
, path = args.server.path || '/'
, url
if (path.charAt(0) !== '/') path = '/' + path
url = args.server.url || 'http://localhost:' + port + path
http.createServer(function (req, res) {
switch (req.url) {
case args.js.alias || args.js.entry:
js(args.js, responder('javascript', res))
break
case args.css.alias || args.css.entry:
css(args.css, responder('css', res))
break
default:
mount(req, res)
break
}
}).listen(port)
if (launch) open(url)
}
function responder (type, res) {
return function (err, src) {
if (!res.headersSent) res.setHeader('Content-Type', 'text/' + type)
res.end(src)
}
}
|
var st = require('st')
, http = require('http')
, js = require('atomify-js')
, css = require('atomify-css')
, open = require('open')
module.exports = function (args) {
var mount = st(args.server.st || process.cwd())
, port = args.server.port || 1337
, launch = args.server.open
, path = args.server.path || ''
, url = args.server.url || 'http://localhost:' + port + path
http.createServer(function(req, res) {
switch (req.url) {
case args.js.alias || args.js.entry:
js(args.js, responder('javascript', res))
break
case args.css.alias || args.css.entry:
css(args.css, responder('css', res))
break
default:
mount(req, res)
break
}
}).listen(port)
if (launch) open(url)
}
function responder (type, res) {
return function (err, src) {
if (!res.headersSent) res.setHeader('Content-Type', 'text/' + type)
res.end(src)
}
}
|
Check main thread before scheduling
|
/*
* Copyright 2016 FabricMC
*
* 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 net.fabricmc.base;
import net.fabricmc.api.Side;
import net.minecraft.client.Minecraft;
import net.minecraft.sortme.EntityPlayerAbstract;
public class ClientSidedHandler implements ISidedHandler {
@Override
public Side getSide() {
return Side.CLIENT;
}
@Override
public EntityPlayerAbstract getClientPlayer() {
return Minecraft.getInstance().player;
}
@Override
public void runOnMainThread(Runnable runnable) {
if (Minecraft.getInstance().isMainThread()) {
runnable.run();
} else {
Minecraft.getInstance().scheduleOnMainThread(runnable);
}
}
}
|
/*
* Copyright 2016 FabricMC
*
* 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 net.fabricmc.base;
import net.fabricmc.api.Side;
import net.minecraft.client.Minecraft;
import net.minecraft.sortme.EntityPlayerAbstract;
public class ClientSidedHandler implements ISidedHandler {
@Override
public Side getSide() {
return Side.CLIENT;
}
@Override
public EntityPlayerAbstract getClientPlayer() {
return Minecraft.getInstance().player;
}
@Override
public void runOnMainThread(Runnable runnable) {
Minecraft.getInstance().scheduleOnMainThread(runnable);
}
}
|
Revert "Minor - webpack client filename change"
This reverts commit 8a687defb70b7c4bab6c5aac3be8867d8efd7542.
|
const webpack = require('webpack')
const merge = require('webpack-merge')
const base = require('./webpack.base.config')
const path = require('path')
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin')
const config = merge(base, {
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all',
},
},
},
runtimeChunk: {
name: "manifest",
}
},
mode: 'development',
resolve: {
alias: {
'create-api': './create-api-client.js'
}
},
plugins: [
// strip dev-only code in Vue source
new webpack.DefinePlugin({
'process.env.VUE_ENV': '"client"'
}),
new VueSSRClientPlugin()
]
})
module.exports = config;
|
const webpack = require('webpack')
const merge = require('webpack-merge')
const base = require('./webpack.base.config')
const path = require('path')
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin')
const config = merge(base, {
output: {
path: path.resolve(__dirname, '../../dist'),
publicPath: '/dist/',
filename: '[name].js'
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all',
},
},
},
runtimeChunk: {
name: "manifest",
}
},
mode: 'development',
resolve: {
alias: {
'create-api': './create-api-client.js'
}
},
plugins: [
// strip dev-only code in Vue source
new webpack.DefinePlugin({
'process.env.VUE_ENV': '"client"'
}),
new VueSSRClientPlugin()
]
})
module.exports = config;
|
Add svn:ignore to the list of standard properties.
|
package com.github.cstroe.svndumpgui.api;
public interface SvnProperty {
String DATE = "svn:date";
String AUTHOR = "svn:author";
String LOG = "svn:log";
String IGNORE = "svn:ignore";
String MIMETYPE = "svn:mime-type";
String MERGEINFO = "svn:mergeinfo";
/**
* Used in {@link com.github.cstroe.svndumpgui.generated.SvnDumpFileParser#Start(SvnDumpConsumer)}
* to keep track of how many EOLs are actually in the dump file, so that
* {@link com.github.cstroe.svndumpgui.internal.writer.SvnDumpWriterImpl#endNode(SvnNode)}
* can produce the matching number of new lines.
*
* Had to resort to this "hack" because the SVN dump file description is not specific enough
* and it was too hard to decipher the behavior of "svnadmin dump" with regards to new lines.
*/
String TRAILING_NEWLINE_HINT = "TRAILING_NEWLINE_HINT";
}
|
package com.github.cstroe.svndumpgui.api;
public interface SvnProperty {
String DATE = "svn:date";
String AUTHOR = "svn:author";
String LOG = "svn:log";
String MIMETYPE = "svn:mime-type";
String MERGEINFO = "svn:mergeinfo";
/**
* Used in {@link com.github.cstroe.svndumpgui.generated.SvnDumpFileParser#Start(SvnDumpConsumer)}
* to keep track of how many EOLs are actually in the dump file, so that
* {@link com.github.cstroe.svndumpgui.internal.writer.SvnDumpWriterImpl#endNode(SvnNode)}
* can produce the matching number of new lines.
*
* Had to resort to this "hack" because the SVN dump file description is not specific enough
* and it was too hard to decipher the behavior of "svnadmin dump" with regards to new lines.
*/
String TRAILING_NEWLINE_HINT = "TRAILING_NEWLINE_HINT";
}
|
Fix "Edit on GitHub" links
Using "master" seems to mess it up, see
https://github.com/readthedocs/readthedocs.org/issues/5518
|
# -*- coding: utf-8 -*-
### General settings
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Firebase Admin SDK for PHP'
author = u'Jérôme Gamez'
copyright = u'Jérôme Gamez'
version = u'4.x'
html_title = u'Firebase Admin SDK for PHP Documentation'
html_short_title = u'Firebase Admin SDK for PHP'
exclude_patterns = ['_build']
html_static_path = ['_static']
suppress_warnings = ['image.nonlocal_uri']
### Theme settings
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_theme_options = {
'canonical_url': 'https://firebase-php.readthedocs.io',
'analytics_id': 'UA-82654714-3'
}
### Syntax Highlighting
from sphinx.highlighting import lexers
from pygments.lexers.web import PhpLexer
lexers['php'] = PhpLexer(startinline=True, linenos=1)
lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1)
### Integrations
html_context = {
"display_github": True,
"github_user": "kreait",
"github_repo": "firebase-php",
"github_version": "",
"conf_py_path": "/docs/",
"source_suffix": ".rst",
}
|
# -*- coding: utf-8 -*-
### General settings
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Firebase Admin SDK for PHP'
author = u'Jérôme Gamez'
copyright = u'Jérôme Gamez'
version = u'4.x'
html_title = u'Firebase Admin SDK for PHP Documentation'
html_short_title = u'Firebase Admin SDK for PHP'
exclude_patterns = ['_build']
html_static_path = ['_static']
suppress_warnings = ['image.nonlocal_uri']
### Theme settings
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
### Syntax Highlighting
from sphinx.highlighting import lexers
from pygments.lexers.web import PhpLexer
lexers['php'] = PhpLexer(startinline=True, linenos=1)
lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1)
### Integrations
html_context = {
"display_github": True,
"github_user": "kreait",
"github_repo": "firebase-php",
"github_version": "master",
"conf_py_path": "/docs/",
"source_suffix": ".rst",
}
|
Remove install_requires that are not on PyPI yet.
|
#!/usr/bin/env python
from setuptools import setup, find_packages
install_requires = [
"bleach",
"jinja2",
"Django>=1.4",
"django-celery",
"django-jsonfield",
"django-model-utils",
"django-tastypie",
"docutils",
"isoweek",
"lxml",
]
setup(
name="crate.web",
version="0.1",
author="Donald Stufft",
author_email="donald@crate.io",
url="https://github.com/crateio/crate.web",
description="crate.web is a Django app that provides the building blocks to build a Package Index Server.",
license=open("LICENSE").read(),
namespace_packages=["crate"],
packages=find_packages(exclude=("tests",)),
package_data={'': ['LICENSE', 'NOTICE']},
include_package_data=True,
install_requires=install_requires,
zip_safe=False,
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
install_requires = [
"bleach",
"jinja2",
"celery-haystack",
"Django>=1.4",
"django-celery",
"django-haystack",
"django-jsonfield",
"django-model-utils",
"django-tastypie",
"docutils",
"isoweek",
"lxml",
"saved_searches",
]
setup(
name="crate.web",
version="0.1",
author="Donald Stufft",
author_email="donald@crate.io",
url="https://github.com/crateio/crate.web",
description="crate.web is a Django app that provides the building blocks to build a Package Index Server.",
license=open("LICENSE").read(),
namespace_packages=["crate"],
packages=find_packages(exclude=("tests",)),
package_data={'': ['LICENSE', 'NOTICE']},
include_package_data=True,
install_requires=install_requires,
zip_safe=False,
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
],
)
|
BB-3192: Make default delete operation available only in main entity management grids
- cs updates
|
<?php
namespace Oro\Bundle\ActionBundle\Helper;
use Symfony\Component\HttpFoundation\RequestStack;
class RequestHelper
{
/** @var RequestStack */
protected $requestStack;
/** @var ApplicationsHelper */
protected $applicationsHelper;
/**
* @param RequestStack $requestStack
* @param ApplicationsHelper $applicationsHelper
*/
public function __construct(RequestStack $requestStack, ApplicationsHelper $applicationsHelper)
{
$this->requestStack = $requestStack;
$this->applicationsHelper = $applicationsHelper;
}
/**
* @return string
*/
public function getRequestRoute()
{
if (null === ($request = $this->requestStack->getMasterRequest())) {
return;
}
$route = $request->get('_route');
return $route !== $this->applicationsHelper->getExecutionRoute() ? $route : null;
}
}
|
<?php
namespace Oro\Bundle\ActionBundle\Helper;
use Symfony\Component\HttpFoundation\RequestStack;
class RequestHelper
{
/** @var RequestStack */
protected $requestStack;
/** @var ApplicationsHelper */
protected $applicationsHelper;
/**
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack, ApplicationsHelper $applicationsHelper)
{
$this->requestStack = $requestStack;
$this->applicationsHelper = $applicationsHelper;
}
/**
* @return string
*/
public function getRequestRoute()
{
if (null === ($request = $this->requestStack->getMasterRequest())) {
return;
}
$route = $request->get('_route');
return $route !== $this->applicationsHelper->getExecutionRoute() ? $route : null;
}
}
|
Move symlinked page field to "Other options"
|
"""
This introduces a new page type, which has no content of its own but inherits
all content from the linked page.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms._internal import monkeypatch_property
def register(cls, admin_cls):
cls.add_to_class('symlinked_page', models.ForeignKey('self', blank=True, null=True,
related_name='%(app_label)s_%(class)s_symlinks',
verbose_name=_('symlinked page'),
help_text=_('All content is inherited from this page if given.')))
@monkeypatch_property(cls)
def content(self):
if not hasattr(self, '_content_proxy'):
if self.symlinked_page:
self._content_proxy = self.content_proxy_class(self.symlinked_page)
else:
self._content_proxy = self.content_proxy_class(self)
return self._content_proxy
admin_cls.raw_id_fields.append('symlinked_page')
|
"""
This introduces a new page type, which has no content of its own but inherits
all content from the linked page.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms._internal import monkeypatch_property
def register(cls, admin_cls):
cls.add_to_class('symlinked_page', models.ForeignKey('self', blank=True, null=True,
related_name='%(app_label)s_%(class)s_symlinks',
verbose_name=_('symlinked page'),
help_text=_('All content is inherited from this page if given.')))
@monkeypatch_property(cls)
def content(self):
if not hasattr(self, '_content_proxy'):
if self.symlinked_page:
self._content_proxy = self.content_proxy_class(self.symlinked_page)
else:
self._content_proxy = self.content_proxy_class(self)
return self._content_proxy
admin_cls.raw_id_fields.append('symlinked_page')
admin_cls.fieldsets.append((_('Symlinked page'), {
'fields': ('symlinked_page',),
'classes': ('collapse',),
}))
|
Update breadcrumb to support localization
|
(function () {
"use strict";
var app = angular.module('RbsChange');
app.config(['$provide', function ($provide)
{
$provide.decorator('RbsChange.UrlManager', ['$delegate', function ($delegate)
{
$delegate.module('Rbs_Plugins')
.route('Installed', 'Rbs/Plugins/Installed/', { 'templateUrl': 'Rbs/Plugins/installed-list.twig'})
.route('Registered', 'Rbs/Plugins/Registered/', { 'templateUrl': 'Rbs/Plugins/registered-list.twig'})
.route('New', 'Rbs/Plugins/New/', { 'templateUrl': 'Rbs/Plugins/new-list.twig'});
return $delegate.module(null);
}]);
}]);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
. when(
'/Rbs/Plugins/',
{
redirectTo : '/Rbs/Plugins/Installed/'
})
;
}]);
})();
|
(function () {
"use strict";
var app = angular.module('RbsChange');
app.config(['$provide', function ($provide)
{
$provide.decorator('RbsChange.UrlManager', ['$delegate', function ($delegate)
{
$delegate.model('Rbs_Plugins')
.route('Installed', 'Rbs/Plugins/Installed/', { 'templateUrl': 'Rbs/Plugins/installed-list.twig'})
.route('Registered', 'Rbs/Plugins/Registered/', { 'templateUrl': 'Rbs/Plugins/registered-list.twig'})
.route('New', 'Rbs/Plugins/New/', { 'templateUrl': 'Rbs/Plugins/new-list.twig'});
return $delegate;
}]);
}]);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
. when(
'/Rbs/Plugins/',
{
redirectTo : '/Rbs/Plugins/Installed/'
})
;
}]);
})();
|
Update with reference to global nav partial
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-hovers/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-hovers/tachyons-hovers.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_hovers.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/hovers/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/themes/hovers/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-hovers/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-hovers/tachyons-hovers.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_hovers.css', 'utf8')
var template = fs.readFileSync('./templates/docs/hovers/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/themes/hovers/index.html', html)
|
Refactor SimpleSectionView to inherit DetailView
|
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.utils.translation import ugettext as _
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from .models import Section
class SimpleSectionView(DetailView):
context_object_name = 'section'
model = Section
def get_object(self, queryset=None):
return get_object_or_404(self.get_queryset(),
full_slug=self.kwargs['full_slug'])
class SectionFeed(Feed):
def __init__(self, section_view, *args, **kwargs):
self.section_view = section_view
def get_object(self, request, full_slug):
return Section.objects.get(full_slug=full_slug)
def title(self, section):
return section.title
def link(self, section):
return reverse(self.section_view,
kwargs={'full_slug': section.full_slug})
def description(self, section):
return section.summary
def items(self, section):
return section.items
|
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView
from django.utils.translation import ugettext as _
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from .models import Section
class SimpleSectionView(TemplateView):
well_title = None
def get_section(self):
return get_object_or_404(Section, full_slug=self.kwargs['full_slug'])
def get_context_data(self, **kwargs):
context = super(SimpleSectionView, self).get_context_data(**kwargs)
context["section"] = self.get_section()
return context
class SectionFeed(Feed):
def __init__(self, section_view, *args, **kwargs):
self.section_view = section_view
def get_object(self, request, full_slug):
return Section.objects.get(full_slug=full_slug)
def title(self, section):
return section.title
def link(self, section):
return reverse(self.section_view,
kwargs={'full_slug': section.full_slug})
def description(self, section):
return section.summary
def items(self, section):
return section.items
|
engine: Improve log message on failure to connect to storage server
From now on log message will contain name and id of the relevant
storage domain a host failed to connect to.
Change-Id: Ife941b59766e699a046122abc74aaede366a2015
Signed-off-by: Sergey Gotliv <76a2e639c7812c7311d8d25c611b643bca4ae95e@redhat.com>
|
package org.ovirt.engine.core.bll.storage;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
public class ConnectSingleAsyncOperation extends ActivateDeactivateSingleAsyncOperation {
public ConnectSingleAsyncOperation(java.util.ArrayList<VDS> vdss, StorageDomain domain, StoragePool storagePool) {
super(vdss, domain, storagePool);
}
@Override
public void execute(int iterationId) {
VDS vds = getVdss().get(iterationId);
try {
StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType())
.connectStorageToDomainByVdsId(getStorageDomain(), vds.getId());
} catch (RuntimeException e) {
log.errorFormat("Failed to connect host {0} to storage domain (name: {1}, id: {2}). Exception: {3}",
vds.getName(), getStorageDomain().getName(), getStorageDomain().getId(), e);
}
}
private static Log log = LogFactory.getLog(ConnectSingleAsyncOperation.class);
}
|
package org.ovirt.engine.core.bll.storage;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
public class ConnectSingleAsyncOperation extends ActivateDeactivateSingleAsyncOperation {
public ConnectSingleAsyncOperation(java.util.ArrayList<VDS> vdss, StorageDomain domain, StoragePool storagePool) {
super(vdss, domain, storagePool);
}
@Override
public void execute(int iterationId) {
try {
StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType())
.connectStorageToDomainByVdsId(getStorageDomain(), getVdss().get(iterationId).getId());
} catch (RuntimeException e) {
log.errorFormat("Failed to connect host {0} to storage pool {1}. Exception: {3}", getVdss()
.get(iterationId).getName(), getStoragePool().getName(), e);
}
}
private static Log log = LogFactory.getLog(ConnectSingleAsyncOperation.class);
}
|
Add polling loop to allow time for callback to be invoked
|
import os
import time
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
for _ in range(10):
if len(calls) == 1:
break
time.sleep(0.2)
else:
raise AssertionError("Expected callback to be invoked but was not.")
|
import os
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
assert len(calls) == 1
|
Use m.Count() even inside pointer-struct functions
This way the backing datastore can be more easily mucked with
|
package litetunes
import (
"errors"
"fmt"
)
// MemoryQueue is an in-memory implementation of the Queue interface
type MemoryQueue struct {
tracks []*Track
}
// NewMemoryQueue constructs a new MemoryQueue to use
func NewMemoryQueue() *MemoryQueue {
return &MemoryQueue{tracks: []*Track{}}
}
// Queue adds a new track to the queue
func (m *MemoryQueue) Queue(t *Track) error {
if curlen := m.Count(); cap(m.tracks) == curlen {
bigger := make([]*Track, curlen, 2*curlen+1)
copy(bigger, m.tracks)
m.tracks = bigger
}
m.tracks = append(m.tracks, t)
return nil
}
// Dequeue removes the track at the head of the queue
func (m *MemoryQueue) Dequeue() (*Track, error) {
c := m.Count()
if c < 1 {
return nil, errors.New("No track to dequeue")
}
t := m.tracks[0]
if t == nil {
for k, v := range m.tracks {
fmt.Printf("%d = %#v\n", k, v)
}
}
m.tracks = m.tracks[1:]
return t, nil
}
// Count returns the number of tracks in the queue
func (m *MemoryQueue) Count() int {
return len(m.tracks)
}
|
package litetunes
import (
"errors"
"fmt"
)
// MemoryQueue is an in-memory implementation of the Queue interface
type MemoryQueue struct {
tracks []*Track
}
// NewMemoryQueue constructs a new MemoryQueue to use
func NewMemoryQueue() *MemoryQueue {
return &MemoryQueue{tracks: []*Track{}}
}
// Queue adds a new track to the queue
func (m *MemoryQueue) Queue(t *Track) error {
if curlen := len(m.tracks); cap(m.tracks) == curlen {
bigger := make([]*Track, curlen, 2*curlen+1)
copy(bigger, m.tracks)
m.tracks = bigger
}
m.tracks = append(m.tracks, t)
return nil
}
// Dequeue removes the track at the head of the queue
func (m *MemoryQueue) Dequeue() (*Track, error) {
c := m.Count()
if c < 1 {
return nil, errors.New("No track to dequeue")
}
t := m.tracks[0]
if t == nil {
for k, v := range m.tracks {
fmt.Printf("%d = %#v\n", k, v)
}
}
m.tracks = m.tracks[1:]
return t, nil
}
// Count returns the number of tracks in the queue
func (m *MemoryQueue) Count() int {
return len(m.tracks)
}
|
Add blacklist check for chat when a user sends a message
|
<?php
# Copyright (c) 2015 Jordan Turley, CSGO Win Big. All Rights Reserved.
session_start();
include 'default.php';
include 'SteamAuthentication/steamauth/userInfo.php';
$db = getDB();
if (!isset($_SESSION['steamid'])) {
echo jsonErr('You are not logged in.');
return;
}
$text = isset($_POST['text']) ? $_POST['text'] : null;
if (is_null($text) || strlen($text) === 0) {
echo jsonErr('The required text for the message was not sent correctly or was left blank. Please refresh and try again.');
return;
}
$steamUserID = $steamprofile['steamid'];
# Check if they are on the blacklist for the chat
$stmt = $db->query('SELECT * FROM chatBlacklist');
$blacklist = $stmt->fetchAll();
foreach ($blacklist as $user) {
$steamId64 = $user['steamId64'];
if ($steamId64 === $steamUserID) {
echo jsonSuccess(array('message' => 'You have been banned from the chat.'));
return;
}
}
$stmt = $db->prepare('INSERT INTO `chat` (`steamUserID`, `text`, `date`, `time`) VALUES (:userid, :text, CURDATE(), CURTIME())');
$stmt->bindValue(':userid', $steamUserID);
$stmt->bindValue(':text', $text);
$stmt->execute();
echo jsonSuccess(array('message' => 'Message has been sent!'));
?>
|
<?php
# Copyright (c) 2015 Jordan Turley, CSGO Win Big. All Rights Reserved.
session_start();
include 'default.php';
include 'SteamAuthentication/steamauth/userInfo.php';
$db = getDB();
if (!isset($_SESSION['steamid'])) {
echo jsonErr('You are not logged in.');
return;
}
$text = isset($_POST['text']) ? $_POST['text'] : null;
if (is_null($text) || strlen($text) === 0) {
echo jsonErr('The required text for the message was not sent correctly or was left blank. Please refresh and try again.');
return;
}
$steamUserID = $steamprofile['steamid'];
$stmt = $db->prepare('INSERT INTO `chat` (`steamUserID`, `text`, `date`, `time`) VALUES (:userid, :text, CURDATE(), CURTIME())');
$stmt->bindValue(':userid', $steamUserID);
$stmt->bindValue(':text', $text);
$stmt->execute();
echo jsonSuccess(array('message' => 'Message has been sent!'));
?>
|
[stargate] Fix infinite recursive loop bug
Submitted-by: Zhentao Huang <zhentao.huang@trendmicro.com.cn>
Signed-off-by: Andrew Purtell <apurtell@apache.org>
git-svn-id: 25ca64b629f24bdef6d1cceac138f74b13f55e41@943999 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Copyright 2010 The Apache Software Foundation
*
* 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.hadoop.hbase.stargate.util;
import java.util.HashMap;
import java.util.Map;
/**
* Generic storage for per user information.
*/
public class UserData {
public static final int TOKENBUCKET = 1;
Map<Integer,Object> data = new HashMap<Integer,Object>(1);
public synchronized boolean has(final int sel) {
return data.get(sel) != null;
}
public synchronized Object get(final int sel) {
return data.get(sel);
}
public synchronized Object put(final int sel, final Object o) {
return data.put(sel, o);
}
public synchronized Object remove(int sel) {
return data.remove(sel);
}
}
|
/*
* Copyright 2010 The Apache Software Foundation
*
* 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.hadoop.hbase.stargate.util;
import java.util.HashMap;
import java.util.Map;
/**
* Generic storage for per user information.
*/
public class UserData {
public static final int TOKENBUCKET = 1;
Map<Integer,Object> data = new HashMap<Integer,Object>(1);
public synchronized boolean has(final int sel) {
return data.get(sel) != null;
}
public synchronized Object get(final int sel) {
return data.get(sel);
}
public synchronized Object put(final int sel, final Object o) {
return data.put(sel, o);
}
public synchronized Object remove(int sel) {
return remove(sel);
}
}
|
Test if partition calls func once for each item
|
/* eslint-env node, jest */
const { partition, range } = require('iter-tools')
describe('partition', function () {
describe('evens and odds', function () {
const isEven = n => n % 2 === 0
it('empty iterable', function () {
const [evens, odds] = partition(isEven, [])
expect([
Array.from(evens),
Array.from(odds)
]).toEqual([[], []])
})
it('range(10)', function () {
const [evens, odds] = partition(isEven, range(10))
expect([
Array.from(evens),
Array.from(odds)
]).toEqual([
[0, 2, 4, 6, 8],
[1, 3, 5, 7, 9]
])
})
it('calls func once for each item', function () {
const func = jest.fn(isEven)
const [evens, odds] = partition(func, range(10))
Array.from(evens)
Array.from(odds)
expect(func.mock.calls).toEqual(
Array.from(range(10)).map(x => [x])
)
})
})
})
|
/* eslint-env node, jest */
const { partition, range } = require('iter-tools')
describe('partition', function () {
describe('evens and odds', function () {
const isEven = n => n % 2 === 0
it('empty iterable', function () {
const [evens, odds] = partition(isEven, [])
expect([
Array.from(evens),
Array.from(odds)
]).toEqual([[], []])
})
it('range(10)', function () {
const [evens, odds] = partition(isEven, range(10))
expect([
Array.from(evens),
Array.from(odds)
]).toEqual([
[0, 2, 4, 6, 8],
[1, 3, 5, 7, 9]
])
})
})
})
|
Copy assets after dist folder has been created
The production build script fails when it tries to copy the content of the assets folder to a non-existing folder.
|
require('shelljs/global');
const package = require('../package.json');
const prodDependencies = Object.keys(package.jspm.dependencies);
const devDependencies = Object.keys(package.jspm.devDependencies);
const allDependencies = prodDependencies.concat(devDependencies);
const command = process.argv[2];
switch (command) {
case 'dev':
exec(
`jspm bundle ${allDependencies.join(' + ')} temp/vendor.dev.js -d`
);
break;
case 'vendor':
exec(
`jspm bundle ${prodDependencies.join(' + ')} dist/vendor.prod.js -ms`
);
cp(
'-R', ['jspm.config.js', 'jspm_packages/system.js'], 'dist'
);
break;
case 'app':
exec(
`jspm build src/app - ${prodDependencies.join(' - ')} dist/app.js --skip-source-maps --minify`
);
cp('assets/*', 'dist');
break;
case 'debug':
exec(
`jspm build src/app - ${prodDependencies.join(' - ')} dist/app.js`
);
break;
default:
console.log('\nUsage: node build.js <arg>');
console.log('\nwhere <arg> is one of:');
console.log(' dev, app, vendor, debug\n');
break;
}
|
require('shelljs/global');
const package = require('../package.json');
const prodDependencies = Object.keys(package.jspm.dependencies);
const devDependencies = Object.keys(package.jspm.devDependencies);
const allDependencies = prodDependencies.concat(devDependencies);
const command = process.argv[2];
switch (command) {
case 'dev':
exec(
`jspm bundle ${allDependencies.join(' + ')} temp/vendor.dev.js -d`
);
break;
case 'vendor':
exec(
`jspm bundle ${prodDependencies.join(' + ')} dist/vendor.prod.js -ms`
);
cp(
'-R', ['jspm.config.js', 'jspm_packages/system.js'], 'dist'
);
break;
case 'app':
cp('assets/*', 'dist');
exec(
`jspm build src/app - ${prodDependencies.join(' - ')} dist/app.js --skip-source-maps --minify`
);
break;
case 'debug':
exec(
`jspm build src/app - ${prodDependencies.join(' - ')} dist/app.js`
);
break;
default:
console.log('\nUsage: node build.js <arg>');
console.log('\nwhere <arg> is one of:');
console.log(' dev, app, vendor, debug\n');
break;
}
|
Verify that the generated playlist contains the path to the item
|
# -*- coding: utf-8 -*-
"""Tests for the play plugin"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
from mock import patch, ANY
from test._common import unittest
from test.helper import TestHelper
class PlayPluginTest(unittest.TestCase, TestHelper):
def setUp(self):
self.setup_beets()
self.load_plugins('play')
self.item = self.add_item(title='aNiceTitle')
def tearDown(self):
self.teardown_beets()
self.unload_plugins()
@patch('beetsplug.play.util.interactive_open')
def test_basic(self, open_mock):
self.run_command('play', 'title:aNiceTitle')
open_mock.assert_called_once_with(ANY, None)
playlist = open(open_mock.call_args[0][0][0], 'r')
self.assertEqual(self.item.path.decode('utf-8') + '\n',
playlist.read().decode('utf-8'))
def suite():
return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == b'__main__':
unittest.main(defaultTest='suite')
|
# -*- coding: utf-8 -*-
"""Tests for the play plugin"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
from mock import patch, Mock
from test._common import unittest
from test.helper import TestHelper
class PlayPluginTest(unittest.TestCase, TestHelper):
def setUp(self):
self.setup_beets()
self.load_plugins('play')
self.add_item(title='aNiceTitle')
def tearDown(self):
self.teardown_beets()
self.unload_plugins()
@patch('beetsplug.play.util.interactive_open', Mock())
def test_basic(self):
self.run_command('play', 'title:aNiceTitle')
def suite():
return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == b'__main__':
unittest.main(defaultTest='suite')
|
Disable CSS for ZEIT AMP theme
|
define([
'plugins/post-hash',
'plugins/status',
'plugins/predefined-types',
'theme/scripts/js/plugins/ampify',
'theme/scripts/js/plugins/button-pagination',
'theme/scripts/js/plugins/social-share',
// 'css!theme/liveblog',
'tmpl!theme/container',
'tmpl!theme/posts-list',
'tmpl!theme/item/base',
// 'tmpl!theme/item/posttype/image',
'tmpl!theme/item/predefined/scorecard',
'tmpl!theme/item/source/flickr',
'tmpl!theme/item/source/google/images',
'tmpl!theme/item/source/google/news',
'tmpl!theme/item/source/google/web',
'tmpl!theme/item/source/instagram',
'tmpl!theme/item/source/twitter',
'tmpl!theme/item/source/youtube',
'tmpl!theme/plugins/after-button-pagination',
'tmpl!theme/plugins/before-button-pagination',
'tmpl!theme/plugins/social-share'
], function() {
'use strict';
liveblog.hashmark = '?';
liveblog.hashaddition = '#livedesk-root';
return {
plugins: [
'ampify',
'button-pagination',
'social-share',
'status'
]
};
});
|
define([
'plugins/post-hash',
'plugins/status',
'plugins/predefined-types',
'theme/scripts/js/plugins/ampify',
'theme/scripts/js/plugins/button-pagination',
'theme/scripts/js/plugins/social-share',
'css!theme/liveblog',
'tmpl!theme/container',
'tmpl!theme/posts-list',
'tmpl!theme/item/base',
// 'tmpl!theme/item/posttype/image',
'tmpl!theme/item/predefined/scorecard',
'tmpl!theme/item/source/flickr',
'tmpl!theme/item/source/google/images',
'tmpl!theme/item/source/google/news',
'tmpl!theme/item/source/google/web',
'tmpl!theme/item/source/instagram',
'tmpl!theme/item/source/twitter',
'tmpl!theme/item/source/youtube',
'tmpl!theme/plugins/after-button-pagination',
'tmpl!theme/plugins/before-button-pagination',
'tmpl!theme/plugins/social-share'
], function() {
'use strict';
liveblog.hashmark = '?';
liveblog.hashaddition = '#livedesk-root';
return {
plugins: [
'ampify',
'button-pagination',
'social-share',
'status'
]
};
});
|
Add source-map to minified build
|
/* eslint-env node */
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
devtool: 'source-map',
entry: {
daypicker: './DayPicker.dist.js',
},
output: {
path: `${__dirname}/lib`,
filename: `[name]${isProduction ? '.min' : ''}.js`,
library: 'DayPicker',
libraryTarget: 'umd',
},
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
moment: {
root: 'moment',
commonjs2: 'moment',
commonjs: 'moment',
amd: 'moment',
},
},
};
|
/* eslint-env node */
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
entry: {
daypicker: './DayPicker.dist.js',
},
output: {
path: `${__dirname}/lib`,
filename: `[name]${isProduction ? '.min' : ''}.js`,
library: 'DayPicker',
libraryTarget: 'umd',
},
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
moment: {
root: 'moment',
commonjs2: 'moment',
commonjs: 'moment',
amd: 'moment',
},
},
};
|
Update modules fixture to always include autoActivated modules in active list.
|
/**
* Modules datastore fixtures.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import modules from '../fixtures.json'; // TODO: move into this directory.
const alwaysActive = [ 'search-console', 'site-verification' ];
/**
* Makes a copy of the modules with the given module activation set.
*
* @param {...string} slugs Active module slugs.
* @return {Object[]} Array of module objects.
*/
export const withActive = ( ...slugs ) => {
const activeSlugs = alwaysActive.concat( slugs );
return modules.map( ( module ) => {
return { ...module, active: activeSlugs.includes( module.slug ) };
} );
};
// Only Search Console and Site Verification are active by default.
export default withActive();
|
/**
* Modules datastore fixtures.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import modules from '../fixtures.json'; // TODO: move into this directory.
/**
* Makes a copy of the modules with the given module activation set.
*
* @param {...string} slugs Active module slugs.
* @return {Object[]} Array of module objects.
*/
export const withActive = ( ...slugs ) => {
return modules.map( ( module ) => {
return { ...module, active: slugs.includes( module.slug ) };
} );
};
// Only Search Console and Site Verification are active by default.
export default withActive( 'search-console', 'site-verification' );
|
Fix race condition on AppVeyor. Increase timeout a bit.
|
package markdown
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
func TestWatcher(t *testing.T) {
expected := "12345678"
interval := time.Millisecond * 100
i := 0
out := ""
stopChan := TickerFunc(interval, func() {
i++
out += fmt.Sprint(i)
})
// wait little more because of concurrency
time.Sleep(interval * 12)
stopChan <- struct{}{}
if !strings.HasPrefix(out, expected) {
t.Fatalf("Expected to have prefix %v, found %v", expected, out)
}
out = ""
i = 0
var mu sync.Mutex
stopChan = TickerFunc(interval, func() {
i++
mu.Lock()
out += fmt.Sprint(i)
mu.Unlock()
})
time.Sleep(interval * 15)
mu.Lock()
res := out
mu.Unlock()
if !strings.HasPrefix(res, expected) || res == expected {
t.Fatalf("expected (%v) must be a proper prefix of out(%v).", expected, out)
}
}
|
package markdown
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
func TestWatcher(t *testing.T) {
expected := "12345678"
interval := time.Millisecond * 100
i := 0
out := ""
stopChan := TickerFunc(interval, func() {
i++
out += fmt.Sprint(i)
})
// wait little more because of concurrency
time.Sleep(interval * 9)
stopChan <- struct{}{}
if !strings.HasPrefix(out, expected) {
t.Fatalf("Expected to have prefix %v, found %v", expected, out)
}
out = ""
i = 0
var mu sync.Mutex
stopChan = TickerFunc(interval, func() {
i++
mu.Lock()
out += fmt.Sprint(i)
mu.Unlock()
})
time.Sleep(interval * 10)
mu.Lock()
res := out
mu.Unlock()
if !strings.HasPrefix(res, expected) || res == expected {
t.Fatalf("expected (%v) must be a proper prefix of out(%v).", expected, out)
}
}
|
Use comma on every line on multi-line lists
|
#!/usr/bin/env python
import setuptools
import samsungctl
setuptools.setup(
name=samsungctl.__title__,
version=samsungctl.__version__,
description=samsungctl.__doc__,
url=samsungctl.__url__,
author=samsungctl.__author__,
author_email=samsungctl.__author_email__,
license=samsungctl.__license__,
long_description=open("README.md").read(),
entry_points={
"console_scripts": ["samsungctl=samsungctl.__main__:main"]
},
packages=["samsungctl"],
install_requires=[],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Home Automation",
],
)
|
#!/usr/bin/env python
import setuptools
import samsungctl
setuptools.setup(
name=samsungctl.__title__,
version=samsungctl.__version__,
description=samsungctl.__doc__,
url=samsungctl.__url__,
author=samsungctl.__author__,
author_email=samsungctl.__author_email__,
license=samsungctl.__license__,
long_description=open("README.md").read(),
entry_points={
"console_scripts": ["samsungctl=samsungctl.__main__:main"]
},
packages=["samsungctl"],
install_requires=[],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Home Automation"
]
)
|
Remove wrong link from Javadoc
|
/*
* Copyright (C) 2010-2014 Hamburg Sud and the contributors.
*
* 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.aludratest.dict;
import org.aludratest.service.gui.GUIInteraction;
/**
* Common interface for all test classes that make use of the ActionWordLibrary pattern.
* @param <E> Chosen by child classes in a way that {@link #verifyState()} is parameterized
* to return the individual child class.
* @author Volker Bergmann
*/
public interface ActionWordLibrary<E extends ActionWordLibrary<E>> {
/** Verifies the state. If the state is wrong,
* the implementor shall call an appropriate service method
* for reporting the inconsistency.
* {@link GUIInteraction#wrongPageFlow(String)}
* @return a reference to itself (this). */
public abstract E verifyState();
}
|
/*
* Copyright (C) 2010-2014 Hamburg Sud and the contributors.
*
* 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.aludratest.dict;
import org.aludratest.service.gui.GUIInteraction;
/**
* Common interface for all test classes that make use of the ActionWordLibrary pattern.
* @param <E> Chosen by child classes in a way that {@link #verifyState()} is parameterized
* to return the individual child class.
* @see <a href="https://wiki.hsdg-ad.int/GLOBE/index.php/ActionWordLibrary_%28AludraTest%29">AludraTest Wiki</a>
* @author Volker Bergmann
*/
public interface ActionWordLibrary<E extends ActionWordLibrary<E>> {
/** Verifies the state. If the state is wrong,
* the implementor shall call an appropriate service method
* for reporting the inconsistency.
* {@link GUIInteraction#wrongPageFlow(String)}
* @return a reference to itself (this). */
public abstract E verifyState();
}
|
Add check for unsuccessful date checks
|
import os
from dateutil.parser import parse
from ...common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and returning the earliest """
basedir = os.path.join(basedir, 'students', username, spec_id)
dates = []
with chdir(basedir):
for file in spec['files']:
# Run a git log on each file with earliest commits listed first
status, res, _ = run(['git', 'log', '--reverse', '--pretty=format:%ad', '--date=iso8601',
os.path.join(basedir, file['filename'])])
# If we didn't get an error, add date to array
if status == 'success':
# Parse the first line
dates.append(parse(res.splitlines()[0]))
# Return earliest date as a string with the format mm/dd/yyyy hh:mm:ss
if not dates:
return "ERROR"
return min(dates).strftime("%x %X")
|
import os
from dateutil.parser import parse
from ...common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and returning the earliest """
basedir = os.path.join(basedir, 'students', username, spec_id)
dates = []
with chdir(basedir):
for file in spec['files']:
# Run a git log on each file with earliest commits listed first
status, res, _ = run(['git', 'log', '--reverse', '--pretty=format:%ad', '--date=iso8601',
os.path.join(basedir, file['filename'])])
# If we didn't get an error, add date to array
if status == 'success':
# Parse the first line
dates.append(parse(res.splitlines()[0]))
# Return earliest date as a string with the format mm/dd/yyyy hh:mm:ss
return min(dates).strftime("%x %X")
|
Add regex for finding path params
|
'use strict';
var resourcify = angular.module('resourcify', []);
function resourcificator ($http, $q) {
var $resourcifyError = angular.$$minErr('resourcify'),
requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'],
requestMethods = {
'query': 'GET',
'get': 'GET',
'$get': 'GET',
'$save': 'POST',
'$update': 'PUT',
'$delete': 'DELETE'
},
bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH'];
// Finds and replaces query params and path params
function replaceParams (params, url) {
var findParam = /[\/=](:\w*[a-zA-Z]\w*)/g, copiedPath = angular.copy(url);
}
}
resourcificator.$inject = ['$http', '$q'];
resourcify.service('resourcify', resourcificator);
|
'use strict';
var resourcify = angular.module('resourcify', []);
function resourcificator ($http, $q) {
var $resourcifyError = angular.$$minErr('resourcify'),
requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'],
requestMethods = {
'query': 'GET',
'get': 'GET',
'$get': 'GET',
'$save': 'POST',
'$update': 'PUT',
'$delete': 'DELETE'
},
validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'],
bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH'];
function validMethod (method) {
if (!~validMethods.indexOf(method)) {
throw $resourcifyError('requesttype', '"@{0}" is not a valid request method.', method);
}
return method;
}
function replaceParams (params, url) {
}
}
resourcificator.$inject = ['$http', '$q'];
resourcify.service('resourcify', resourcificator);
|
Refactor query out into instance with delegates the update
|
from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate(object):
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
cls(query).update(bearer_token=new_token)
def __init__(self, query_dict):
self.model_filter = DataSet.objects
if 'data_type' in query_dict:
data_type = self._get_model_instance_by_name(
DataType, query_dict['data_type'])
self.model_filter = self.model_filter.filter(data_type=data_type)
if 'data_group' in query_dict:
data_group = self._get_model_instance_by_name(
DataGroup, query_dict['data_group'])
self.model_filter = self.model_filter.filter(data_group=data_group)
def update(self, **kwargs):
self.model_filter.update(**kwargs)
def _get_model_instance_by_name(self, model, name):
return model.objects.get(name=name)
|
from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate():
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
model_filter = DataSet.objects
if 'data_type' in query:
data_type = cls._get_model_instance_by_name(
DataType, query['data_type'])
model_filter = model_filter.filter(data_type=data_type)
if 'data_group' in query:
data_group = cls._get_model_instance_by_name(
DataGroup, query['data_group'])
model_filter = model_filter.filter(data_group=data_group)
model_filter.update(bearer_token=new_token)
@classmethod
def _get_model_instance_by_name(cls, model, name):
return model.objects.get(name=name)
|
Make sure that we reference the config file using an absolute path... just in case...
git-svn-id: efba275c3291004ad656db059d43564e37a1fae9@1775 60fe80c7-c1f8-43be-bd32-c3e8feb7a3b0
|
<?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';
/**
* Check that the configuration file exists and has the appropriate access rights
* If the file does not exist, launch the configuration wizard to create it
*/
if (file_exists(dirname(__FILE__).'/'.$sConfigFile))
{
if (!is_readable($sConfigFile))
{
echo "<p><b>Error</b>: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.</p>";
}
else if (is_writable($sConfigFile))
{
echo "<p><b>Security Warning</b>: the configuration file '$sConfigFile' should be read-only.</p>";
echo "<p>Please modify the access rights to this file.</p>";
echo "<p>Click <a href=\"$sStartPage\">here</a> to ignore this warning and continue to run iTop.</p>";
}
else
{
header("Location: $sStartPage");
}
}
else
{
// Config file does not exist, need to run the setup wizard to create it
header("Location: $sSetupPage");
}
?>
|
<?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';
/**
* Check that the configuration file exists and has the appropriate access rights
* If the file does not exist, launch the configuration wizard to create it
*/
if (file_exists($sConfigFile))
{
if (!is_readable($sConfigFile))
{
echo "<p><b>Error</b>: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.</p>";
}
else if (is_writable($sConfigFile))
{
echo "<p><b>Security Warning</b>: the configuration file '$sConfigFile' should be read-only.</p>";
echo "<p>Please modify the access rights to this file.</p>";
echo "<p>Click <a href=\"$sStartPage\">here</a> to ignore this warning and continue to run iTop.</p>";
}
else
{
header("Location: $sStartPage");
}
}
else
{
// Config file does not exist, need to run the setup wizard to create it
header("Location: $sSetupPage");
}
?>
|
Use main file name as umd library name
|
const HtmlWebPackPlugin = require("html-webpack-plugin")
const mainFile = "InfiniteAnyHeight.jsx"
module.exports = {
entry: {
main: __dirname + "/src/" + mainFile,
},
output: {
filename: "[name].js",
path: __dirname + "/dist",
library: mainFile.substring (0, mainFile.indexOf(".")),
libraryTarget: "umd",
},
devtool: "source-map",
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/],
use: {
loader: "babel-loader",
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true },
}
]
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
})
],
}
|
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
entry: {
main: __dirname + "/src/InfiniteAnyHeight.jsx",
},
output: {
filename: "[name].js",
path: __dirname + "/dist",
library: "InfiniteAnyHeight",
libraryTarget: "umd",
},
devtool: "source-map",
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/],
use: {
loader: "babel-loader",
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true },
}
]
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
})
],
}
|
Adjust error color to be darker
|
// You still need to register Vuetify itself
// src/plugins/vuetify.js
import Vuetify from 'vuetify/lib'
import PbsLogo from '@/assets/PbsLogo.svg'
import GoogleLogo from '@/assets/GoogleLogo.svg'
import eCampLogo from '@/assets/eCampLogo.svg'
import i18n from '@/plugins/i18n'
import colors from 'vuetify/lib/util/colors'
class VuetifyLoaderPlugin {
install (Vue, options) {
Vue.use(Vuetify)
const opts = {
lang: {
t: (key, ...params) => i18n.t(key, params)
},
icons: {
values: {
pbs: { component: PbsLogo },
google: { component: GoogleLogo },
ecamp: { component: eCampLogo }
}
},
theme: {
themes: {
light: {
error: colors.red.darken2
}
}
}
}
vuetify = new Vuetify(opts)
}
}
export let vuetify
export default new VuetifyLoaderPlugin()
|
// You still need to register Vuetify itself
// src/plugins/vuetify.js
import Vuetify from 'vuetify/lib'
import PbsLogo from '@/assets/PbsLogo.svg'
import GoogleLogo from '@/assets/GoogleLogo.svg'
import eCampLogo from '@/assets/eCampLogo.svg'
import i18n from '@/plugins/i18n'
class VuetifyLoaderPlugin {
install (Vue, options) {
Vue.use(Vuetify)
const opts = {
lang: {
t: (key, ...params) => i18n.t(key, params)
},
icons: {
values: {
pbs: { component: PbsLogo },
google: { component: GoogleLogo },
ecamp: { component: eCampLogo }
}
}
}
vuetify = new Vuetify(opts)
}
}
export let vuetify
export default new VuetifyLoaderPlugin()
|
Fix broken unit test under PHP 8
|
<?php
declare(strict_types=1);
namespace Phpcq\Runner\Test\Config\Builder;
use Phpcq\Runner\Config\Builder\AbstractOptionBuilder;
use Phpcq\Runner\Config\Builder\ConfigOptionBuilderInterface;
use Phpcq\PluginApi\Version10\Configuration\Builder\OptionBuilderInterface;
use Phpcq\PluginApi\Version10\Exception\InvalidConfigurationException;
trait OptionBuilderTestTrait
{
public function testInstantiation(): void
{
$builder = $this->createInstance();
$this->assertInstanceOf(OptionBuilderInterface::class, $builder);
$this->assertInstanceOf(AbstractOptionBuilder::class, $builder);
}
public function testIsRequired(): void
{
$builder = $this->createInstance();
$this->assertSame($builder, $builder->isRequired());
$this->expectException(InvalidConfigurationException::class);
$builder->validateValue(null);
}
abstract public function testDefaultValue(): void;
abstract public function testNormalizesValue(): void;
abstract public function testValidatesValue(): void;
abstract protected function createInstance(): ConfigOptionBuilderInterface;
}
|
<?php
declare(strict_types=1);
namespace Phpcq\Runner\Test\Config\Builder;
use Phpcq\Runner\Config\Builder\AbstractOptionBuilder;
use Phpcq\Runner\Config\Builder\ConfigOptionBuilderInterface;
use Phpcq\PluginApi\Version10\Configuration\Builder\OptionBuilderInterface;
use Phpcq\PluginApi\Version10\Exception\InvalidConfigurationException;
trait OptionBuilderTestTrait
{
public function testInstantiation(): void
{
$builder = $this->createInstance();
$this->assertInstanceOf(OptionBuilderInterface::class, $builder);
$this->assertInstanceOf(AbstractOptionBuilder::class, $builder);
}
public function testIsRequired(): void
{
$builder = $this->createInstance();
$this->assertSame($builder, $builder->isRequired());
$this->expectException(InvalidConfigurationException::class);
$builder->validateValue(null);
}
abstract public function testDefaultValue(): void;
abstract public function testNormalizesValue(): void;
abstract public function testValidatesValue(): void;
abstract protected function createInstance(array $validators = []): ConfigOptionBuilderInterface;
}
|
Improve some tests for calendar conversions.
|
// Copyright (C) 2020 Igalia, S.L. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-temporal.absolute.prototype.todatetime
---*/
const values = [
[null, "null"],
[true, "true"],
["iso8601", "iso8601"],
[2020, "2020"],
[2n, "2"],
];
const absolute = Temporal.Absolute.from("1975-02-02T14:25:36.123456789Z");
const calendar = Temporal.Calendar.from("iso8601");
for (const [input, output] of values) {
let called = 0;
Temporal.Calendar.from = function(argument) {
++called;
assert.sameValue(argument, output);
return calendar;
};
const dateTime = absolute.toDateTime("UTC", input);
assert.sameValue(called, 1);
assert.sameValue(dateTime.calendar, calendar);
}
Temporal.Calendar.from = function() {
throw new Test262Error("Should not call Calendar.from");
};
assert.throws(TypeError, () => absolute.toDateTime("UTC", Symbol()));
|
// Copyright (C) 2020 Igalia, S.L. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-temporal.absolute.prototype.todatetime
---*/
const values = [
[null, "null"],
[true, "true"],
["iso8601", "iso8601"],
[2020, "2020"],
[2n, "2"],
];
const absolute = Temporal.Absolute.from("1975-02-02T14:25:36.123456789Z");
const calendar = Temporal.Calendar.from("iso8601");
for (const [input, output] of values) {
Temporal.Calendar.from = function(argument) {
assert.sameValue(argument, output);
return calendar;
};
absolute.toDateTime("UTC", input);
}
Temporal.Calendar.from = function() {
throw new Test262Error("Should not call Calendar.from");
};
assert.throws(TypeError, () => absolute.toDateTime("UTC", Symbol()));
|
Change adaddress, etc to gaddress, etc in address filter
|
(function() {
'use strict';
/**
* Generate a human-readable address string from a single museum object
*
* Can get fancy here and prioritize one of the three address types provided:
* source address, geocoded address, physical address
*
* For now, default to geocoded address since that's what seems to always be populated
*/
/* ngInject */
function AddressFilter() {
return function (input) {
var address = input.gstreet;
var city = input.gcity;
var state = input.gstate;
var zip = input.gzip;
return address + ', ' + city + ', ' + state + ' ' + zip;
};
}
angular.module('imls.museum')
.filter('imlsAddress', AddressFilter);
})();
|
(function() {
'use strict';
/**
* Generate a human-readable address string from a single museum object
*
* Can get fancy here and prioritize one of the three address types provided:
* source address, geocoded address, physical address
*
* For now, default to geocoded address since that's what seems to always be populated
*/
/* ngInject */
function AddressFilter() {
return function (input) {
var address = input.adstreet;
var city = input.adcity;
var state = input.adstate;
var zip = input.adzip;
return address + ', ' + city + ', ' + state + ' ' + zip;
};
}
angular.module('imls.museum')
.filter('imlsAddress', AddressFilter);
})();
|
Improve the query execution order.
|
from application import app
from flask.ext.restful import Api, Resource
import os
from subprocess import Popen as run, PIPE
from distutils.sysconfig import get_python_lib
from autoupdate import lib_path, db_path
api = Api(app)
fetch = '{:s}/hmmer/easel/miniapps/esl-afetch'.format(lib_path)
def db(query):
cmd = [fetch, db_path, query]
return run(cmd, stdout=PIPE).communicate()[0]
class QueryAPI(Resource):
def get(self, query):
queries = [query, query.upper(), query.capitalize(), query.lower()]
for q in queries:
output = db(q)
if output:
return {'query': q, 'output': output}
return {'query': query, 'output': output}
api.add_resource(QueryAPI, '/api/query/<string:query>', endpoint = 'query')
|
from application import app
from flask.ext.restful import Api, Resource
import os
from subprocess import Popen as run, PIPE
from distutils.sysconfig import get_python_lib
from autoupdate import lib_path, db_path
api = Api(app)
fetch = '{:s}/hmmer/easel/miniapps/esl-afetch'.format(lib_path)
def db(query):
cmd = [fetch, db_path, query]
return run(cmd, stdout=PIPE).communicate()[0]
class QueryAPI(Resource):
def get(self, query):
queries = [query, query.capitalize(), query.upper(), query.lower()]
for q in queries:
output = db(q)
if output:
return {'query': q, 'output': output}
return {'query': query, 'output': output}
api.add_resource(QueryAPI, '/api/query/<string:query>', endpoint = 'query')
|
Index all scrolled models by perma id in entry state
|
import {watchCollection} from '../collections';
export function watchCollections({chapters, sections, contentElements, files}, {dispatch}) {
watchCollection(chapters, {
name: 'chapters',
attributes: ['id', 'permaId'],
keyAttribute: 'permaId',
includeConfiguration: true,
dispatch
});
watchCollection(sections, {
name: 'sections',
attributes: ['id', 'permaId', 'chapterId'],
keyAttribute: 'permaId',
includeConfiguration: true,
dispatch
});
watchCollection(contentElements, {
name: 'contentElements',
attributes: ['id', 'permaId', 'typeName', 'sectionId'],
keyAttribute: 'permaId',
includeConfiguration: true,
dispatch
});
Object.keys(files).forEach(collectionName => {
watchCollection(files[collectionName], {
name: camelize(collectionName),
attributes: ['id', {permaId: 'perma_id'}, 'width', 'height', 'basename'],
keyAttribute: 'permaId',
includeConfiguration: true,
dispatch
});
});
}
function camelize(snakeCase) {
return snakeCase.replace(/_[a-z]/g, function(match) {
return match[1].toUpperCase();
});
}
|
import {watchCollection} from '../collections';
export function watchCollections({chapters, sections, contentElements, files}, {dispatch}) {
watchCollection(chapters, {
name: 'chapters',
attributes: ['id', 'permaId'],
includeConfiguration: true,
dispatch
});
watchCollection(sections, {
name: 'sections',
attributes: ['id', 'permaId', 'chapterId'],
includeConfiguration: true,
dispatch
});
watchCollection(contentElements, {
name: 'contentElements',
attributes: ['id', 'permaId', 'typeName', 'sectionId'],
keyAttribute: 'permaId',
includeConfiguration: true,
dispatch
});
Object.keys(files).forEach(collectionName => {
watchCollection(files[collectionName], {
name: camelize(collectionName),
attributes: ['id', {permaId: 'perma_id'}, 'width', 'height', 'basename'],
keyAttribute: 'permaId',
includeConfiguration: true,
dispatch
});
});
}
function camelize(snakeCase) {
return snakeCase.replace(/_[a-z]/g, function(match) {
return match[1].toUpperCase();
});
}
|
Fix for Connectivity status check
Updates connectivity status check to match best practice from
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#DetermineType
|
package org.commcare.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
/**
* @author Phillip Mates (pmates@dimagi.com)
*/
public class ConnectivityStatus {
public static boolean isAirplaneModeOn(Context context) {
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.Global.getInt(context.getApplicationContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
} else {
return Settings.System.getInt(context.getApplicationContext().getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
}
|
package org.commcare.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
/**
* @author Phillip Mates (pmates@dimagi.com)
*/
public class ConnectivityStatus {
public static boolean isAirplaneModeOn(Context context) {
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.Global.getInt(context.getApplicationContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
} else {
return Settings.System.getInt(context.getApplicationContext().getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
|
Set initial focused option item
|
var $ = require('jquery');
module.exports = {
$doc: $(document),
setupDom: function () {
this.$el = $(this.element);
this.$el.addClass(this.options.classes.originalSelect);
// Setup wrapper
this.$wrapper = $('<div />', {
'class': this.options.classes.wrapper
});
// Setup select
this.$select = $('<button />', {
type: 'button',
'class': this.options.classes.select
});
// Setup option list
this.$optionList = $('<ul />', {
'class': [this.options.classes.optionList, this.options.classes.isHidden].join(' ')
});
this.renderOptions();
this.renderSelect(this.getContent());
this.setActiveOption(this.getValue(), true);
this.setFocusedOption(this.getValue());
// Go!
this.$wrapper
.insertBefore(this.$el)
.append(this.$el, this.$select, this.$optionList);
},
destroyDom: function () {
this.$el
.removeClass(this.options.classes.originalSelect)
.insertBefore(this.$wrapper);
this.$wrapper.remove();
}
};
|
var $ = require('jquery');
module.exports = {
$doc: $(document),
setupDom: function () {
this.$el = $(this.element);
this.$el.addClass(this.options.classes.originalSelect);
// Setup wrapper
this.$wrapper = $('<div />', {
'class': this.options.classes.wrapper
});
// Setup select
this.$select = $('<button />', {
type: 'button',
'class': this.options.classes.select
});
// Setup option list
this.$optionList = $('<ul />', {
'class': [this.options.classes.optionList, this.options.classes.isHidden].join(' ')
});
this.renderOptions();
this.renderSelect(this.getContent());
this.setActiveOption(this.getValue(), true);
// Go!
this.$wrapper
.insertBefore(this.$el)
.append(this.$el, this.$select, this.$optionList);
},
destroyDom: function () {
this.$el
.removeClass(this.options.classes.originalSelect)
.insertBefore(this.$wrapper);
this.$wrapper.remove();
}
};
|
Fix typo when setting up handler.
|
#
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from mint import amiperms
class AWSHandler(object):
def __init__(self, cfg, db):
self.db = db
self.amiPerms = amiperms.AMIPermissionsManager(cfg, db)
def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None):
self.amiPerms.deleteMemberFromProject(userId, projectId)
def notify_UserProductAdded(self, event, userId, projectId, userlevel = None):
self.amiPerms.addMemberToProject(userId, projectId)
def notify_UserProductChanged(self, event, userId, projectId, oldLevel,
newLevel):
self.amiPerms.setMemberLevel(userId, projectId, oldLevel, newLevel)
def notify_UserCancelled(self, userId):
# yuck.
awsFound, oldAwsAccountNumber = self.db.userData.getDataValue(
userId, 'awsAccountNumber')
self.amiPerms.setUserKey(userId, oldAwsAccountNumber, None)
def notify_ReleasePublished(self, releaseId):
self.amiPerms.publishRelease(releaseId)
def notify_ReleaseUnpublished(self, releaseId):
self.amiPerms.unpublishRelease(releaseId)
|
#
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from mint import amiperms
class AWSHandler(object):
def __init__(self, cfg, db):
self.db = db
self.amiPerms = amiperms.AMIPermissionsManager(cfg, db)
def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None):
self.amiPerms.addMemberToProject(userId, projectId)
def notify_UserProductAdded(self, event, userId, projectId, userlevel = None):
self.amiPerms.deleteMemberFromProject(userId, projectId)
def notify_UserProductChanged(self, event, userId, projectId, oldLevel,
newLevel):
self.amiPerms.setMemberLevel(userId, projectId, oldLevel, newLevel)
def notify_UserCancelled(self, userId):
# yuck.
awsFound, oldAwsAccountNumber = self.db.userData.getDataValue(
userId, 'awsAccountNumber')
self.amiPerms.setUserKey(userId, oldAwsAccountNumber, None)
def notify_ReleasePublished(self, releaseId):
self.amiPerms.publishRelease(releaseId)
def notify_ReleaseUnpublished(self, releaseId):
self.amiPerms.unpublishRelease(releaseId)
|
Add option to select database by index.
|
/**
* Module dependencies.
*/
var redis = require('redis');
exports = module.exports = function(settings, logger) {
var config = settings.toObject();
if (!config.host) { throw new Error('Redis host not set in config'); }
var host = config.host;
var port = config.port || 6379;
var db = config.db;
var client = redis.createClient(port, host);
if (db) {
logger.debug('Selecting Redis database %d', db);
client.select(db);
}
// NOTE: By default, if the connection to Redis is closed, the process will
// exit. In accordance with a microservices architecture, it is
// expected that a higher-level monitor will detect process termination
// and restart as necessary.
client.on('close', function() {
logger.error('Redis connection closed');
process.exit(-1);
});
// NOTE: By default, if an error is encountered from Redis it will be
// rethrown. This will cause an `uncaughtException` within Node and the
// process will exit. In accordance with a microservices architecture,
// it is expected that a higher-level monitor will detect process
// failures and restart as necessary.
client.on('error', function(err) {
logger.error('Unexpected error from Redis: %s', err.message);
logger.error(err.stack);
throw err;
});
return client;
}
/**
* Component annotations.
*/
exports['@singleton'] = true;
exports['@require'] = ['settings', 'logger'];
|
/**
* Module dependencies.
*/
var redis = require('redis');
exports = module.exports = function(settings, logger) {
var config = settings.toObject();
if (!config.host) { throw new Error('Redis host not set in config'); }
var host = config.host;
var port = config.port || 6379;
var client = redis.createClient(port, host);
// NOTE: By default, if the connection to Redis is closed, the process will
// exit. In accordance with a microservices architecture, it is
// expected that a higher-level monitor will detect process termination
// and restart as necessary.
client.on('close', function() {
logger.error('Redis connection closed');
process.exit(-1);
});
// NOTE: By default, if an error is encountered from Redis it will be
// rethrown. This will cause an `uncaughtException` within Node and the
// process will exit. In accordance with a microservices architecture,
// it is expected that a higher-level monitor will detect process
// failures and restart as necessary.
client.on('error', function(err) {
logger.error('Unexpected error from Redis: %s', err.message);
logger.error(err.stack);
throw err;
});
return client;
}
/**
* Component annotations.
*/
exports['@singleton'] = true;
exports['@require'] = ['settings', 'logger'];
|
Handle blog posts front page
|
<?php
// If blog posts configured for front page, pass on handling
if ( 'posts' == get_option( 'show_on_front' ) ) {
include( get_home_template() );
return;
}
?>
<?php get_header(); ?>
<main>
<!--Main layout-->
<div class="container">
<div class="row">
<!--Main column-->
<div class="col-md-12 col-lg-8 posts-col">
<?php
if ( is_active_sidebar( 'frontpage' ) ) {
dynamic_sidebar( 'frontpage' );
} elseif ( have_posts() ) {
while ( have_posts() ) {
the_post();
?>
<!--Post-->
<div <?php post_class( 'card post-wrapper' ); ?>>
<?php get_template_part( 'template-parts/content', get_post_format() ); ?>
</div>
<!--/Post-->
<?php
}
seabadgermd_pagination();
}
?>
</div>
<!--/Main column-->
<!--Sidebar-->
<?php get_sidebar(); ?>
<!--/Sidebar-->
</div>
</div>
<!--/Main layout-->
</main>
<?php get_footer(); ?>
|
<?php get_header(); ?>
<main>
<!--Main layout-->
<div class="container">
<div class="row">
<!--Main column-->
<div class="col-md-12 col-lg-8 posts-col">
<?php
if ( is_active_sidebar( 'frontpage' ) ) {
dynamic_sidebar( 'frontpage' );
} elseif ( have_posts() ) {
while ( have_posts() ) {
the_post();
?>
<!--Post-->
<div <?php post_class( 'card post-wrapper' ); ?>>
<?php get_template_part( 'template-parts/content', get_post_format() ); ?>
</div>
<!--/Post-->
<?php
}
seabadgermd_pagination();
}
?>
</div>
<!--/Main column-->
<!--Sidebar-->
<?php get_sidebar(); ?>
<!--/Sidebar-->
</div>
</div>
<!--/Main layout-->
</main>
<?php get_footer(); ?>
|
Increase item max to 500
|
import devtools from '../devtools';
import { REALLY_BIG_NUMBER } from '../utils';
import merge from 'deepmerge';
import PineCone from '../sprites/object/PineCone';
const itemMax = 500;
let items = {
'wood-axe': {
value: true,
sellable: false,
},
bucket: {
value: false,
sellable: false,
},
water: {
value: 0,
max: itemMax,
sellable: false,
},
log: {
value: 0,
max: itemMax,
sellable: true,
},
'pine-cone': {
value: 0,
max: itemMax,
sellable: true,
place: PineCone,
},
};
let money = {
value: 10000,
max: REALLY_BIG_NUMBER,
};
items = merge(items, devtools.enabled ? devtools.items : {});
money = merge(money, devtools.enabled ? devtools.money : {});
export { items, money };
|
import devtools from '../devtools';
import { REALLY_BIG_NUMBER } from '../utils';
import merge from 'deepmerge';
import PineCone from '../sprites/object/PineCone';
const itemMax = 50;
let items = {
'wood-axe': {
value: true,
sellable: false,
},
bucket: {
value: false,
sellable: false,
},
water: {
value: 0,
max: itemMax,
sellable: false,
},
log: {
value: 0,
max: itemMax,
sellable: true,
},
'pine-cone': {
value: 0,
max: itemMax,
sellable: true,
place: PineCone,
},
};
let money = {
value: 10000,
max: REALLY_BIG_NUMBER,
};
items = merge(items, devtools.enabled ? devtools.items : {});
money = merge(money, devtools.enabled ? devtools.money : {});
export { items, money };
|
Fix test wasn't actually testing
|
let ivm = require('isolated-vm');
let isolate = new ivm.Isolate;
function makeContext() {
let context = isolate.createContextSync();
let global = context.globalReference();
global.setSync('ivm', ivm);
isolate.compileScriptSync(`
function makeReference(ref) {
return new ivm.Reference(ref);
}
function isReference(ref) {
return ref instanceof ivm.Reference;
}
`).runSync(context);
return {
makeReference: global.getSync('makeReference'),
isReference: global.getSync('isReference'),
};
}
let context1 = makeContext();
let context2 = makeContext();
[ context1, context2 ].forEach(context => {
if (!context.isReference.applySync(null, [ new ivm.Reference({}) ])) {
console.log('fail1');
}
if (!context.isReference.applySync(null, [ context.makeReference.applySync(null, [ 1 ]) ])) {
console.log('fail2');
}
});
if (context1.isReference.applySync(null, [ context2.makeReference.applySync(null, [ 1 ]).derefInto() ])) {
console.log('fail3');
}
console.log('pass');
|
let ivm = require('isolated-vm');
let isolate = new ivm.Isolate;
function makeContext() {
let context = isolate.createContextSync();
let global = context.globalReference();
global.setSync('ivm', ivm);
isolate.compileScriptSync(`
function makeReference(ref) {
return new ivm.Reference(ref);
}
function isReference(ref) {
return ref instanceof ivm.Reference;
}
`).runSync(context);
return {
makeReference: global.getSync('makeReference'),
isReference: global.getSync('isReference'),
};
}
let context1 = makeContext();
let context2 = makeContext();
[ context1, context2 ].forEach(context => {
if (!context1.isReference.applySync(null, [ new ivm.Reference({}) ])) {
console.log('fail1');
}
if (!context1.isReference.applySync(null, [ context1.makeReference.applySync(null, [ 1 ]) ])) {
console.log('fail2');
}
});
if (context1.isReference.applySync(null, [ context2.makeReference.applySync(null, [ 1 ]).derefInto() ])) {
console.log('fail3');
}
console.log('pass');
|
Check if field exists, not if it's empty
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Diesel Sweeties (web)'
language = 'en'
url = 'http://www.dieselsweeties.com/'
start_date = '2000-01-01'
rights = 'Richard Stevens'
class Crawler(CrawlerBase):
history_capable_date = '2000-01-01'
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -5
def crawl(self, pub_date):
feed = self.parse_feed('http://www.dieselsweeties.com/ds-unifeed.xml')
for entry in feed.for_date(pub_date):
if not hasattr(entry, 'summary'):
continue
url = entry.summary.src('img[src*="/strips/"]')
title = entry.title
text = entry.summary.alt('img[src*="/strips/"]')
return CrawlerImage(url, title, text)
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Diesel Sweeties (web)'
language = 'en'
url = 'http://www.dieselsweeties.com/'
start_date = '2000-01-01'
rights = 'Richard Stevens'
class Crawler(CrawlerBase):
history_capable_date = '2000-01-01'
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -5
def crawl(self, pub_date):
feed = self.parse_feed('http://www.dieselsweeties.com/ds-unifeed.xml')
for entry in feed.for_date(pub_date):
if not entry.summary:
continue
url = entry.summary.src('img[src*="/strips/"]')
title = entry.title
text = entry.summary.alt('img[src*="/strips/"]')
return CrawlerImage(url, title, text)
|
Comment out Analytics ui-router code
|
/* global*/
import config from './index.config';
import routerConfig from './index.route';
import runBlock from './index.run';
import HomeController from './home/home.controller';
import PortfolioIndexService from './home/portfolio-index.service';
angular.module('lazarus', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ui.router'])
// .run(['$rootScope', '$location', '$window', function($rootScope, $location, $window){
// $rootScope
// .$on('$stateChangeSuccess',
// function(event){
// if (!$window.ga)
// return;
//
// $window.ga('send', 'pageview', { page: $location.path() });
// });
// }])
// General config
.config(config)
// Routing
.config(routerConfig)
.service('PortfolioIndex', PortfolioIndexService)
.run(runBlock)
.controller('HomeController', HomeController);
|
/* global*/
import config from './index.config';
import routerConfig from './index.route';
import runBlock from './index.run';
import HomeController from './home/home.controller';
import PortfolioIndexService from './home/portfolio-index.service';
angular.module('lazarus', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ui.router'])
.run(['$rootScope', '$location', '$window', function($rootScope, $location, $window){
$rootScope
.$on('$stateChangeSuccess',
function(event){
if (!$window.ga)
return;
$window.ga('send', 'pageview', { page: $location.path() });
});
}])
// General config
.config(config)
// Routing
.config(routerConfig)
.service('PortfolioIndex', PortfolioIndexService)
.run(runBlock)
.controller('HomeController', HomeController);
|
Adjust JS document ready function
|
"use strict";
$(document).on("ready turbolinks:load", function() { //equivalent of $(document).ready()
console.log("JS loaded.")
addSpace();
var $grid = initMasonry();
// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() {
$grid.masonry('layout');
});
});
function initMasonry() {
return $('.masonry-grid').masonry({ //returns the jquery masonry grid to be stored as a variable
// options
itemSelector: '.card',
// columnWidth: 280, //with no columnWidth set, will take size of first element in grid
horizontalOrder: true,
isFitWidth: true, //breaks columns like media queries
gutter: 20,
transitionDuration: '0.3s'
});
}
function addSpace() {
var spaceBetween = $(".custom-footer").offset().top - $(".navbar").offset().top; //get space between header and footer
var target = 600;
if (spaceBetween < target) { //if space between header and footer < x
var numOfSpaces = (target - spaceBetween) / 35;
for(var i = 0; i < numOfSpaces; i++) {
$("#main-container").append("<p> </p>"); //add space above footer
}
}
}
|
"use strict";
$(document).on("turbolinks:load", function() { //equivalent of $(document).ready()
console.log("JS loaded.")
addSpace();
var $grid = initMasonry();
// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() {
$grid.masonry('layout');
});
});
function initMasonry() {
return $('.masonry-grid').masonry({ //returns the jquery masonry grid to be stored as a variable
// options
itemSelector: '.card',
// columnWidth: 280, //with no columnWidth set, will take size of first element in grid
horizontalOrder: true,
isFitWidth: true, //breaks columns like media queries
gutter: 20,
transitionDuration: '0.3s'
});
}
function addSpace() {
var spaceBetween = $(".custom-footer").offset().top - $(".navbar").offset().top; //get space between header and footer
var target = 600;
if (spaceBetween < target) { //if space between header and footer < x
var numOfSpaces = (target - spaceBetween) / 35;
for(var i = 0; i < numOfSpaces; i++) {
$("#main-container").append("<p> </p>"); //add space above footer
}
}
}
|
Use EventListenerInterface instead of EventListener.
|
<?php
namespace Crud\Core;
use Cake\Controller\Controller;
use Cake\Core\InstanceConfigTrait;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Crud\Event\Subject;
/**
* Crud Base Class
*
* Implement base methods used in CrudAction and CrudListener classes
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
*/
abstract class Object implements EventListenerInterface {
use InstanceConfigTrait;
use ProxyTrait;
/**
* Container with reference to all objects
* needed within the CrudListener and CrudAction
*
* @var \Cake\Controller\Controller
*/
protected $_controller;
/**
* Default configuration
*
* @var array
*/
protected $_defaultConfig = [];
/**
* Constructor
*
* @param \Crud\Event\Subject $subject
* @param array $defaults Default settings
* @return void
*/
public function __construct(Controller $Controller, $config = []) {
$this->_controller = $Controller;
$this->config($config);
}
/**
* List of implemented events
*
* @return array
*/
public function implementedEvents() {
return [];
}
/**
* Convenient method for Request::is
*
* @param string|array $method
* @return boolean
*/
protected function _checkRequestType($method) {
return $this->_request()->is($method);
}
}
|
<?php
namespace Crud\Core;
use Cake\Controller\Controller;
use Cake\Core\InstanceConfigTrait;
use Cake\Event\Event;
use Cake\Event\EventListener;
use Crud\Event\Subject;
/**
* Crud Base Class
*
* Implement base methods used in CrudAction and CrudListener classes
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
*/
abstract class Object implements EventListener {
use InstanceConfigTrait;
use ProxyTrait;
/**
* Container with reference to all objects
* needed within the CrudListener and CrudAction
*
* @var \Cake\Controller\Controller
*/
protected $_controller;
/**
* Default configuration
*
* @var array
*/
protected $_defaultConfig = [];
/**
* Constructor
*
* @param \Crud\Event\Subject $subject
* @param array $defaults Default settings
* @return void
*/
public function __construct(Controller $Controller, $config = []) {
$this->_controller = $Controller;
$this->config($config);
}
/**
* List of implemented events
*
* @return array
*/
public function implementedEvents() {
return [];
}
/**
* Convenient method for Request::is
*
* @param string|array $method
* @return boolean
*/
protected function _checkRequestType($method) {
return $this->_request()->is($method);
}
}
|
Fix the language object (wasn't available before)
|
package ceylon.language;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Object;
@Ceylon(major = 3) @Object
public final class language_ {
public java.lang.String getVersion() {
return Versions.CEYLON_VERSION_NUMBER;
}
public long getMajorVersion() {
return Versions.CEYLON_VERSION_MAJOR;
}
public long getMinorVersion() {
return Versions.CEYLON_VERSION_MINOR;
}
public long getReleaseVersion() {
return Versions.CEYLON_VERSION_RELEASE;
}
public java.lang.String getVersionName() {
return Versions.CEYLON_VERSION_NAME;
}
public long getMajorVersionBinary() {
return Versions.JVM_BINARY_MAJOR_VERSION;
}
public long getMinorVersionBinary() {
return Versions.JVM_BINARY_MINOR_VERSION;
}
@Override
public java.lang.String toString() {
return "language";
}
private language_() {}
private static final language_ value = new language_();
public static language_ getLanguage$() {
return value;
}
}
|
package ceylon.language;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Object;
@Ceylon(major = 3) @Object
public final class language_ {
public java.lang.String getVersion() {
return Versions.CEYLON_VERSION_NUMBER;
}
public long getMajorVersion() {
return Versions.CEYLON_VERSION_MAJOR;
}
public long getMinorVersion() {
return Versions.CEYLON_VERSION_MINOR;
}
public long getReleaseVersion() {
return Versions.CEYLON_VERSION_RELEASE;
}
public java.lang.String getVersionName() {
return Versions.CEYLON_VERSION_NAME;
}
public long getMajorVersionBinary() {
return Versions.JVM_BINARY_MAJOR_VERSION;
}
public long getMinorVersionBinary() {
return Versions.JVM_BINARY_MINOR_VERSION;
}
@Override
public java.lang.String toString() {
return "language";
}
private language_() {}
private static final language_ value = new language_();
public static language_ getLanguage() {
return value;
}
}
|
Add _capnp for original Cython module. Meant for testing.
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
import capnp as _capnp
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
Add settings support for tmdb keys
|
'use strict';
// Load requirements
const parser = require('parse-torrent-name');
// Load libraries
const settings = __require('libs/settings');
// Create promise to resolve with dataset
module.exports = function(filename) {
return new Promise((resolve, reject) => {
// Variables
let source;
// No file provided
if ( filename === undefined ) {
return reject('No filename provided');
}
// Check for tmdb key
/* istanbul ignore if */
if ( process.env.TMDB_KEY) {
source = require('./show/tmdb')(process.env.TMDB_KEY);
} else if ( settings.tmdb && settings.tmdb.key ) {
source = require('./show/tmdb')(settings.tmdb.key);
} else {
source = require('./show/tvmaze')();
}
// Decode episode details from filename
let details = parser(filename);
// Check we have what we need to continue
// TODO: Replace with better validation
if ( ! details.title || ! details.season || ! details.episode ) {
return resolve({});
}
// Check for the show in cache
source.findShow(details.title).then((show) => {
return source.findEpisode(details.title, details.season, details.episode);
}).then((episode) => {
episode.type = 'show';
return resolve(episode);
}).catch((err) => {
return reject(err);
});
});
};
|
'use strict';
// Load requirements
const parser = require('parse-torrent-name');
// Create promise to resolve with dataset
module.exports = function(filename) {
return new Promise((resolve, reject) => {
// Variables
let source;
// No file provided
if ( filename === undefined ) {
return reject('No filename provided');
}
// Check for tmdb key
/* istanbul ignore if */
if ( process.env.TMDB_KEY ) {
source = require('./show/tmdb')(process.env.TMDB_KEY);
} else {
source = require('./show/tvmaze')();
}
// Decode episode details from filename
let details = parser(filename);
// Check we have what we need to continue
// TODO: Replace with better validation
if ( ! details.title || ! details.season || ! details.episode ) {
return resolve({});
}
// Check for the show in cache
source.findShow(details.title).then((show) => {
return source.findEpisode(details.title, details.season, details.episode);
}).then((episode) => {
episode.type = 'show';
return resolve(episode);
}).catch((err) => {
return reject(err);
});
});
};
|
Snoop: Add host to ARP table if MAC not found
Signed-off-by: Claudio Matsuoka <ef7f691d9947ca9adbfeb1538a53a661ec9f041b@gmail.com>
|
package main
import (
"fmt"
"net"
"github.com/cmatsuoka/ouidb"
"github.com/mostlygeek/arp"
)
var db *ouidb.OuiDB
func init() {
db = ouidb.New("/etc/manuf")
if db == nil {
db = ouidb.New("manuf")
}
}
func getMAC(s string) (string, error) {
ifaces, err := net.Interfaces()
checkError(err)
for _, i := range ifaces {
if i.Name == s {
return i.HardwareAddr.String(), nil
}
}
return "", fmt.Errorf("%s: no such interface", s)
}
func getName(addr string) string {
names, err := net.LookupAddr(addr)
if err != nil {
return ""
}
return names[0]
}
func getMACFromIP(addr string) string {
arp.CacheUpdate()
mac := arp.Search(addr)
if mac != "" {
return mac
}
ip := net.ParseIP(addr)
if ip == nil {
return mac
}
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{ip, 0, ""})
if err != nil {
return mac
}
conn.Write([]byte{0})
conn.Close()
arp.CacheUpdate()
return arp.Search(addr)
}
func getVendor(mac string) string {
v, _ := db.Lookup(mac)
return v
}
|
package main
import (
"fmt"
"net"
"github.com/cmatsuoka/ouidb"
"github.com/mostlygeek/arp"
)
var db *ouidb.OuiDB
func init() {
db = ouidb.New("/etc/manuf")
if db == nil {
db = ouidb.New("manuf")
}
}
func getMAC(s string) (string, error) {
ifaces, err := net.Interfaces()
checkError(err)
for _, i := range ifaces {
if i.Name == s {
return i.HardwareAddr.String(), nil
}
}
return "", fmt.Errorf("%s: no such interface", s)
}
func getName(addr string) string {
names, err := net.LookupAddr(addr)
if err != nil {
return ""
}
return names[0]
}
func getMACFromIP(addr string) string {
arp.CacheUpdate()
return arp.Search(addr)
}
func getVendor(mac string) string {
v, _ := db.Lookup(mac)
return v
}
|
Use a fixed size of 100 bytes for the randomly generated data
|
'use strict';
const chai = require('chai');
const crypto = require('crypto');
const lzo = require('../index');
const expect = chai.expect;
let data = crypto.randomBytes(100),
compressed;
describe('Compression', () => {
it('Should throw if nothing is passed', () =>
expect(() => lzo.compress()).to.throw() );
it('Should properly compress and not throw', () => {
expect(() => {
compressed = lzo.compress(data)
}).to.not.throw();
});
});
describe('Decompression', () => {
it('Should throw if nothing is passed', () =>
expect(() => lzo.decompress()).to.throw() );
it('Should properly decompress and not throw', () =>
expect( data.compare(lzo.decompress(compressed)) ).to.equal(0) );
});
describe('Properties', () => {
it('Should have property \'version\'', () =>
expect(lzo).to.have.ownProperty('version') );
it('Should have property \'versionDate\'', () =>
expect(lzo).to.have.ownProperty('versionDate') );
it('Should have property \'errors\' (lzo error codes)', () =>
expect(lzo).to.have.ownProperty('errors') );
});
|
'use strict';
const chai = require('chai');
const crypto = require('crypto');
const lzo = require('../index');
const expect = chai.expect;
let data = crypto.randomBytes(Math.floor(Math.random() * 500)),
compressed;
describe('Compression', () => {
it('Should throw if nothing is passed', () =>
expect(() => lzo.compress()).to.throw() );
it('Should properly compress and not throw', () => {
expect(() => {
compressed = lzo.compress(data)
}).to.not.throw();
});
});
describe('Decompression', () => {
it('Should throw if nothing is passed', () =>
expect(() => lzo.decompress()).to.throw() );
it('Should properly decompress and not throw', () =>
expect( data.compare(lzo.decompress(compressed)) ).to.equal(0) );
});
describe('Properties', () => {
it('Should have property \'version\'', () =>
expect(lzo).to.have.ownProperty('version') );
it('Should have property \'versionDate\'', () =>
expect(lzo).to.have.ownProperty('versionDate') );
it('Should have property \'errors\' (lzo error codes)', () =>
expect(lzo).to.have.ownProperty('errors') );
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.