text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change file name to logger name in example settings
|
"""
Example settings module.
This should be copied as `settings.py` and the values modified there.
That file is ignored by the repo, since it will contain environment
specific and sensitive information (like passwords).
"""
import logging
import os
import re
import yaml
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml')
#- file: %(pathname)s
# function: %(funcName)s
LOGGING_FORMAT = '''
- level: %(levelname)s
line: %(lineno)s
logger: %(name)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
def get_csv_file_types():
csv_file_types = None
with open(SETTINGS_YAML_PATH) as r:
csv_file_types = yaml.load(r)
return csv_file_types
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
|
"""
Example settings module.
This should be copied as `settings.py` and the values modified there.
That file is ignored by the repo, since it will contain environment
specific and sensitive information (like passwords).
"""
import logging
import os
import re
import yaml
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml')
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
def get_csv_file_types():
csv_file_types = None
with open(SETTINGS_YAML_PATH) as r:
csv_file_types = yaml.load(r)
return csv_file_types
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
|
Add comments to gulp file
|
var git = require('gulp-git');
var gulp = require('gulp');
/*
* Release Tasks
*/
// Git Tag
gulp.task('publish:tag', function(done) {
// get the version from package.json
var pkg = JSON.parse(require('fs').readFileSync('./package.json'));
// prepend the 'v'
var v = 'v' + pkg.version;
// Tag message
var message = 'Release ' + v;
// tag the current commit
git.tag(v, message, function (err) {
if (err) throw err;
// push to origin
git.push('origin', v, function (err) {
if (err) throw err;
done();
});
});
});
// NPM Publish
gulp.task('publish:npm', function(done) {
// get the npm child process
require('child_process')
// spawn another npm process with the command of publish
.spawn('npm', ['publish'], { stdio: 'inherit' })
.on('close', done);
});
// Expose a single command to git tag and npm publish
gulp.task('release', ['publish:tag', 'publish:npm']);
|
var git = require('gulp-git');
var gulp = require('gulp');
/**
* Release Tasks
*/
gulp.task('publish:tag', function(done) {
var pkg = JSON.parse(require('fs').readFileSync('./package.json'));
var v = 'v' + pkg.version;
var message = 'Release ' + v;
git.tag(v, message, function (err) {
if (err) throw err;
git.push('origin', v, function (err) {
if (err) throw err;
done();
});
});
});
gulp.task('publish:npm', function(done) {
require('child_process')
.spawn('npm', ['publish'], { stdio: 'inherit' })
.on('close', done);
});
gulp.task('release', ['publish:tag', 'publish:npm']);
|
Save request in new m2m filed
|
from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, slug = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
kwargs = {
'pk': int(slug)
}
except ValueError:
kwargs = {'slug': slug}
try:
iobj = InformationObject.objects.get(campaign=campaign, **kwargs)
except InformationObject.DoesNotExist:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
if iobj.foirequest is None:
iobj.foirequest = sender
iobj.foirequests.add(sender)
iobj.save()
|
from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, slug = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
kwargs = {
'pk': int(slug)
}
except ValueError:
kwargs = {'slug': slug}
try:
iobj = InformationObject.objects.get(campaign=campaign, **kwargs)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
|
Use project member email if given
|
# -*- coding: utf-8 -*-
"""
folivora.utils.notification
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Framework for user/project notifications.
"""
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
def route_notifications(*log_entries):
for entry in log_entries:
if entry.action in ACTION_MAPPING:
ACTION_MAPPING[entry.action](entry)
def send_update_avilable_notification(log):
message = loader.render_to_string('notifications/update_available.mail.txt',
{'log': log})
subject = '{prefix}New update available for project "{project}"'.format(**{
'prefix': settings.EMAIL_SUBJECT_PREFIX,
'project': log.project.name})
mails = []
members = log.project.projectmember_set.all()
for member in members:
mails.append(member.mail or member.user.email)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, mails,
fail_silently=False)
ACTION_MAPPING = {
'update_available': send_update_avilable_notification
}
|
# -*- coding: utf-8 -*-
"""
folivora.utils.notification
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Framework for user/project notifications.
"""
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
def route_notifications(*log_entries):
for entry in log_entries:
if entry.action in ACTION_MAPPING:
ACTION_MAPPING[entry.action](entry)
def send_update_avilable_notification(log):
message = loader.render_to_string('notifications/update_available.mail.txt',
{'log': log})
subject = '{prefix}New update available for project "{project}"'.format(**{
'prefix': settings.EMAIL_SUBJECT_PREFIX,
'project': log.project.name})
emails = log.project.members.values_list('email', flat=True)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, emails,
fail_silently=False)
ACTION_MAPPING = {
'update_available': send_update_avilable_notification
}
|
Remove silly stylism for "( document )"
|
/**
* Interactive features for the external menus functionality
*
* This piece of JS is loaded on both the list view app for the
* epfl-external-menu custom post type, and in the Appearance -> Menus
* screen (although at the moment it does nothing on the latter).
*/
/**
* Activate the app on the epfl-external-menu list view screen
*/
function initExternalMenuList ($) {
$('a.page-title-action').remove();
$('h1.wp-heading-inline').after('<button class="page-title-action">' + wp.translations.refresh_button + '</button>');
var $button = $('h1.wp-heading-inline').next();
var spinning = false;
$button.click(function() {
if (spinning) return;
var $form = window.EPFLMenus.asWPAdminPostForm('refresh');
$form.submit();
var $spinner = $('<span class="ajax-spinner"></span>');
$button.append($spinner);
spinning = true;
});
}
jQuery(document).ready(function($) {
if (window.wp.screen.base === 'edit' && window.wp.screen.post_type === 'epfl-external-menu' ) {
initExternalMenuList($);
}
// If you see this, nothing threw or crashed (yet).
console.log('epfl-menus-admin.js is on duty.');
});
|
/**
* Interactive features for the external menus functionality
*
* This piece of JS is loaded on both the list view app for the
* epfl-external-menu custom post type, and in the Appearance -> Menus
* screen (although at the moment it does nothing on the latter).
*/
/**
* Activate the app on the epfl-external-menu list view screen
*/
function initExternalMenuList ($) {
$('a.page-title-action').remove();
$('h1.wp-heading-inline').after('<button class="page-title-action">' + wp.translations.refresh_button + '</button>');
var $button = $('h1.wp-heading-inline').next();
var spinning = false;
$button.click(function() {
if (spinning) return;
var $form = window.EPFLMenus.asWPAdminPostForm('refresh');
$form.submit();
var $spinner = $('<span class="ajax-spinner"></span>');
$button.append($spinner);
spinning = true;
});
}
jQuery( document ).ready(function($) {
if (window.wp.screen.base === 'edit' && window.wp.screen.post_type === 'epfl-external-menu' ) {
initExternalMenuList($);
}
// If you see this, nothing threw or crashed (yet).
console.log('epfl-menus-admin.js is on duty.');
});
|
Return a 404 response when a blog post isn't found.
|
package uk.co.todddavies.website.blog;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.template.soy.jbcsrc.api.SoySauce;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Singleton
final class BlogPostServletModule extends HttpServlet {
static final ImmutableMap<String, String> PATH_MAP = ImmutableMap.of(
"how-to-pull", "howToPull",
"starting-a-blog", "startingABlog"
);
private final SoySauce soySauce;
@Inject
private BlogPostServletModule(SoySauce soySauce) {
this.soySauce = soySauce;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String postPath = request.getPathInfo();
if (postPath.startsWith("/")) {
postPath = postPath.substring(1);
}
if (!PATH_MAP.containsKey(postPath)) {
response.sendError(404, String.format("Post '%s' not found.", postPath));
return;
}
response.getWriter().print(
soySauce
.renderTemplate("todddavies.website.blog." + PATH_MAP.get(postPath))
.renderHtml().get().getContent());
}
}
|
package uk.co.todddavies.website.blog;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.template.soy.jbcsrc.api.SoySauce;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Singleton
final class BlogPostServletModule extends HttpServlet {
static final ImmutableMap<String, String> PATH_MAP = ImmutableMap.of(
"how-to-pull", "howToPull",
"starting-a-blog", "startingABlog"
);
private final SoySauce soySauce;
@Inject
private BlogPostServletModule(SoySauce soySauce) {
this.soySauce = soySauce;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String postPath = request.getPathInfo();
if (postPath.startsWith("/")) {
postPath = postPath.substring(1);
}
response.getWriter().print(
soySauce
.renderTemplate("todddavies.website.blog." + PATH_MAP.get(postPath))
.renderHtml().get().getContent());
}
}
|
Change default timeout value to 2 minutes. JM-1002
git-svn-id: 4206c2c2bb40b5782672a0d03c2c381094954de9@7557 b35dd754-fafc-0310-a699-88a17e54d16e
|
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2007 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.wildfire.nio;
import org.apache.mina.common.IoSession;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.wildfire.XMPPServer;
import org.jivesoftware.wildfire.net.ClientStanzaHandler;
import org.jivesoftware.wildfire.net.StanzaHandler;
/**
* ConnectionHandler that knows which subclass of {@link StanzaHandler} should
* be created and how to build and configure a {@link NIOConnection}.
*
* @author Gaston Dombiak
*/
public class ClientConnectionHandler extends ConnectionHandler {
public ClientConnectionHandler(String serverName) {
super(serverName);
}
NIOConnection createNIOConnection(IoSession session) {
return new NIOConnection(session, XMPPServer.getInstance().getPacketDeliverer());
}
StanzaHandler createStanzaHandler(NIOConnection connection) {
return new ClientStanzaHandler(XMPPServer.getInstance().getPacketRouter(), serverName, connection);
}
int getMaxIdleTime() {
return JiveGlobals.getIntProperty("xmpp.client.idle", 2 * 60 * 1000) / 1000;
}
}
|
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2007 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.wildfire.nio;
import org.apache.mina.common.IoSession;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.wildfire.XMPPServer;
import org.jivesoftware.wildfire.net.ClientStanzaHandler;
import org.jivesoftware.wildfire.net.StanzaHandler;
/**
* ConnectionHandler that knows which subclass of {@link StanzaHandler} should
* be created and how to build and configure a {@link NIOConnection}.
*
* @author Gaston Dombiak
*/
public class ClientConnectionHandler extends ConnectionHandler {
public ClientConnectionHandler(String serverName) {
super(serverName);
}
NIOConnection createNIOConnection(IoSession session) {
return new NIOConnection(session, XMPPServer.getInstance().getPacketDeliverer());
}
StanzaHandler createStanzaHandler(NIOConnection connection) {
return new ClientStanzaHandler(XMPPServer.getInstance().getPacketRouter(), serverName, connection);
}
int getMaxIdleTime() {
return JiveGlobals.getIntProperty("xmpp.client.idle", 30 * 60 * 1000) / 1000;
}
}
|
Test export email return an HttpResponse
|
from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
class MockRequest(object):
pass
site = AdminSite()
user_admin = UserAdmin(User, site)
query_set = User.objects.all()
response = user_admin.export_email(request=MockRequest(), queryset=query_set)
self.assertIsInstance(response, HttpResponse)
|
from django.test import TestCase
from django.contrib.admin.sites import AdminSite
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
|
Revert "added jquery 4 bence"
This reverts commit 036c16bdaeac0d5c4dc3105dcff35f9e61857ca3.
|
<?
//Start of index.php
require_once('engine/require.php');
require_once('engine/includes/motor.php');
?>
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>VPG Blog</title>
<link rel="stylesheet" type="text/css" href="./assets/style/style.css" />
</head><body>
<div id="fejlecKontener">
<header>
<h1>VPG szakkör blog</h1>
</header>
</div>
<div id="tartalomKontener">
<aside id="oldalsav">
<? require('engine/includes/loginform.php'); ?>
</aside>
<article>
<? require('engine/includes/tartalom.php'); ?>
</article>
<div class="clearer"></div>
</div>
<div id="lablecKontener">
<footer>
Copyright
</footer>
</div>
</body></html>
|
<?
//Start of index.php
require_once('engine/require.php');
require_once('engine/includes/motor.php');
?>
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>VPG Blog</title>
<link rel="stylesheet" type="text/css" href="./assets/style/style.css" />
</head><body onload="JSL('assets/style/main.js');">
<script>
//gyorsított betöltődés
function JSL(call) {
var element = document.createElement("script");
element.src = call;
document.body.appendChild(element);
}
JSL("http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js");
</script>
<div id="fejlecKontener">
<header>
<h1>VPG szakkör blog</h1>
</header>
</div>
<div id="tartalomKontener">
<aside id="oldalsav">
<? require('engine/includes/loginform.php'); ?>
</aside>
<article>
<? require('engine/includes/tartalom.php'); ?>
</article>
<div class="clearer"></div>
</div>
<div id="lablecKontener">
<footer>
Copyright
</footer>
</div>
</body></html>
|
Load plugins from entry point
|
"""Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
# Load external commands which register themselves
# with entry point msmbuilder.commands
from pkg_resources import iter_entry_points
for ep in iter_entry_points("msmbuilder.commands"):
external_command = ep.load()
# Some groups start with numbers for ordering
# Some start with descriptions e.g. "MSM"
# Let's set the group to start with ZZZ to put plugins last.
external_command._group = "ZZZ-External_" + external_command._group
class MSMBuilderApp(App):
pass
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
|
"""Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
class MSMBuilderApp(App):
def _subcommands(self):
cmds = super(MSMBuilderApp, self)._subcommands()
# sort the commands in some arbitrary order.
return sorted(cmds, key=lambda e: ''.join(x.__name__ for x in e.mro()))
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
|
Mark this test as a known failure to return the bots to blue
|
# TestREPLPOReplType.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that types defined in the REPL can be po'ed."""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.decorators as decorators
class REPLPOTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
@decorators.swiftTest
@decorators.no_debug_info_test
@decorators.expectedFailureAll(oslist=["macosx", "linux"], bugnumber="rdar://26725839")
def testREPL(self):
REPLTest.testREPL(self)
def doTest(self):
self.command('struct S {}')
self.command(':po S()', patterns=['S'])
self.command('extension S : CustomDebugStringConvertible { public var debugDescription: String { get { return "ABC" } } }')
self.command(':po S()', patterns='ABC')
|
# TestREPLPOReplType.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that types defined in the REPL can be po'ed."""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
class REPLPOTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
self.command('struct S {}')
self.command(':po S()', patterns=['S'])
self.command('extension S : CustomDebugStringConvertible { public var debugDescription: String { get { return "ABC" } } }')
self.command(':po S()', patterns='ABC')
|
Decrease reset delay to 10 seconds.
|
/*global CpuSolver GpuSolver Maze */
var RESET_DELAY = 10 * 1000;
function nearest(dim, scale) {
var floor = Math.floor(dim / scale);
return (floor % 2 == 0) ? floor - 1 : floor;
}
var solver = null;
function init() {
var canvas = $('#display')[0],
scale = 14,
w = nearest(canvas.width, scale),
h = nearest(canvas.height, scale),
maze = Maze.kruskal(w, h);
canvas.width = w * scale;
canvas.height = h * scale;
solver = new GpuSolver(w, h, maze, canvas).draw().animate(reset);
function reset() {
window.setTimeout(function() {
solver.reset(Maze.kruskal(w, h));
solver.animate(reset);
}, RESET_DELAY);
}
}
/* requestAnimationFrame shim */
if (window.requestAnimationFrame == null) {
window.requestAnimationFrame =
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
}
$(document).ready(init);
|
/*global CpuSolver GpuSolver Maze */
var RESET_DELAY = 30 * 1000;
function nearest(dim, scale) {
var floor = Math.floor(dim / scale);
return (floor % 2 == 0) ? floor - 1 : floor;
}
var solver = null;
function init() {
var canvas = $('#display')[0],
scale = 14,
w = nearest(canvas.width, scale),
h = nearest(canvas.height, scale),
maze = Maze.kruskal(w, h);
canvas.width = w * scale;
canvas.height = h * scale;
solver = new GpuSolver(w, h, maze, canvas).draw().animate(reset);
function reset() {
window.setTimeout(function() {
solver.reset(Maze.kruskal(w, h));
solver.animate(reset);
}, RESET_DELAY);
}
}
/* requestAnimationFrame shim */
if (window.requestAnimationFrame == null) {
window.requestAnimationFrame =
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
}
$(document).ready(init);
|
Format expected checkin as Y-m-d in form
|
<!-- Purchase Date -->
<div class="form-group {{ $errors->has('purchase_date') ? ' has-error' : '' }}">
<label for="purchase_date" class="col-md-3 control-label">{{ trans('general.purchase_date') }}</label>
<div class="input-group col-md-3">
<div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd" data-autoclose="true">
<input type="text" class="form-control" placeholder="{{ trans('general.select_date') }}" name="purchase_date" id="purchase_date" value="{{ Input::old('purchase_date', $item->purchase_date->format('Y-m-d')) }}">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
{!! $errors->first('purchase_date', '<span class="alert-msg"><i class="fa fa-times"></i> :message</span>') !!}
</div>
</div>
|
<!-- Purchase Date -->
<div class="form-group {{ $errors->has('purchase_date') ? ' has-error' : '' }}">
<label for="purchase_date" class="col-md-3 control-label">{{ trans('general.purchase_date') }}</label>
<div class="input-group col-md-3">
<div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd" data-autoclose="true">
<input type="text" class="form-control" placeholder="{{ trans('general.select_date') }}" name="purchase_date" id="purchase_date" value="{{ Input::old('purchase_date', $item->purchase_date) }}">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
{!! $errors->first('purchase_date', '<span class="alert-msg"><i class="fa fa-times"></i> :message</span>') !!}
</div>
</div>
|
Make the status data migration optional
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-15 14:58
from __future__ import unicode_literals
from django.db import migrations
def update_status_names(apps, schema_editor):
ProjectPhase = apps.get_model('bb_projects', 'ProjectPhase')
updates = {
'plan-new': 'Plan - Draft',
'voting': 'Voting - Running',
'campaign': 'Project - Running',
'done-complete': 'Project - Realised',
'done-incomplete': 'Project - Done',
'closed': 'Rejected / Cancelled'
}
for slug, new_name in updates.items():
try:
phase = ProjectPhase.objects.get(slug=slug)
phase.name = new_name
phase.save()
except ProjectPhase.DoesNotExist:
pass
class Migration(migrations.Migration):
dependencies = [
('bb_projects', '0002_remove_projecttheme_name_nl'),
]
operations = [
migrations.RunPython(update_status_names)
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-15 14:58
from __future__ import unicode_literals
from django.db import migrations
def update_status_names(apps, schema_editor):
ProjectPhase = apps.get_model('bb_projects', 'ProjectPhase')
updates = {
'plan-new': 'Plan - Draft',
'voting': 'Voting - Running',
'campaign': 'Project - Running',
'done-complete': 'Project - Realised',
'done-incomplete': 'Project - Done',
'closed': 'Rejected / Cancelled'
}
for slug, new_name in updates.items():
phase = ProjectPhase.objects.get(slug=slug)
phase.name = new_name
phase.save()
class Migration(migrations.Migration):
dependencies = [
('bb_projects', '0002_remove_projecttheme_name_nl'),
]
operations = [
migrations.RunPython(update_status_names)
]
|
Allow comma-separated values for --previewAttr.
|
#!/usr/bin/env node
/**
* Parse and insert all log lines in a path.
*/
'use strict';
var program = require('commander');
var splitCsv = function(list) {
return list.split(',');
}
// Support all attributes normally defined by config.js.
program
.option('-p, --parser <name>', 'Ex. nginx_access')
.option('-P, --path <file>', 'Ex. /var/log/nginx/access.log')
.option('-t, --tags [list]', 'Ex. tag1,tag2', splitCsv)
.option('-T, --timeAttr [name]', 'Ex. logtime')
.option('-r, --previewAttr [name]', 'Ex. message', splitCsv)
.parse(process.argv);
var source = {
parser: program.parser,
path: program.path,
tags: program.tags,
timeAttr: program.timeAttr,
previewAttr: program.previewAttr
};
if (!source.parser || !source.path) {
console.error('--parser and --path are required');
process.exit(1);
}
GLOBAL.helpers = require(__dirname + '/modules/helpers.js');
var parsers = helpers.requireModule('parsers/parsers');
var lazy = require('lazy');
new lazy(require("fs").createReadStream(source.path))
.lines
.map(String)
.filter(function(line) {
// lazy will convert a blank line to "undefined"
return line !== 'undefined';
})
.join(function (lines) {
parsers.parseAndInsert(source, lines);
});
|
#!/usr/bin/env node
/**
* Parse and insert all log lines in a path.
*/
'use strict';
var program = require('commander');
// Support all attributes normally defined by config.js.
program
.option('-p, --parser <name>', 'Ex. nginx_access')
.option('-P, --path <file>', 'Ex. /var/log/nginx/access.log')
.option('-t, --tags [list]', 'Ex. tag1,tag2', function(list) { return list.split(','); })
.option('-T, --timeAttr [name]', 'Ex. logtime')
.option('-r, --previewAttr [name]', 'Ex. message')
.parse(process.argv);
var source = {
parser: program.parser,
path: program.path,
tags: program.tags,
timeAttr: program.timeAttr,
previewAttr: program.previewAttr
};
if (!source.parser || !source.path) {
console.error('--parser and --path are required');
process.exit(1);
}
GLOBAL.helpers = require(__dirname + '/modules/helpers.js');
var parsers = helpers.requireModule('parsers/parsers');
var lazy = require('lazy');
new lazy(require("fs").createReadStream(source.path))
.lines
.map(String)
.filter(function(line) {
// lazy will convert a blank line to "undefined"
return line !== 'undefined';
})
.join(function (lines) {
parsers.parseAndInsert(source, lines);
});
|
Add a helper to iterate over all endpoint types in a context store
Unused for now.
Signed-off-by: Ian Campbell <a8db091655a7f47ecb9c39a2d278e9662e440dc0@docker.com>
|
package store
// TypeGetter is a func used to determine the concrete type of a context or
// endpoint metadata by returning a pointer to an instance of the object
// eg: for a context of type DockerContext, the corresponding TypeGetter should return new(DockerContext)
type TypeGetter func() interface{}
// NamedTypeGetter is a TypeGetter associated with a name
type NamedTypeGetter struct {
name string
typeGetter TypeGetter
}
// EndpointTypeGetter returns a NamedTypeGetter with the spcecified name and getter
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter {
return NamedTypeGetter{
name: name,
typeGetter: getter,
}
}
// Config is used to configure the metadata marshaler of the context store
type Config struct {
contextType TypeGetter
endpointTypes map[string]TypeGetter
}
// SetEndpoint set an endpoint typing information
func (c Config) SetEndpoint(name string, getter TypeGetter) {
c.endpointTypes[name] = getter
}
// ForeachEndpointType calls cb on every endpoint type registered with the Config
func (c Config) ForeachEndpointType(cb func(string, TypeGetter) error) error {
for n, ep := range c.endpointTypes {
if err := cb(n, ep); err != nil {
return err
}
}
return nil
}
// NewConfig creates a config object
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config {
res := Config{
contextType: contextType,
endpointTypes: make(map[string]TypeGetter),
}
for _, e := range endpoints {
res.endpointTypes[e.name] = e.typeGetter
}
return res
}
|
package store
// TypeGetter is a func used to determine the concrete type of a context or
// endpoint metadata by returning a pointer to an instance of the object
// eg: for a context of type DockerContext, the corresponding TypeGetter should return new(DockerContext)
type TypeGetter func() interface{}
// NamedTypeGetter is a TypeGetter associated with a name
type NamedTypeGetter struct {
name string
typeGetter TypeGetter
}
// EndpointTypeGetter returns a NamedTypeGetter with the spcecified name and getter
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter {
return NamedTypeGetter{
name: name,
typeGetter: getter,
}
}
// Config is used to configure the metadata marshaler of the context store
type Config struct {
contextType TypeGetter
endpointTypes map[string]TypeGetter
}
// SetEndpoint set an endpoint typing information
func (c Config) SetEndpoint(name string, getter TypeGetter) {
c.endpointTypes[name] = getter
}
// NewConfig creates a config object
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config {
res := Config{
contextType: contextType,
endpointTypes: make(map[string]TypeGetter),
}
for _, e := range endpoints {
res.endpointTypes[e.name] = e.typeGetter
}
return res
}
|
Change method order to match filters
|
import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_date(self, data, match):
year = int(match.groupdict()['year'])
month = int(match.groupdict()['month'])
day = int(match.groupdict()['day'])
self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data)
def handle_today(self, data, match):
self.send(str(DDate()), data)
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main()
|
import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_today(self, data, match):
self.send(str(DDate()), data)
def handle_date(self, data, match):
year = int(match.groupdict()['year'])
month = int(match.groupdict()['month'])
day = int(match.groupdict()['day'])
self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data)
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main()
|
Fix brownie points not showing on react pages
|
import { Observable } from 'rx';
import { handleError, setUser, fetchUser } from './types';
export default ({ services }) => ({ dispatch }) => next => {
return function getUserSaga(action) {
if (action.type !== fetchUser) {
return next(action);
}
return services.readService$({ service: 'user' })
.map(({
username,
picture,
points,
isFrontEndCert,
isBackEndCert,
isFullStackCert
}) => {
return {
type: setUser,
payload: {
username,
picture,
points,
isFrontEndCert,
isBackEndCert,
isFullStackCert,
isSignedIn: true
}
};
})
.catch(error => Observable.just({
type: handleError,
error
}))
.doOnNext(dispatch);
};
};
|
import { Observable } from 'rx';
import { handleError, setUser, fetchUser } from './types';
export default ({ services }) => ({ dispatch }) => next => {
return function getUserSaga(action) {
if (action.type !== fetchUser) {
return next(action);
}
return services.readService$({ service: 'user' })
.map(({
username,
picture,
progressTimestamps = [],
isFrontEndCert,
isBackEndCert,
isFullStackCert
}) => {
return {
type: setUser,
payload: {
username,
picture,
points: progressTimestamps.length,
isFrontEndCert,
isBackEndCert,
isFullStackCert,
isSignedIn: true
}
};
})
.catch(error => Observable.just({
type: handleError,
error
}))
.doOnNext(dispatch);
};
};
|
Use local etcd for testing
|
var _ = require('lodash');
var defaultConfig = {
database: {
backend: 'leveldown',
file: __dirname + '/data/baixs.db'
},
etcd: {
host: 'racktables.hupu.com',
port: '4001',
},
zabbix: {
url: '',
user: '',
password: '',
},
};
var config = {
development: function() {
return _.merge(defaultConfig, {
database: {
},
etcd: {
},
zabbix: {
url: 'http://192.168.8.225/zabbix/api_jsonrpc.php',
user: 'Admin',
password: 'zabbix',
},
});
},
test: function() {
return _.merge(defaultConfig,{
database:{
backend: 'memdown'
},
etcd: {
host: 'localhost',
port: 4001
},
zabbix: {
},
});
},
production: function() {
return _.merge(defaultConfig, require('./config.production.js'));
}
};
var env = process.env.NODE_ENV || 'development';
module.exports = config[env]();
|
var _ = require('lodash');
var defaultConfig = {
database: {
backend: 'leveldown',
file: __dirname + '/data/baixs.db'
},
etcd: {
host: 'racktables.hupu.com',
port: '4001',
},
zabbix: {
url: 'http://al.zabbix.hupu.com/api_jsonrpc.php',
user: 'admin',
password: '',
},
};
var config = {
development: function() {
return _.merge(defaultConfig, {
database: {
},
etcd: {
},
zabbix: {
url: 'http://192.168.8.225/zabbix/api_jsonrpc.php',
user: 'Admin',
password: 'zabbix',
},
});
},
test: function() {
return _.merge(defaultConfig,{
database:{
backend: 'memdown'
},
etcd: {
},
zabbix: {
},
});
},
production: function() {
return _.merge(defaultConfig, require('./config.production.js'));
}
};
var env = process.env.NODE_ENV || 'development';
module.exports = config[env]();
|
Fix jest env template value
|
module.exports = {
env: {
amd: <%= (moduleFormat === 'amd') %>,
commonjs: <%= (moduleFormat === 'commonjs') %>,
es6: true,
browser: true,
jquery: true,
mocha: <%= !useJest %>,
jest: <%= !!useJest %>
},
globals: {
sinon: true
},
extends: 'omaha-prime-grade',
plugins: [
'backbone'
],
rules: {
'backbone/collection-model': ['warn'],
'backbone/defaults-on-top': ['warn'],
'backbone/model-defaults': ['warn'],
'backbone/no-collection-models': ['warn'],
'backbone/no-model-attributes': ['warn']
}
};
|
module.exports = {
env: {
amd: <%= (moduleFormat === 'amd') %>,
commonjs: <%= (moduleFormat === 'commonjs') %>,
es6: true,
browser: true,
jquery: true,
mocha: <%= !useJest %>,
jest: <%= useJest %>
},
globals: {
sinon: true
},
extends: 'omaha-prime-grade',
plugins: [
'backbone'
],
rules: {
'backbone/collection-model': ['warn'],
'backbone/defaults-on-top': ['warn'],
'backbone/model-defaults': ['warn'],
'backbone/no-collection-models': ['warn'],
'backbone/no-model-attributes': ['warn']
}
};
|
Use json rather than simplejson
|
import json
from django.http import HttpResponse
class JSONResponseMixin(object):
"""
A Mixin that renders context as a JSON response
"""
def render_to_response(self, context):
"""
Returns a JSON response containing 'context' as payload
"""
return self.get_json_response(self.convert_context_to_json(context))
def get_json_response(self, content, **httpresponse_kwargs):
"""
Construct an `HttpResponse` object.
"""
response = HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
return response
def convert_context_to_json(self, context):
"""
Convert the context dictionary into a JSON object
"""
return json.dumps(context, indent=4)
|
import simplejson as json
from django.http import HttpResponse
class JSONResponseMixin(object):
"""
A Mixin that renders context as a JSON response
"""
def render_to_response(self, context):
"""
Returns a JSON response containing 'context' as payload
"""
return self.get_json_response(self.convert_context_to_json(context))
def get_json_response(self, content, **httpresponse_kwargs):
"""
Construct an `HttpResponse` object.
"""
response = HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
return response
def convert_context_to_json(self, context):
"""
Convert the context dictionary into a JSON object
"""
return json.dumps(context, indent=4)
|
Make the example more informative
|
"""
This example:
1. Connects to the current model
2. Deploy a bundle and waits until it reports itself active
3. Upgrades the charm with a local path
4. Destroys the units and applications
"""
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
local_path = './examples/charms/onos.charm'
print('Upgrading charm with %s' % local_path)
await applications[0].upgrade_charm(path=local_path)
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main())
|
"""
This example:
1. Connects to the current model
2. Deploy a bundle and waits until it reports itself active
3. Destroys the units and applications
"""
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
await applications[0].upgrade_charm(path='./examples/charms/onos.charm')
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main())
|
Fix scroll Component when the page is updated but the feature didn't change
|
import React from 'react'
import Card from '../util/View/Card'
import {PageTitle} from '../util/View/Title'
import {Meta} from '../util/View/Meta'
import FeatureList from '../Feature/List'
import Dependencies from './Dependencies'
const ComponentDetails = ({component}) => <Dependencies component={component} />
const Component = ({prefix, component}) => {
const title = <div>
<PageTitle>{component.name}</PageTitle>
<Meta>{component.Component.__PIGMENT_META.file}</Meta>
</div>
return <div>
<Card id='component' title={title} closable defaultClosed>
<ComponentDetails component={component} />
</Card>
<FeatureList component={component} prefix={prefix} />
</div>
}
export default ({prefix, component}) => class extends React.Component {
constructor () {
super()
document.title = `${component.name}`
}
scrollIfNeeded () {
const featureName = this.props.params.featureName
if (featureName && this.featureName !== featureName) {
document.getElementById(featureName).scrollIntoView()
this.featureName = featureName
}
}
componentDidMount () {
this.scrollIfNeeded()
}
componentDidUpdate () {
this.scrollIfNeeded()
}
render () {
return <Component {...this.props} prefix={prefix} component={component} />
}
}
|
import React from 'react'
import Card from '../util/View/Card'
import {PageTitle} from '../util/View/Title'
import {Meta} from '../util/View/Meta'
import FeatureList from '../Feature/List'
import Dependencies from './Dependencies'
const ComponentDetails = ({component}) => <Dependencies component={component} />
const Component = ({prefix, component}) => {
const title = <div>
<PageTitle>{component.name}</PageTitle>
<Meta>{component.Component.__PIGMENT_META.file}</Meta>
</div>
return <div>
<Card id='component' title={title} closable defaultClosed>
<ComponentDetails component={component} />
</Card>
<FeatureList component={component} prefix={prefix} />
</div>
}
export default ({prefix, component}) => class extends React.Component {
constructor () {
super()
document.title = `${component.name}`
}
componentDidUpdate () {
const featureName = this.props.params.featureName
if (featureName) {
document.getElementById(featureName).scrollIntoView()
}
}
render () {
return <Component {...this.props} prefix={prefix} component={component} />
}
}
|
Fix Auth API key check causing error 500s
|
from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
if 'apikey' in params:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
except:
keyobj = None
if keyobj and keyobj.active:
request.user = AnonymousUser()
return True
return False
def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key')
|
from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
if params['apikey']:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
except:
keyobj = None
if keyobj and keyobj.active:
request.user = AnonymousUser()
return True
return False
def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key')
|
:fire: Remove declaring non-interface public method
|
<?php
/**
* Vainyl
*
* PHP Version 7
*
* @package Core
* @license https://opensource.org/licenses/MIT MIT License
* @link https://vainyl.com
*/
declare(strict_types=1);
namespace Vainyl\Core\Renderer\Decorator;
use Vainyl\Core\AbstractIdentifiable;
use Vainyl\Core\IdentifiableInterface;
use Vainyl\Core\Renderer\RendererInterface;
/**
* Class AbstractRendererDecorator
*
* @author Taras P. Girnyk <taras.p.gyrnik@gmail.com>
*/
abstract class AbstractRendererDecorator extends AbstractIdentifiable implements RendererInterface
{
private $renderer;
/**
* AbstractRendererDecorator constructor.
*
* @param RendererInterface $renderer
*/
public function __construct(RendererInterface $renderer)
{
$this->renderer = $renderer;
}
/**
* @inheritDoc
*/
public function render(IdentifiableInterface $identifiable): array
{
return $this->renderer->render($identifiable);
}
}
|
<?php
/**
* Vainyl
*
* PHP Version 7
*
* @package Core
* @license https://opensource.org/licenses/MIT MIT License
* @link https://vainyl.com
*/
declare(strict_types=1);
namespace Vainyl\Core\Renderer\Decorator;
use Vainyl\Core\AbstractIdentifiable;
use Vainyl\Core\IdentifiableInterface;
use Vainyl\Core\Renderer\RendererInterface;
/**
* Class AbstractRendererDecorator
*
* @author Taras P. Girnyk <taras.p.gyrnik@gmail.com>
*/
abstract class AbstractRendererDecorator extends AbstractIdentifiable implements RendererInterface
{
private $renderer;
/**
* AbstractRendererDecorator constructor.
*
* @param RendererInterface $renderer
*/
public function __construct(RendererInterface $renderer)
{
$this->renderer = $renderer;
}
/**
* @inheritDoc
*/
public function getName(): string
{
return $this->renderer->getName();
}
/**
* @inheritDoc
*/
public function render(IdentifiableInterface $identifiable): array
{
return $this->renderer->render($identifiable);
}
}
|
ENH: Add Choose node to imported nodes
|
################################################################################
# Copyright (C) 2011-2012 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
# Import some most commonly used nodes
from . import *
from .bernoulli import Bernoulli
from .binomial import Binomial
from .categorical import Categorical
from .multinomial import Multinomial
from .poisson import Poisson
from .beta import Beta
from .beta import Complement
from .dirichlet import Dirichlet, DirichletConcentration
from .exponential import Exponential
from .gaussian import Gaussian, GaussianARD
from .wishart import Wishart
from .gamma import Gamma, GammaShape
from .gaussian import (GaussianGamma,
GaussianWishart)
from .gaussian_markov_chain import GaussianMarkovChain
from .gaussian_markov_chain import VaryingGaussianMarkovChain
from .gaussian_markov_chain import SwitchingGaussianMarkovChain
from .categorical_markov_chain import CategoricalMarkovChain
from .mixture import Mixture, MultiMixture
from .gate import Gate
from .gate import Choose
from .concatenate import Concatenate
from .dot import Dot
from .dot import SumMultiply
from .add import Add
from .take import Take
from .gaussian import ConcatGaussian
from .logpdf import LogPDF
from .constant import Constant
|
################################################################################
# Copyright (C) 2011-2012 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
# Import some most commonly used nodes
from . import *
from .bernoulli import Bernoulli
from .binomial import Binomial
from .categorical import Categorical
from .multinomial import Multinomial
from .poisson import Poisson
from .beta import Beta
from .beta import Complement
from .dirichlet import Dirichlet, DirichletConcentration
from .exponential import Exponential
from .gaussian import Gaussian, GaussianARD
from .wishart import Wishart
from .gamma import Gamma, GammaShape
from .gaussian import (GaussianGamma,
GaussianWishart)
from .gaussian_markov_chain import GaussianMarkovChain
from .gaussian_markov_chain import VaryingGaussianMarkovChain
from .gaussian_markov_chain import SwitchingGaussianMarkovChain
from .categorical_markov_chain import CategoricalMarkovChain
from .mixture import Mixture, MultiMixture
from .gate import Gate
from .concatenate import Concatenate
from .dot import Dot
from .dot import SumMultiply
from .add import Add
from .take import Take
from .gaussian import ConcatGaussian
from .logpdf import LogPDF
from .constant import Constant
|
Use request.defaults() to simplify testing
|
const app = require('../app');
const requestPromiseNative = require('request-promise-native');
const seeds = require('../lib/seeds');
const seedData = require('./seedData');
describe('app', () => {
const request = requestPromiseNative.defaults({ baseUrl: 'http://localhost:3000/' });
beforeAll(() => seeds(seedData));
beforeAll(done => app.listen(3000, done));
describe('GET /', () => {
it('responds with success', () => {
return request('/');
});
});
describe('GET /index.json', () => {
it('responds with features', () => {
return request('/index.json', {
headers: { 'Content-Type': /json/ }
}).then(response => expect(response.length).toBeGreaterThan(0));
});
});
describe('GET /404', () => {
it('responds with a 404 error', () => {
return request('/404', {
resolveWithFullResponse: true,
simple: false
}).then(response => expect(response.statusCode).toBe(404));
});
});
});
|
const app = require('../app');
const request = require('request-promise-native');
const seeds = require('../lib/seeds');
const seedData = require('./seedData');
describe('app', () => {
beforeAll(() => seeds(seedData));
beforeAll(done => app.listen(3000, done));
describe('GET /', () => {
it('responds with success', () => {
return request('http://localhost:3000/');
});
});
describe('GET /index.json', () => {
it('responds with features', () => {
return request('http://localhost:3000/index.json', {
headers: { 'Content-Type': /json/ }
}).then(response => expect(response.length).toBeGreaterThan(0));
});
});
describe('GET /404', () => {
it('responds with a 404 error', () => {
return request('http://localhost:3000/404', {
resolveWithFullResponse: true,
simple: false
}).then(response => expect(response.statusCode).toBe(404));
});
});
});
|
Remove all jenkins-specific bits and bobs
|
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = require __DIR__.'/../vendor/autoload.php';
// intl
if (!function_exists('intl_get_error_code')) {
require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
$loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
/**
* Explicitly include some dependencies that otherwise result in 'class not found'
* errors when running on Jenkins.
*
* Works on local dev environment. Works on live. Works on Travis. Doesn't work on Jenkins.
*/
//$jenkinsNeedsThese = array(
// 'Stripe' => '/stripe/stripe-php/lib/Stripe.php',
// 'ExpressiveDate' => '/jasonlewis/expressive-date/src/ExpressiveDate.php'
//);
//
//foreach ($jenkinsNeedsThese as $class => $path) {
// if (!class_exists($class)) {
// var_dump("cp01");
// exit();
//
// require_once(realpath(__DIR__ . '/../vendor' . $path));
// }
//}
return $loader;
|
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = require __DIR__.'/../vendor/autoload.php';
// intl
if (!function_exists('intl_get_error_code')) {
require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
$loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
/**
* Explicitly include some dependencies that otherwise result in 'class not found'
* errors when running on Jenkins.
*
* Works on local dev environment. Works on live. Works on Travis. Doesn't work on Jenkins.
*/
$jenkinsNeedsThese = array(
'Stripe' => '/stripe/stripe-php/lib/Stripe.php',
'ExpressiveDate' => '/jasonlewis/expressive-date/src/ExpressiveDate.php'
);
foreach ($jenkinsNeedsThese as $class => $path) {
if (!class_exists($class)) {
var_dump("cp01");
exit();
require_once(realpath(__DIR__ . '/../vendor' . $path));
}
}
return $loader;
|
Fix invalid use of $this
|
<?php
/**
* Show a warning to an user about the SP requesting SSO a short time after
* doing it previously.
*
* @package SimpleSAMLphp
*/
if (!array_key_exists('StateId', $_REQUEST)) {
throw new \SimpleSAML\Error\BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = \SimpleSAML\Auth\State::loadState($id, 'core:short_sso_interval');
$session = \SimpleSAML\Session::getSessionFromRequest();
if (array_key_exists('continue', $_REQUEST)) {
// The user has pressed the continue/retry-button
\SimpleSAML\Auth\ProcessingChain::resumeProcessing($state);
}
$globalConfig = \SimpleSAML\Configuration::getInstance();
$t = new \SimpleSAML\XHTML\Template($globalConfig, 'core:short_sso_interval.php');
$translator = $t->getTranslator();
$t->data['target'] = \SimpleSAML\Module::getModuleURL('core/short_sso_interval.php');
$t->data['params'] = ['StateId' => $id];
$t->data['trackId'] = $session->getTrackID();
$t->data['header'] = $translator->t('{core:short_sso_interval:warning_header}');
$t->data['autofocus'] = 'contbutton';
$t->show();
|
<?php
/**
* Show a warning to an user about the SP requesting SSO a short time after
* doing it previously.
*
* @package SimpleSAMLphp
*/
if (!array_key_exists('StateId', $_REQUEST)) {
throw new \SimpleSAML\Error\BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = \SimpleSAML\Auth\State::loadState($id, 'core:short_sso_interval');
$session = \SimpleSAML\Session::getSessionFromRequest();
if (array_key_exists('continue', $_REQUEST)) {
// The user has pressed the continue/retry-button
\SimpleSAML\Auth\ProcessingChain::resumeProcessing($state);
}
$globalConfig = \SimpleSAML\Configuration::getInstance();
$t = new \SimpleSAML\XHTML\Template($globalConfig, 'core:short_sso_interval.php');
$t->data['target'] = \SimpleSAML\Module::getModuleURL('core/short_sso_interval.php');
$t->data['params'] = ['StateId' => $id];
$t->data['trackId'] = $session->getTrackID();
$this->data['header'] = $this->t('{core:short_sso_interval:warning_header}');
$this->data['autofocus'] = 'contbutton';
$t->show();
|
Make exception mapper more accurate on jax-rs internal error
|
package fr.insee.pogues.webservice.rest;
import org.apache.log4j.Logger;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
/**
* Created by acordier on 04/07/17.
*/
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
private Status STATUS = Status.INTERNAL_SERVER_ERROR;
private Logger logger = Logger.getLogger(GenericExceptionMapper.class);
public Response toResponse(Throwable error){
RestMessage message = new RestMessage(
STATUS.getStatusCode(),
"An unexpected error occured", error.getMessage());
if(error instanceof NotFoundException) {
STATUS = Status.NOT_FOUND;
message.setMessage("Not Found");
message.setDetails("No JAX-RS resource found for this path");
}
return Response.status(STATUS)
.entity(message)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
|
package fr.insee.pogues.webservice.rest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
/**
* Created by acordier on 04/07/17.
*/
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
private final Status STATUS = Status.INTERNAL_SERVER_ERROR;
public Response toResponse(Throwable error){
RestMessage message = new RestMessage(
STATUS.getStatusCode(),
"An unexpected error occured", error.getMessage());
return Response.status(STATUS)
.entity(message)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
|
[DuckDB] Test DuckDB only with one thread due to multithreading issues
|
package sqlancer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class TestMain {
private static final String NUM_QUERIES = "1000";
private static final String SECONDS = "300";
@Test
public void testDuckDB() {
// run with one thread due to multithreading issues, see https://github.com/sqlancer/sqlancer/pull/45
assertEquals(0, Main.executeMain(new String[] { "--timeout-seconds", SECONDS, "--num-threads", "1",
"--num-queries", NUM_QUERIES, "duckdb", "--oracle", "NoREC" }));
assertEquals(0, Main.executeMain(new String[] { "--timeout-seconds", SECONDS, "--num-threads", "1",
"--num-queries", NUM_QUERIES, "duckdb", "--oracle", "QUERY_PARTITIONING" }));
}
}
|
package sqlancer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class TestMain {
private static final String NUM_QUERIES = "1000";
private static final String SECONDS = "300";
@Test
public void testDuckDB() {
assertEquals(0, Main.executeMain(new String[] { "--timeout-seconds", SECONDS, "--num-queries", NUM_QUERIES,
"duckdb", "--oracle", "NoREC" }));
assertEquals(0, Main.executeMain(new String[] { "--timeout-seconds", SECONDS, "--num-queries", NUM_QUERIES,
"duckdb", "--oracle", "QUERY_PARTITIONING" }));
}
}
|
Make the example test run without requiring local server
|
var util = require('util'),
webdriver = require('selenium-webdriver'),
chrome = require('selenium-webdriver/chrome'),
retry = require('./index.js');
// Assumes that there is a chromedriver binary in the same directory.
var driver = chrome.createDriver(
new webdriver.Capabilities({'browserName': 'chrome'}),
new chrome.ServiceBuilder('./chromedriver').build());
driver.get('http://juliemr.github.io/webdriverjs-retry/');
retry.run(function() {
// Note that everything in here will be retried - including the
// first click.
driver.findElement(webdriver.By.id('showmessage')).click();
// This would throw an error without waiting because the message
// is hidden for 3 seconds.
driver.findElement(webdriver.By.id('message')).click();
}, 5000).then(function() {
// run returns a promise which resolves when all the retrying is done
// If the retry fails (either it times out or the error is not in the ignore
// list) the promise will be rejected.
});
// 7 is the error code for element not found.
retry.ignoring(7).run(function() {
driver.findElement(webdriver.By.id('creatediv')).click();
// This would throw an error because the div does not appear for
// 3 seconds.
driver.findElement(webdriver.By.id('inserted')).getText();
}, 5000);
driver.quit();
|
var util = require('util'),
webdriver = require('selenium-webdriver'),
chrome = require('selenium-webdriver/chrome'),
retry = require('./index.js');
var driver = chrome.createDriver(
new webdriver.Capabilities({'browserName': 'chrome'}),
new chrome.ServiceBuilder('./chromedriver').build());
driver.get('localhost:8888');
retry.run(function() {
// Note that everything in here will be retried - including the
// first click.
driver.findElement(webdriver.By.id('showmessage')).click();
// This would throw an error without waiting because the message
// is hidden for 3 seconds.
driver.findElement(webdriver.By.id('message')).click();
}, 5000).then(function() {
// run returns a promise which resolves when all the retrying is done
// If the retry fails (either it times out or the error is not in the ignore
// list) the promise will be rejected.
});
// 7 is the error code for element not found.
retry.ignoring(7).run(function() {
driver.findElement(webdriver.By.id('creatediv')).click();
// This would throw an error because the div does not appear for
// 3 seconds.
driver.findElement(webdriver.By.id('inserted')).getText();
}, 5000);
driver.quit();
|
Use mirrored system images with "mirrored" prefix
|
package v3
import (
projectv3 "github.com/rancher/rancher/pkg/apis/project.cattle.io/v3"
)
var (
ToolsSystemImages = struct {
PipelineSystemImages projectv3.PipelineSystemImages
AuthSystemImages AuthSystemImages
}{
PipelineSystemImages: projectv3.PipelineSystemImages{
Jenkins: "rancher/pipeline-jenkins-server:v0.1.4",
JenkinsJnlp: "rancher/mirrored-jenkins-jnlp-slave:3.35-4",
AlpineGit: "rancher/pipeline-tools:v0.1.15",
PluginsDocker: "rancher/mirrored-plugins-docker:18.09",
Minio: "rancher/mirrored-minio-minio:RELEASE.2020-07-13T18-09-56Z",
Registry: "registry:2",
RegistryProxy: "rancher/pipeline-tools:v0.1.15",
KubeApply: "rancher/pipeline-tools:v0.1.15",
},
AuthSystemImages: AuthSystemImages{
KubeAPIAuth: "rancher/kube-api-auth:v0.1.4",
},
}
)
|
package v3
import (
projectv3 "github.com/rancher/rancher/pkg/apis/project.cattle.io/v3"
"github.com/rancher/rke/types/image"
)
var (
m = image.Mirror
ToolsSystemImages = struct {
PipelineSystemImages projectv3.PipelineSystemImages
AuthSystemImages AuthSystemImages
}{
PipelineSystemImages: projectv3.PipelineSystemImages{
Jenkins: m("rancher/pipeline-jenkins-server:v0.1.4"),
JenkinsJnlp: m("jenkins/jnlp-slave:3.35-4"),
AlpineGit: m("rancher/pipeline-tools:v0.1.15"),
PluginsDocker: m("plugins/docker:18.09"),
Minio: m("minio/minio:RELEASE.2020-07-13T18-09-56Z"),
Registry: m("registry:2"),
RegistryProxy: m("rancher/pipeline-tools:v0.1.15"),
KubeApply: m("rancher/pipeline-tools:v0.1.15"),
},
AuthSystemImages: AuthSystemImages{
KubeAPIAuth: m("rancher/kube-api-auth:v0.1.4"),
},
}
)
|
[HOUSEKEEPING] Use Factory class from module instead of from __init__
|
# -*- coding: utf-8 -*-
import os
from infcommon.factory import Factory
from infcommon.postgres.postgres import PostgresClient
def postgres_client_from_connection_parameters(user, password, host, port, db_name):
connection_uri = 'postgresql://{user}:{password}@{host}:{port}/{db_name}'.format(user=user, password=password, host=host, port=port, db_name=db_name)
return Factory.instance('posgres_client_from_connection_parameters',
lambda: PostgresClient(connection_uri)
)
def postgres_client_from_connection_os_variable(db_uri_os_valiable_name='LOCAL_PG_DB_URI'):
connection_uri = os.getenv(db_uri_os_valiable_name)
return Factory.instance('posgres_client_from_connection_parameters',
lambda: PostgresClient(connection_uri)
)
|
# -*- coding: utf-8 -*-
import os
from infcommon import Factory
from infcommon.postgres.postgres import PostgresClient
def postgres_client_from_connection_parameters(user, password, host, port, db_name):
connection_uri = 'postgresql://{user}:{password}@{host}:{port}/{db_name}'.format(user=user, password=password, host=host, port=port, db_name=db_name)
return Factory.instance('posgres_client_from_connection_parameters',
lambda: PostgresClient(connection_uri)
)
def postgres_client_from_connection_os_variable(db_uri_os_valiable_name='LOCAL_PG_DB_URI'):
connection_uri = os.getenv(db_uri_os_valiable_name)
return Factory.instance('posgres_client_from_connection_parameters',
lambda: PostgresClient(connection_uri)
)
|
Fix wrong table preferrence for role_user
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('auth.table'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
|
Work around sometimes getting invalid coordinates
|
/**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Feature from 'ol/Feature.js';
import VectorSource from 'ol/source/Vector.js';
import Point from 'ol/geom/Point.js';
import {fromLonLat} from 'ol/proj.js';
export default class VesselSource extends VectorSource {
constructor() {
super();
}
addOrUpdateVessel(vessel) {
let feature = this.getFeatureById(vessel.mmsi);
if (!feature) {
feature = new Feature({
name: vessel.mmsi
});
feature.setId(vessel.mmsi);
this.addFeature(feature);
}
let coord = fromLonLat([vessel.lon, vessel.lat]);
if (!isFinite(coord[0]) || !isFinite(coord[1]))
return;
feature.setGeometry(new Point(coord));
feature.set('data', vessel);
}
};
|
/**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Feature from 'ol/Feature.js';
import VectorSource from 'ol/source/Vector.js';
import Point from 'ol/geom/Point.js';
import {fromLonLat} from 'ol/proj.js';
export default class VesselSource extends VectorSource {
constructor() {
super();
}
addOrUpdateVessel(vessel) {
let feature = this.getFeatureById(vessel.mmsi);
if (!feature) {
feature = new Feature({
name: vessel.mmsi
});
feature.setId(vessel.mmsi);
this.addFeature(feature);
}
feature.setGeometry(new Point(fromLonLat([vessel.lon, vessel.lat])));
feature.set('data', vessel);
}
};
|
Change default subcommand to "source random"
|
import sys
from redcmd.api import execute_commandline
def main():
from .db.manage.db import DB
db = DB()
response = db.check()
from util.printer import printer
response and printer.printf('program maintenance', response)
from .util import log
from .db.app.config import Config, ConfigError
from . import const
config = Config()
try:
log.start(config.eget('client.logfile', default=const.logfile), loglevel=config.eget('client.loglevel', default=40))
except ConfigError as e:
print(str(e) + '\nlog start failed')
from .subcmd import all
from .version import __version__
def update_autocomplete_cb():
printer.printf('program maintenance', 'updated autocomplete data')
execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True,
default_subcommand='source random', moves=True, update_autocomplete_cb=update_autocomplete_cb)
|
import sys
from redcmd.api import execute_commandline
def main():
from .db.manage.db import DB
db = DB()
response = db.check()
from util.printer import printer
response and printer.printf('program maintenance', response)
from .util import log
from .db.app.config import Config, ConfigError
from . import const
config = Config()
try:
log.start(config.eget('client.logfile', default=const.logfile), loglevel=config.eget('client.loglevel', default=40))
except ConfigError as e:
print(str(e) + '\nlog start failed')
from .subcmd import all
from .version import __version__
def update_autocomplete_cb():
printer.printf('program maintenance', 'updated autocomplete data')
execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True,
default_subcommand='change', moves=True, update_autocomplete_cb=update_autocomplete_cb)
|
Fix stats files language issues
- If you used forced_lang stats files were in this language which is bad.
- Force english!
|
<?php
// -----------------------------------------------------------------------------------------------------------
// Pokemons datas
// Total pokemon available
// -----------------------------------------------------------------------------------------------------------
// This file is used to rank by rarity
// Load the pokemons array
// force english language
$config->system->forced_lang = 'en';
include_once($filePath.'/../process/locales.loader.php');
$pokemon_stats['timestamp'] = $timestamp;
$req = "SELECT COUNT(*) as total FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result = $mysqli->query($req);
$data = $result->fetch_object();
$pokemon_stats['pokemon_now'] = $data->total;
$req = "SELECT pokemon_id FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result = $mysqli->query($req);
$rarityarray = array();
while ($data = $result->fetch_object()) {
$poke_id = $data->pokemon_id;
$rarity = $pokemons->pokemon->$poke_id->rarity;
isset($rarityarray[$rarity]) ? $rarityarray[$rarity]++ : $rarityarray[$rarity] = 1;
}
$pokemon_stats['rarity_spawn'] = $rarityarray;
// Add the datas in file
$pokedatas[] = $pokemon_stats;
$json = json_encode($pokedatas);
file_put_contents($pokemonstats_file, $json);
|
<?php
// -----------------------------------------------------------------------------------------------------------
// Pokemons datas
// Total pokemon available
// -----------------------------------------------------------------------------------------------------------
// This file is used to rank by rarity
// Load the pokemons array
// will load english one because language is not set
############################
include_once($filePath.'/../process/locales.loader.php');
$pokemon_stats['timestamp'] = $timestamp;
$req = "SELECT COUNT(*) as total FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result = $mysqli->query($req);
$data = $result->fetch_object();
$pokemon_stats['pokemon_now'] = $data->total;
$req = "SELECT pokemon_id FROM pokemon WHERE disappear_time >= UTC_TIMESTAMP()";
$result = $mysqli->query($req);
$rarityarray = array();
while ($data = $result->fetch_object()) {
$poke_id = $data->pokemon_id;
$rarity = $pokemons->pokemon->$poke_id->rarity;
isset($rarityarray[$rarity]) ? $rarityarray[$rarity]++ : $rarityarray[$rarity] = 1;
}
$pokemon_stats['rarity_spawn'] = $rarityarray;
// Add the datas in file
$pokedatas[] = $pokemon_stats;
$json = json_encode($pokedatas);
file_put_contents($pokemonstats_file, $json);
|
Add note that lazy-installed modules are once-off only.
|
var canihaz = require('canihaz'),
fs = require('fs'),
p = require('path');
/**
* Install dependency modules that are not yet installed, and needed for executing the tasks.
*
* @param {Array} depNames: an array of dependency module names
* @param {String} dir: application directory where node_modules dir is located
* @param {Function} cb: standard cb(err, result) callback
*/
function install(depNames, dir, cb) {
fs.readdir(p.join(dir, 'node_modules'), function(err, installed) {
var uninstalled = [];
depNames.forEach(function (depName) {
if (installed.indexOf(depName) === -1) {
uninstalled.push(depName);
}
});
if (uninstalled.length > 0) {
console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', '));
canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb));
} else {
cb();
}
});
}
exports.install = install;
|
var canihaz = require('canihaz'),
fs = require('fs'),
p = require('path');
/**
* Install dependency modules that are not yet installed, and needed for executing the tasks.
*
* @param {Array} depNames: an array of dependency module names
* @param {String} dir: application directory where node_modules dir is located
* @param {Function} cb: standard cb(err, result) callback
*/
function install(depNames, dir, cb) {
fs.readdir(p.join(dir, 'node_modules'), function(err, installed) {
var uninstalled = [];
depNames.forEach(function (depName) {
if (installed.indexOf(depName) === -1) {
uninstalled.push(depName);
}
});
if (uninstalled.length > 0) {
console.log('[deps] Installing modules: %s (might take a while)', uninstalled .join(', '));
canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb));
} else {
cb();
}
});
}
exports.install = install;
|
Add nose to tests dependencies
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
'nose',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
|
Mark gateway as transparent redirect
|
<?php
namespace Omnipay\Eway;
use Omnipay\Common\AbstractGateway;
/**
* eWAY Rapid 3.0 Gateway
*/
class RapidGateway extends AbstractGateway
{
public $transparentRedirect = true;
public function getName()
{
return 'eWAY Rapid 3.0';
}
public function getDefaultParameters()
{
return array(
'apiKey' => '',
'password' => '',
'testMode' => false,
);
}
public function getApiKey()
{
return $this->getParameter('apiKey');
}
public function setApiKey($value)
{
return $this->setParameter('apiKey', $value);
}
public function getPassword()
{
return $this->getParameter('password');
}
public function setPassword($value)
{
return $this->setParameter('password', $value);
}
public function purchase(array $parameters = array())
{
return $this->createRequest('\Omnipay\Eway\Message\RapidPurchaseRequest', $parameters);
}
public function completePurchase(array $parameters = array())
{
return $this->createRequest('\Omnipay\Eway\Message\RapidCompletePurchaseRequest', $parameters);
}
}
|
<?php
namespace Omnipay\Eway;
use Omnipay\Common\AbstractGateway;
/**
* eWAY Rapid 3.0 Gateway
*/
class RapidGateway extends AbstractGateway
{
public function getName()
{
return 'eWAY Rapid 3.0';
}
public function getDefaultParameters()
{
return array(
'apiKey' => '',
'password' => '',
'testMode' => false,
);
}
public function getApiKey()
{
return $this->getParameter('apiKey');
}
public function setApiKey($value)
{
return $this->setParameter('apiKey', $value);
}
public function getPassword()
{
return $this->getParameter('password');
}
public function setPassword($value)
{
return $this->setParameter('password', $value);
}
public function purchase(array $parameters = array())
{
return $this->createRequest('\Omnipay\Eway\Message\RapidPurchaseRequest', $parameters);
}
public function completePurchase(array $parameters = array())
{
return $this->createRequest('\Omnipay\Eway\Message\RapidCompletePurchaseRequest', $parameters);
}
}
|
Fix for unit test. Removed empty tests.
|
<?php
/**
* @package elemental
* @subpackage tests
*/
class ElementPageExtensionTests extends FunctionalTest {
protected static $fixture_file = 'elemental/tests/fixtures.yml';
public function setUp() {
parent::setUp();
Page::add_extension('ElementPageExtension');
}
public function testUpdateCmsFields() {
$page = $this->objFromFixture('Page', 'elementaldemo');
$elementarea = $page->getCMSFields()->dataFieldByName('ElementArea');
$this->assertNotNull($elementarea);
$content = $page->getCMSFields()->dataFieldByName('Content');
$this->assertNull($content);
$redirect = $this->objFromFixture('RedirectorPage', 'elementredirectpage');
$elementarea = $redirect->getCMSFields()->dataFieldByName('ElementArea');
$this->assertNull($elementarea);
}
}
|
<?php
/**
* @package elemental
* @subpackage tests
*/
class ElementPageExtensionTests extends FunctionalTest {
protected static $fixture_file = 'elemental/tests/fixtures.yml';
public function setUp() {
parent::setUp();
Page::add_extension('ElementPageExtension');
}
public function testUpdateCmsFields() {
$page = $this->objFromFixture('Page', 'elementaldemo');
$elementarea = $page->getCMSFields()->dataFieldByName('ElementArea');
$this->assertNotNull($elementarea);
$elementarea = $page->getCMSFields()->dataFieldByName('Content');
$this->assertNull($content);
$redirect = $this->objFromFixture('Page', 'elementredirectpage');
$elementarea = $page->getCMSFields()->dataFieldByName('ElementArea');
$this->assertNull($elementarea);
}
public function testDuplicatePageCopiesContent() {
}
public function testPublishingPagePublishesElement() {
}
public function testElementalArea() {
}
}
|
Adjust for TED urls without html suffix
|
<?php
/**
* Ted.php
*
* @package Providers
* @author Michael Pratt <pratt@hablarmierda.net>
* @link http://www.michael-pratt.com/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Embera\Providers;
/**
* The ted.com Provider
* @link http://ted.com
*/
class Ted extends \Embera\Adapters\Service
{
/** inline {@inheritdoc} */
protected $apiUrl = 'http://www.ted.com/talks/oembed.json';
/** inline {@inheritdoc} */
protected function validateUrl()
{
return (preg_match('~ted\.com/talks/(?:\S*)$~i', $this->url));
}
/** inline {@inheritdoc} */
public function fakeResponse()
{
$url = preg_replace('~http(?:.*)ted\.com/~i', 'http://embed.ted.com/$1', $this->url);
return array(
'type' => 'video',
'provider_name' => 'TED',
'provider_url' => 'http://ted.com',
'html' => '<iframe src="' . $url . '" width="{width}" height="{height}" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe',
);
}
}
|
<?php
/**
* Ted.php
*
* @package Providers
* @author Michael Pratt <pratt@hablarmierda.net>
* @link http://www.michael-pratt.com/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Embera\Providers;
/**
* The ted.com Provider
* @link http://ted.com
*/
class Ted extends \Embera\Adapters\Service
{
/** inline {@inheritdoc} */
protected $apiUrl = 'http://www.ted.com/talks/oembed.json';
/** inline {@inheritdoc} */
protected function validateUrl()
{
return (preg_match('~ted\.com/talks/(?:.*)\.html$~i', $this->url));
}
/** inline {@inheritdoc} */
public function fakeResponse()
{
$url = preg_replace('~http(?:.*)ted\.com/~i', 'http://embed.ted.com/$1', $this->url);
return array(
'type' => 'video',
'provider_name' => 'TED',
'provider_url' => 'http://ted.com',
'html' => '<iframe src="' . $url . '" width="{width}" height="{height}" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe',
);
}
}
?>
|
Add windows 10 to browserstack tests
|
const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
},
bs_ie10_windows: {
base: 'BrowserStack',
browser: 'IE',
browser_version : '10',
os: 'Windows',
os_version: '7'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack', 'coverage']
}));
};
|
const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack', 'coverage']
}));
};
|
Update logic in getBaseUrl determining if SSL is being used, to match http hook
|
/**
* Module dependencies
*/
var _ = require ('lodash');
/**
* Calculate the base URL (useful in emails, etc.)
* @return {String} [description]
*/
module.exports = function getBaseurl() {
var sails = this;
var usingSSL = sails.config.ssl === true || (sails.config.ssl && ((sails.config.ssl.key && sails.config.ssl.cert) || sails.config.ssl.pfx));
var host = sails.getHost() || 'localhost';
var port = sails.config.proxyPort || sails.config.port;
var probablyUsingSSL = (port === 443);
// If host doesn't contain `http*` already, include the protocol string.
var protocolString = '';
if (!_.contains(host,'http')) {
protocolString = ((usingSSL || probablyUsingSSL) ? 'https' : 'http') + '://';
}
var portString = (port === 80 || port === 443 ? '' : ':' + port);
var localAppURL = protocolString + host + portString;
return localAppURL;
};
|
/**
* Module dependencies
*/
var _ = require ('lodash');
/**
* Calculate the base URL (useful in emails, etc.)
* @return {String} [description]
*/
module.exports = function getBaseurl() {
var sails = this;
var usingSSL = sails.config.ssl && sails.config.ssl.key && sails.config.ssl.cert;
var host = sails.getHost() || 'localhost';
var port = sails.config.proxyPort || sails.config.port;
var probablyUsingSSL = (port === 443);
// If host doesn't contain `http*` already, include the protocol string.
var protocolString = '';
if (!_.contains(host,'http')) {
protocolString = ((usingSSL || probablyUsingSSL) ? 'https' : 'http') + '://';
}
var portString = (port === 80 || port === 443 ? '' : ':' + port);
var localAppURL = protocolString + host + portString;
return localAppURL;
};
|
Validate date filter for event
|
<?php
namespace App\Http\Controllers;
use App\Event;
use Carbon\Carbon;
use Illuminate\Http\Request;
class EventsController extends Controller
{
public function show(Event $event)
{
return view('events.show', compact('event'));
}
public function index(Request $request)
{
$this->validate($request, ['before' => 'date']);
$before = $request->get('before');
$events = $before
? Event::before(Carbon::parse($before))->get()
: Event::upcoming()->paginate();
return view('events.index', [
'events' => $events,
'earliestDate' => $this->getEarliestDate($events, $before),
]);
}
protected function getEarliestDate($events, $before)
{
if (!$events->count()) {
return $before ? $before : Carbon::now()->format('Y-m-d');
}
return $events->min('start_date')->format('Y-m-d');
}
}
|
<?php
namespace App\Http\Controllers;
use App\Event;
use Carbon\Carbon;
use Illuminate\Http\Request;
class EventsController extends Controller
{
public function show(Event $event)
{
return view('events.show', compact('event'));
}
public function index(Request $request)
{
$before = $request->get('before');
$events = $before
? Event::before(Carbon::parse($before))->get()
: Event::upcoming()->paginate();
return view('events.index', [
'events' => $events,
'earliestDate' => $this->getEarliestDate($events, $before),
]);
}
protected function getEarliestDate($events, $before)
{
if (!$events->count()) {
return $before ? $before : Carbon::now()->format('Y-m-d');
}
return $events->min('start_date')->format('Y-m-d');
}
}
|
Change rollbarLogger & sentryLogger to be conditionally used
|
const winston = require('winston');
const util = require('util');
const transports = [new winston.transports.Console()];
if (process.env.SENTRY_DSN) {
const Raven = require('raven');
const sentryLogger = winston.transports.CustomLogger = function () {
this.name = 'sentryLogger';
this.level = 'error';
};
util.inherits(sentryLogger, winston.Transport);
sentryLogger.prototype.log = function (level, msg, meta, callback) {
Raven.captureException(meta);
callback(null, true);
};
transports.push(new sentryLogger());
}
if (process.env.ROLLBAR_ACCESS_TOKEN) {
const Rollbar = require('rollbar');
const rollbar = new Rollbar(process.env.ROLLBAR_ACCESS_TOKEN);
const rollbarLogger = winston.transports.CustomLogger = function () {
this.name = 'rollbarLogger';
this.level = 'error';
};
util.inherits(rollbarLogger, winston.Transport);
rollbarLogger.prototype.log = function (level, msg, meta, callback) {
rollbar.error(meta.message, meta);
callback(null, true);
};
transports.push(new rollbarLogger());
}
module.exports = new winston.Logger({
transports: transports,
filters: [
(level, msg, meta) => msg.trim(), // shouldn't be necessary, but good-winston is adding \n
],
});
|
const winston = require('winston');
const util = require('util');
const transports = [new winston.transports.Console()];
const Rollbar = require('rollbar');
const rollbar = new Rollbar('ff3ef8cca74244eabffb17dc2365e7bb');
const rollbarLogger = winston.transports.CustomLogger = function () {
this.name = 'rollbarLogger';
this.level = 'error';
};
util.inherits(rollbarLogger, winston.Transport);
rollbarLogger.prototype.log = function (level, msg, meta, callback) {
rollbar.error(meta.message, meta);
callback(null, true);
};
const Raven = require('raven');
const sentryLogger = winston.transports.CustomLogger = function () {
this.name = 'sentryLogger';
this.level = 'error';
};
util.inherits(sentryLogger, winston.Transport);
sentryLogger.prototype.log = function (level, msg, meta, callback) {
Raven.captureMessage(msg);
callback(null, true);
};
transports.push(new sentryLogger());
transports.push(new rollbarLogger());
module.exports = new winston.Logger({
transports: transports,
filters: [
(level, msg, meta) => msg.trim(), // shouldn't be necessary, but good-winston is adding \n
],
});
|
Make sure to install the tap.
|
import os
from setuptools import find_packages, setup
from great import __url__
with open(os.path.join(os.path.dirname(__file__), "README.rst")) as readme:
long_description = readme.read()
classifiers = [
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy"
]
setup(
name="great",
packages=find_packages() + ["twisted.plugins"],
setup_requires=["setuptools_scm"],
use_scm_version=True,
install_requires=[
"Alchimia",
"appdirs",
"attrs",
"filesystems",
"hyperlink",
"Minion",
"pytoml",
"SQLAlchemy",
"Twisted",
"txmusicbrainz",
],
author="Julian Berman",
author_email="Julian@GrayVines.com",
classifiers=classifiers,
description="A ratings aggregator",
license="MIT",
long_description=long_description,
url=__url__,
)
|
import os
from setuptools import find_packages, setup
from great import __url__
with open(os.path.join(os.path.dirname(__file__), "README.rst")) as readme:
long_description = readme.read()
classifiers = [
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy"
]
setup(
name="great",
packages=find_packages(),
setup_requires=["setuptools_scm"],
use_scm_version=True,
install_requires=[
"Alchimia",
"appdirs",
"attrs",
"filesystems",
"hyperlink",
"Minion",
"pytoml",
"SQLAlchemy",
"Twisted",
"txmusicbrainz",
],
author="Julian Berman",
author_email="Julian@GrayVines.com",
classifiers=classifiers,
description="A ratings aggregator",
license="MIT",
long_description=long_description,
url=__url__,
)
|
Use requests built-in .json(), pass verify=False.
|
import requests
import logging
from glanerbeard import show
log = logging.getLogger(__name__)
class Server:
def __init__(self, name, url, apikey):
self.name = name
self.url = url
self.apikey = apikey
def requestJson(self, path):
url = '{url}/api/{apikey}{path}'.format(url=self.url,apikey=self.apikey,path=path)
return requests.get(url, verify=False).json()
def getShows(self):
shows = show.fromJson(self.requestJson('/?cmd=shows'))
for s in shows:
s.addServer(self)
return shows
def __repr__(self):
return 'Server {name} at {url}'.format(name=self.name,url=self.url)
def fromConfig(serverdict, apikeydict):
result = []
for name,url in serverdict.items():
result.append(Server(name, url, apikeydict[name]))
return result
|
import requests
import json
import logging
from glanerbeard import show
log = logging.getLogger(__name__)
class Server:
def __init__(self, name, url, apikey):
self.name = name
self.url = url
self.apikey = apikey
def requestJson(self, path):
url = '{url}/api/{apikey}{path}'.format(url=self.url,apikey=self.apikey,path=path)
response = requests.get(url)
response_str = response.content.decode('utf-8')
result = json.loads(response_str)
return result
def getShows(self):
shows = show.fromJson(self.requestJson('/?cmd=shows'))
for s in shows:
s.addServer(self)
return shows
def __repr__(self):
return 'Server {name} at {url}'.format(name=self.name,url=self.url)
def fromConfig(serverdict, apikeydict):
result = []
for name,url in serverdict.items():
result.append(Server(name, url, apikeydict[name]))
return result
|
Allow int(msg) and float(msg) calls
|
# The main message class that the AuthChannel operate on
class AuthenticatedMessage(object):
def __init__(self, sender, msg, session=None):
self.sender = sender
self.msg = msg
self.session = session
def __str__(self):
return self.msg
def __int__(self):
return int(self.msg)
def __float__(self):
return float(self.msg)
class NutsError(Exception):
""" General NUTS-related failure. """
class NutsConnectionError(NutsError):
""" Something failed in the communication. """
class NutsMessageTooLarge(NutsError):
""" Tried to send message larger than what's supported by the underlying
transport.
"""
class NutsInvalidState(NutsError):
""" Tried to perform an action which is unavilable in the current
state. """
from .channels import (
AuthChannel,
UDPAuthChannel,
)
from .enums import (
ClientState,
ServerState,
Message,
)
|
# The main message class that the AuthChannel operate on
class AuthenticatedMessage(object):
def __init__(self, sender, msg, session=None):
self.sender = sender
self.msg = msg
self.session = session
def __str__(self):
return self.msg
class NutsError(Exception):
""" General NUTS-related failure. """
class NutsConnectionError(NutsError):
""" Something failed in the communication. """
class NutsMessageTooLarge(NutsError):
""" Tried to send message larger than what's supported by the underlying
transport.
"""
class NutsInvalidState(NutsError):
""" Tried to perform an action which is unavilable in the current
state. """
from .channels import (
AuthChannel,
UDPAuthChannel,
)
from .enums import (
ClientState,
ServerState,
Message,
)
|
Fix add to cart JS for compatibility with group buy
|
/**
* Update the price on the product details page in real time when the variant or the quantity are changed.
**/
$(document).ready(function() {
// Product page with variant choice
$("#product-variants input[type='radio']").change(products_update_price_with_variant);
$("#quantity").change(products_update_price_with_variant);
$("#quantity").change();
// Product page with master price only
$(".add-to-cart input.title:not(#quantity):not(#max_quantity)").change(products_update_price_without_variant).change();
});
function products_update_price_with_variant() {
var variant_price = $("#product-variants input[type='radio']:checked").parent().find("span.price").html();
variant_price = variant_price.substr(2, variant_price.length-3);
var quantity = $("#quantity").val();
$("#product-price span.price").html("$"+(parseFloat(variant_price) * parseInt(quantity)).toFixed(2));
}
function products_update_price_without_variant() {
var master_price = $("#product-price span.price").data('master-price');
if(master_price == null) {
// Store off the master price
master_price = $("#product-price span.price").html();
master_price = master_price.substr(1, master_price.length-2);
$("#product-price span.price").data('master-price', master_price);
}
var quantity = $(this).val();
$("#product-price span.price").html("$"+(parseFloat(master_price)*parseInt(quantity)).toFixed(2));
}
|
/**
* Update the price on the product details page in real time when the variant or the quantity are changed.
**/
$(document).ready(function() {
// Product page with variant choice
$("#product-variants input[type='radio']").change(products_update_price_with_variant);
$("#quantity").change(products_update_price_with_variant);
$("#quantity").change();
// Product page with master price only
$(".add-to-cart input.title:not(#quantity)").change(products_update_price_without_variant).change();
});
function products_update_price_with_variant() {
var variant_price = $("#product-variants input[type='radio']:checked").parent().find("span.price").html();
variant_price = variant_price.substr(2, variant_price.length-3);
var quantity = $("#quantity").val();
$("#product-price span.price").html("$"+(parseFloat(variant_price) * parseInt(quantity)).toFixed(2));
}
function products_update_price_without_variant() {
var master_price = $("#product-price span.price").data('master-price');
if(master_price == null) {
// Store off the master price
master_price = $("#product-price span.price").html();
master_price = master_price.substr(1, master_price.length-2);
$("#product-price span.price").data('master-price', master_price);
}
var quantity = $(this).val();
$("#product-price span.price").html("$"+(parseFloat(master_price)*parseInt(quantity)).toFixed(2));
}
|
Add doc string to prescriptSummaryRow
|
/* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import { View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { NumberLabelRow } from './NumberLabelRow';
import { DetailRow } from './DetailRow';
import { SimpleLabel } from './SimpleLabel';
/**
* Simple layout component for primary use within the PrescriptionSummary
* component.
*
* Simply lays out a TransactionItem record showing details related to
* the prescription it is related from.
*
* @param {Object} item A TransactionItem record to display details for.
*/
export const PrescriptionSummaryRow = ({ item }) => {
const { itemName, itemCode, totalQuantity, direction } = item;
const details = [{ label: 'Code', text: itemCode }];
return (
<View style={localStyles.mainContainer}>
<NumberLabelRow text={itemName} number={totalQuantity} />
<View style={localStyles.marginFive} />
<DetailRow details={details} />
<View style={localStyles.marginFive} />
<SimpleLabel label="Directions" text={direction} />
</View>
);
};
const localStyles = StyleSheet.create({
mainContainer: { justifyContent: 'space-evenly', flex: 1, flexDirection: 'column' },
marginFive: { margin: 5 },
});
PrescriptionSummaryRow.propTypes = { item: PropTypes.object.isRequired };
|
/* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import { View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { NumberLabelRow } from './NumberLabelRow';
import { DetailRow } from './DetailRow';
import { SimpleLabel } from './SimpleLabel';
export const PrescriptionSummaryRow = ({ item }) => {
const { itemName, itemCode, totalQuantity, direction } = item;
const details = React.useMemo([{ label: 'Code', text: itemCode }], []);
return (
<View style={localStyles.mainContainer}>
<NumberLabelRow text={itemName} number={totalQuantity} />
<View style={localStyles.marginFive} />
<DetailRow details={details} />
<View style={localStyles.marginFive} />
<SimpleLabel label="Directions" text={direction} />
</View>
);
};
const localStyles = StyleSheet.create({
mainContainer: { justifyContent: 'space-evenly', flex: 1, flexDirection: 'column' },
marginFive: { margin: 5 },
});
PrescriptionSummaryRow.propTypes = { item: PropTypes.object.isRequired };
|
Add classes to run ./configure
|
#
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import os
import shutil
import util
class ManualConfigure:
def doBuild(self, dir):
os.system("cd %s; ./configure %s" % (dir, self.extraflags))
def __init__(self, extraflags=""):
self.extraflags = extraflags
class Configure:
def doBuild(self, dir):
os.system("cd %s; ./configure --prefix=/usr --sysconfdir=/etc %s" % (dir, self.extraflags))
def __init__(self, extraflags=""):
self.extraflags = extraflags
class Make:
def doBuild(self, dir):
os.system("cd %s; make" % dir)
class MakeInstall:
def doInstall(self, dir, root):
os.system("cd %s; make %s=%s install" % (dir, self.rootVar, root))
def __init__(self, rootVar = "DESTDIR"):
self.rootVar = rootVar
class InstallFile:
def doInstall(self, dir, root):
dest = root + self.toFile
util.mkdirChain(os.path.dirname(dest))
shutil.copyfile(self.toFile, dest)
os.chmod(dest, self.mode)
def __init__(self, fromFile, toFile, perms = 0644):
self.toFile = toFile
self.file = fromFile
self.mode = perms
|
#
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import os
import shutil
import util
class Make:
def doBuild(self, dir):
os.system("cd %s; make" % dir)
class MakeInstall:
def doInstall(self, dir, root):
os.system("cd %s; make %s=%s install" % (dir, self.rootVar, root))
def __init__(self, rootVar = "DESTDIR"):
self.rootVar = rootVar
class InstallFile:
def doInstall(self, dir, root):
dest = root + self.toFile
util.mkdirChain(os.path.dirname(dest))
shutil.copyfile(self.toFile, dest)
os.chmod(dest, self.mode)
def __init__(self, fromFile, toFile, perms = 0644):
self.toFile = toFile
self.file = fromFile
self.mode = perms
|
Set an initial selection area of 115 by 115 pixels. Added minimum (115 by 115 pixels) and maximum (300 by 300 pixels) sizes for cropping images
|
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
(function($) {
$(window).load(function(){
var jcrop_api = $.Jcrop('#cropbox',{
onChange: showPreview,
onSelect: showPreview,
setSelect: [ 0, 0, 115, 115 ],
minSize: [115,115],
maxSize: [300,300],
aspectRatio: 1
});
var bounds = jcrop_api.getBounds();
var boundx = bounds[0];
var boundy = bounds[1];
function showPreview(coords)
{
if (parseInt(coords.w) > 0)
{
var rx = 115 / coords.w;
var ry = 115 / coords.h;
$('#preview').css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
$('input[name=x]').val(coords.x);
$('input[name=y]').val(coords.y);
$('input[name=w]').val(coords.w);
$('input[name=h]').val(coords.h);
}
};
});
}(jQuery));
|
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
(function($) {
$(window).load(function(){
var jcrop_api = $.Jcrop('#cropbox',{
onChange: showPreview,
onSelect: showPreview,
aspectRatio: 1
});
var bounds = jcrop_api.getBounds();
var boundx = bounds[0];
var boundy = bounds[1];
function showPreview(coords)
{
if (parseInt(coords.w) > 0)
{
var rx = 115 / coords.w;
var ry = 115 / coords.h;
$('#preview').css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
$('input[name=x]').val(coords.x);
$('input[name=y]').val(coords.y);
$('input[name=w]').val(coords.w);
$('input[name=h]').val(coords.h);
}
};
});
}(jQuery));
|
Add confLoaded event to ArethusaCtrl spec
|
"use strict";
describe('ArethusaCtrl', function() {
beforeEach(module('arethusa'));
it('sets scope values after conf has been loaded', inject(function($controller, $rootScope) {
var scope = $rootScope.$new();
var state = {
init: function() {},
allLoaded: false
};
var mainCtrlInits = {
$scope: scope,
configurator: arethusaMocks.configurator({
configurationFor: function () {
return { template: "template", plugins: {} };
}
}),
state: state,
notifier: arethusaMocks.notifier(),
saver: arethusaMocks.saver(),
history: arethusaMocks.history(),
plugins: arethusaMocks.plugins(),
translator: function() {}
};
var ctrl = $controller('ArethusaCtrl', mainCtrlInits);
expect(scope.state).toBeUndefined();
expect(scope.template).toBeUndefined();
$rootScope.$broadcast('confLoaded');
expect(scope.state).toBe(state);
expect(scope.template).toBe("template");
}));
});
|
"use strict";
describe('ArethusaCtrl', function() {
beforeEach(module('arethusa'));
it('sets scope values', inject(function($controller, $rootScope) {
var scope = $rootScope.$new();
var state = {
init: function() {},
allLoaded: false
};
var mainCtrlInits = {
$scope: scope,
configurator: arethusaMocks.configurator({
configurationFor: function () {
return { template: "template", plugins: {} };
}
}),
state: state,
notifier: arethusaMocks.notifier(),
saver: arethusaMocks.saver(),
history: arethusaMocks.history(),
plugins: arethusaMocks.plugins(),
translator: function() {}
};
var ctrl = $controller('ArethusaCtrl', mainCtrlInits);
expect(scope.state).toBe(state);
expect(scope.template).toBe("template");
}));
});
|
Fix phpdoc for created_at and updated_at properties
|
<?php
namespace Isswp101\Persimmon\Traits;
use Carbon\Carbon;
trait Timestampable
{
/**
* @var string
*/
public $created_at;
/**
* @var string
*/
public $updated_at;
/**
* @return Carbon
*/
public function getCreatedAt()
{
return Carbon::parse($this->created_at);
}
/**
* @param string $created_at
*/
public function setCreatedAt($created_at)
{
$this->created_at = $created_at;
}
/**
* @return Carbon
*/
public function getUpdatedAt()
{
return Carbon::parse($this->updated_at);
}
/**
* @param string $updated_at
*/
public function setUpdatedAt($updated_at)
{
$this->updated_at = $updated_at;
}
protected function fillTimestamp()
{
$utc = Carbon::now('UTC')->toDateTimeString();
$this->setUpdatedAt($utc);
if (!$this->_exist) {
$this->setCreatedAt($utc);
}
}
}
|
<?php
namespace Isswp101\Persimmon\Traits;
use Carbon\Carbon;
trait Timestampable
{
/**
* @var Carbon
*/
public $created_at;
/**
* @var Carbon
*/
public $updated_at;
/**
* @return Carbon
*/
public function getCreatedAt()
{
return Carbon::parse($this->created_at);
}
/**
* @param string $created_at
*/
public function setCreatedAt($created_at)
{
$this->created_at = $created_at;
}
/**
* @return Carbon
*/
public function getUpdatedAt()
{
return Carbon::parse($this->updated_at);
}
/**
* @param string $updated_at
*/
public function setUpdatedAt($updated_at)
{
$this->updated_at = $updated_at;
}
protected function fillTimestamp()
{
$utc = Carbon::now('UTC')->toDateTimeString();
$this->setUpdatedAt($utc);
if (!$this->_exist) {
$this->setCreatedAt($utc);
}
}
}
|
Use a faster blank object creator
http://justin.ridgewell.name/browser-benchmark/blank-object/index.html
Creation is 2-10x faster (depends on the browser), and access is the
same for both existent and non-existent properties.
|
/**
* Copyright 2015 The Incremental DOM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A cached reference to the hasOwnProperty function.
*/
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* A constructor function that will create blank objects.
* @constructor
*/
function Blank() {}
Blank.prototype = Object.create(null);
/**
* Used to prevent property collisions between our "map" and its prototype.
* @param {!Object<string, *>} map The map to check.
* @param {string} property The property to check.
* @return {boolean} Whether map has property.
*/
const has = function(map, property) {
return hasOwnProperty.call(map, property);
};
/**
* Creates an map object without a prototype.
* @return {!Object}
*/
const createMap = function() {
return new Blank();
};
/** */
export {
createMap,
has
};
|
/**
* Copyright 2015 The Incremental DOM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A cached reference to the hasOwnProperty function.
*/
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* A cached reference to the create function.
*/
const create = Object.create;
/**
* Used to prevent property collisions between our "map" and its prototype.
* @param {!Object<string, *>} map The map to check.
* @param {string} property The property to check.
* @return {boolean} Whether map has property.
*/
const has = function(map, property) {
return hasOwnProperty.call(map, property);
};
/**
* Creates an map object without a prototype.
* @return {!Object}
*/
const createMap = function() {
return create(null);
};
/** */
export {
createMap,
has
};
|
Fix race condition on containers retrieval
Signed-off-by: Carlos Pérez-Aradros Herce <a9fe7a739a79c3eddb29e5b128a9f0360449da12@gmail.com>
|
package project
import (
"fmt"
"sync"
"golang.org/x/net/context"
"github.com/docker/libcompose/project/events"
)
// Containers lists the containers for the specified services. Can be filter using
// the Filter struct.
func (p *Project) Containers(ctx context.Context, filter Filter, services ...string) ([]string, error) {
containers := []string{}
var lock sync.Mutex
err := p.forEach(services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
wrapper.Do(nil, events.NoEvent, events.NoEvent, func(service Service) error {
serviceContainers, innerErr := service.Containers(ctx)
if innerErr != nil {
return innerErr
}
for _, container := range serviceContainers {
running := container.IsRunning(ctx)
switch filter.State {
case Running:
if !running {
continue
}
case Stopped:
if running {
continue
}
case AnyState:
// Don't do a thing
default:
// Invalid state filter
return fmt.Errorf("Invalid container filter: %s", filter.State)
}
containerID := container.ID()
lock.Lock()
containers = append(containers, containerID)
lock.Unlock()
}
return nil
})
}), nil)
if err != nil {
return nil, err
}
return containers, nil
}
|
package project
import (
"fmt"
"golang.org/x/net/context"
"github.com/docker/libcompose/project/events"
)
// Containers lists the containers for the specified services. Can be filter using
// the Filter struct.
func (p *Project) Containers(ctx context.Context, filter Filter, services ...string) ([]string, error) {
containers := []string{}
err := p.forEach(services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
wrapper.Do(nil, events.NoEvent, events.NoEvent, func(service Service) error {
serviceContainers, innerErr := service.Containers(ctx)
if innerErr != nil {
return innerErr
}
for _, container := range serviceContainers {
running := container.IsRunning(ctx)
switch filter.State {
case Running:
if !running {
continue
}
case Stopped:
if running {
continue
}
case AnyState:
// Don't do a thing
default:
// Invalid state filter
return fmt.Errorf("Invalid container filter: %s", filter.State)
}
containerID := container.ID()
containers = append(containers, containerID)
}
return nil
})
}), nil)
if err != nil {
return nil, err
}
return containers, nil
}
|
DOC: Fix unicode in citation (again)
|
"""
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@article{Bocklund2019ESPEI,
archivePrefix = {arXiv},
arxivId = {1902.01269},
author = {Bocklund, Brandon and Otis, Richard and Egorov, Aleksei and Obaied, Abdulmonem and Roslyakova, Irina and Liu, Zi-Kui},
doi = {10.1557/mrc.2019.59},
eprint = {1902.01269},
issn = {2159-6859},
journal = {MRS Communications},
month = {jun},
pages = {1--10},
title = {{ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu–Mg}},
year = {2019}
}
"""
|
"""
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1–10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@article{Bocklund2019ESPEI,
archivePrefix = {arXiv},
arxivId = {1902.01269},
author = {Bocklund, Brandon and Otis, Richard and Egorov, Aleksei and Obaied, Abdulmonem and Roslyakova, Irina and Liu, Zi-Kui},
doi = {10.1557/mrc.2019.59},
eprint = {1902.01269},
issn = {2159-6859},
journal = {MRS Communications},
month = {jun},
pages = {1--10},
title = {{ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu–Mg}},
year = {2019}
}
"""
|
Use "Walker" class instead of traverse()
for Ember 1.13 compat
|
/* eslint-env node */
var TEST_SELECTOR_PREFIX = /data-test-.*/;
function TransformTestSelectorParamsToHashPairs() {
this.syntax = null;
}
function isTestSelectorParam(param) {
return param.type === 'PathExpression'
&& TEST_SELECTOR_PREFIX.test(param.original);
}
TransformTestSelectorParamsToHashPairs.prototype.transform = function(ast) {
var b = this.syntax.builders;
var walker = new this.syntax.Walker();
walker.visit(ast, function(node) {
if (node.type === 'MustacheStatement' || node.type === 'BlockStatement') {
var testSelectorParams = [];
var otherParams = [];
node.params.forEach(function(param) {
if (isTestSelectorParam(param)) {
testSelectorParams.push(param);
} else {
otherParams.push(param);
}
});
node.params = otherParams;
testSelectorParams.forEach(function(param) {
var pair = b.pair(param.original, b.boolean(true));
node.hash.pairs.push(pair);
});
}
});
return ast;
};
module.exports = TransformTestSelectorParamsToHashPairs;
|
/* eslint-env node */
var TEST_SELECTOR_PREFIX = /data-test-.*/;
function TransformTestSelectorParamsToHashPairs() {
this.syntax = null;
}
function isTestSelectorParam(param) {
return param.type === 'PathExpression'
&& TEST_SELECTOR_PREFIX.test(param.original);
}
TransformTestSelectorParamsToHashPairs.prototype.transform = function(ast) {
var b = this.syntax.builders;
var traverse = this.syntax.traverse;
traverse(ast, {
MustacheStatement: function(node) {
var testSelectorParams = [];
var otherParams = [];
node.params.forEach(function(param) {
if (isTestSelectorParam(param)) {
testSelectorParams.push(param);
} else {
otherParams.push(param);
};
});
node.params = otherParams;
testSelectorParams.forEach(function(param) {
var pair = b.pair(param.original, b.boolean(true));
node.hash.pairs.push(pair);
});
}
});
return ast;
};
module.exports = TransformTestSelectorParamsToHashPairs;
|
Add default encoding parameter to configure subcommand
|
#!/usr/bin/env python
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.DEFAULT_ENCODING,
prompt_text="Default encoding to load files",
initial_value="utf-8"),
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value=""),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
|
#!/usr/bin/env python
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value="",
),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
|
Load translator module with a relative path
|
var nroonga = require('nroonga');
var translator = require('./translator');
var Deferred = require('jsdeferred').Deferred;
function Processor(options) {
this.databasePath = options.databasePath;
this.domain = options.domain;
this.initialize();
}
Processor.prototype = {
initialize: function() {
this.database = new nroonga.Database(this.databasePath);
this.translator = new translator.Translator(this.domain);
},
process: function(batchs) {
var commandSets = this.translator.translate(batchs);
var self = this;
return Deferred.loop(commandSets.length, function(commandSet) {
return self.sendOneCommandSet(commandSet);
});
},
sendOneCommandSet: function(commandSet) {
var deferred = new Deferred();
var callback = function(error, data) {
if (error)
deferred.fail(error);
else
deferred.call(data);
};
if (commandSet.options)
this.database.command(commandSet.command, commandSet.options, callback);
else
this.database.command(commandSet.command, callback);
return deferred;
}
};
exports.Processor = Processor;
|
var nroonga = require('nroonga');
var translator = require('translator');
var Deferred = require('jsdeferred').Deferred;
function Processor(options) {
this.databasePath = options.databasePath;
this.domain = options.domain;
this.initialize();
}
Processor.prototype = {
initialize: function() {
this.database = new nroonga.Database(this.databasePath);
this.translator = new translator.Translator(this.domain);
},
process: function(batchs) {
var commandSets = this.translator.translate(batchs);
var self = this;
return Deferred.loop(commandSets.length, function(commandSet) {
return self.sendOneCommandSet(commandSet);
});
},
sendOneCommandSet: function(commandSet) {
var deferred = new Deferred();
var callback = function(error, data) {
if (error)
deferred.fail(error);
else
deferred.call(data);
};
if (commandSet.options)
this.database.command(commandSet.command, commandSet.options, callback);
else
this.database.command(commandSet.command, callback);
return deferred;
}
};
exports.Processor = Processor;
|
Update test to new package structure
|
import unittest
from datetime import datetime, timedelta
import sys
sys.path.append(r"../..")
from daymetpy import daymet_timeseries
class TimeseriesTest(unittest.TestCase):
def setUp(self):
pass
def test_ornl_df(self):
ornl_lat, ornl_long = 35.9313167, -84.3104124
df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012)
self.assertTrue(df.year.count() == 365)
self.assertTrue("tmax" in df.columns)
self.assertTrue("tmin" in df.columns)
self.assertTrue("prcp" in df.columns)
def test_out_of_bounds(self):
london_lat, london_long = 51.5072, 0.1275
with self.assertRaises(NameError):
df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012)
if __name__ == '__main__':
unittest.main()
|
import unittest
from datetime import datetime, timedelta
import sys
sys.path.append(r"..")
from daymetpy import download_Daymet
class TimeseriesTest(unittest.TestCase):
def setUp(self):
pass
def test_ornl_df(self):
ornl_lat, ornl_long = 35.9313167, -84.3104124
df = download_Daymet(lon=ornl_long, lat=ornl_lat, start_yr=2012, end_yr=2013)
self.assertTrue(df.year.count() == 365)
self.assertTrue("tmax" in df.columns)
self.assertTrue("tmin" in df.columns)
self.assertTrue("prcp" in df.columns)
def test_out_of_bounds(self):
london_lat, london_long = 51.5072, 0.1275
with self.assertRaises(NameError):
df = download_Daymet(lon=london_long, lat=london_lat, start_yr=2012, end_yr=2013)
if __name__ == '__main__':
unittest.main()
|
Handle REG_MULTI_SZ.toString when there the value is null (i.e., raw data is a single \0, not a double \0\0).
|
// Copyright (C) 2011 jOVAL.org. All rights reserved.
// This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt
package org.joval.os.windows.registry;
import org.joval.intf.windows.registry.IKey;
import org.joval.intf.windows.registry.IMultiStringValue;
/**
* Representation of a Windows registry multi-string value.
*
* @author David A. Solin
* @version %I% %G%
*/
public class MultiStringValue extends Value implements IMultiStringValue {
String[] data;
public MultiStringValue(IKey parent, String name, String[] data) {
type = Type.REG_MULTI_SZ;
this.parent = parent;
this.name = name;
this.data = data;
}
public String[] getData() {
return data;
}
public String toString() {
StringBuffer sb = new StringBuffer("MultiStringValue [Name=\"").append(name).append("\" Value=");
if (data == null) {
sb.append("null");
} else {
sb.append("{");
for (int i=0; i < data.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append("\"").append(data[i]).append("\"");
}
sb.append("}");
}
sb.append("]");
return sb.toString();
}
}
|
// Copyright (C) 2011 jOVAL.org. All rights reserved.
// This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt
package org.joval.os.windows.registry;
import org.joval.intf.windows.registry.IKey;
import org.joval.intf.windows.registry.IMultiStringValue;
/**
* Representation of a Windows registry multi-string value.
*
* @author David A. Solin
* @version %I% %G%
*/
public class MultiStringValue extends Value implements IMultiStringValue {
String[] data;
public MultiStringValue(IKey parent, String name, String[] data) {
type = Type.REG_MULTI_SZ;
this.parent = parent;
this.name = name;
this.data = data;
}
public String[] getData() {
return data;
}
public String toString() {
StringBuffer sb = new StringBuffer("MultiStringValue [Name=\"").append(name).append("\" Value={");
for (int i=0; i < data.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append("\"").append(data[i]).append("\"");
}
sb.append("}]");
return sb.toString();
}
}
|
Add user role restriction to the app abstract state
|
'use strict';
angular.module('module.core').config(function($stateProvider, USER_ROLES) {
$stateProvider
.state('app', {
abstract: true,
url: '/app',
templateUrl: 'modules/core/views/layouts/app.html',
controller: 'AppCtrl as app',
data: {
authorizedRoles: [USER_ROLES.registered]
}
})
.state('page', {
abstract: true,
url: '/page',
templateUrl: 'modules/core/views/layouts/page.html',
controller: 'PageCtrl as page'
})
.state('page.home', {
url: '/home',
templateUrl: 'modules/core/views/home.html'
})
.state('page.about', {
url: '/about',
templateUrl: 'modules/core/views/about.html'
})
.state('page.architecture', {
url: '/architecture',
templateUrl: 'modules/core/views/architecture.html'
})
});
|
'use strict';
angular.module('module.core').config(function($stateProvider, USER_ROLES) {
$stateProvider
.state('app', {
abstract: true,
url: '/app',
templateUrl: 'modules/core/views/layouts/app.html',
controller: 'AppCtrl as app',
})
.state('page', {
abstract: true,
url: '/page',
templateUrl: 'modules/core/views/layouts/page.html',
controller: 'PageCtrl as page'
})
.state('page.home', {
url: '/home',
templateUrl: 'modules/core/views/home.html'
})
.state('page.about', {
url: '/about',
templateUrl: 'modules/core/views/about.html'
})
.state('page.architecture', {
url: '/architecture',
templateUrl: 'modules/core/views/architecture.html'
})
});
|
Convert two .set() calls into one .update()
|
"use strict";
var db = require("./firebase");
// Ensure the updated timestamp is always accurate-ish
module.exports = function(ref) {
ref.on("child_changed", function(snap) {
var key = snap.key(),
auth;
// Avoid looping forever
if(key === "updated_at" || key === "updated_by") {
return;
}
auth = db.getAuth();
// Clean up any old updated timestamps floating around
ref.child("updated").remove();
ref.update({
updated_at : db.TIMESTAMP,
updated_by : auth.uid
});
});
};
|
"use strict";
var db = require("./firebase");
// Ensure the updated timestamp is always accurate-ish
module.exports = function(ref) {
ref.on("child_changed", function(snap) {
var key = snap.key(),
auth;
// Avoid looping forever
if(key === "updated_at" || key === "updated_by") {
return;
}
auth = db.getAuth();
// Clean up any old updated timestamps floating around
ref.child("updated").remove();
ref.child("updated_at").set(db.TIMESTAMP);
ref.child("updated_by").set(auth.uid);
});
};
|
Make sure we can search names with '
|
import re
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import Count, F
from people.models import Person
def search_person_by_name(name, synonym=True):
name = name.lower()
name = re.sub(r"[^a-z ]", " ", name)
name = " ".join(name.strip().split())
and_name = " & ".join(name.split(" "))
or_name = " | ".join(name.split(" "))
name = f"({and_name}) | ({or_name})"
query = SearchQuery(name, search_type="raw", config="english")
search_args = {}
if synonym:
search_args["name_search_vector__synonym"] = query
else:
search_args["name_search_vector"] = query
qs = (
Person.objects.annotate(membership_count=Count("memberships"))
.filter(**search_args)
.annotate(rank=SearchRank(F("name_search_vector"), query))
.order_by("-rank", "membership_count")
.defer("biography", "versions")
)
return qs
|
import re
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import Count, F
from people.models import Person
def search_person_by_name(name, synonym=True):
name = name.lower()
name = re.sub(r"[^a-z ]", "", name)
name = " ".join(name.strip().split())
and_name = " & ".join(name.split(" "))
or_name = " | ".join(name.split(" "))
name = f"({and_name}) | ({or_name})"
query = SearchQuery(name, search_type="raw", config="english")
search_args = {}
if synonym:
search_args["name_search_vector__synonym"] = query
else:
search_args["name_search_vector"] = query
qs = (
Person.objects.annotate(membership_count=Count("memberships"))
.filter(**search_args)
.annotate(rank=SearchRank(F("name_search_vector"), query))
.order_by("-rank", "membership_count")
.defer("biography", "versions")
)
return qs
|
Disable Firefox specs because the runner consistently crashes
|
// Karma configuration
// Generated on Fri Dec 05 2014 16:49:29 GMT-0500 (EST)
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jspm', 'jasmine'],
jspm: {
loadFiles: ['test/helpers.js', 'src/**/*.js', 'test/**/*.js']
},
files: [
'src/**/*.html', 'src/**/*.css', 'test/**/*.html'
],
exclude: [],
preprocessors: {
'test/**/*.js': ['babel'],
'src/**/*.js': ['babel']
},
babelPreprocessor: {
options: {
sourceMap: 'inline',
presets: [ 'stage-1'],
plugins: [
'transform-decorators-legacy',
]
}
},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
// logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: [
'Chrome',
'Safari',
// 'Firefox'
],
singleRun: false
});
};
|
// Karma configuration
// Generated on Fri Dec 05 2014 16:49:29 GMT-0500 (EST)
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jspm', 'jasmine'],
jspm: {
loadFiles: ['test/helpers.js', 'src/**/*.js', 'test/**/*.js']
},
files: [
'src/**/*.html', 'src/**/*.css', 'test/**/*.html'
],
exclude: [],
preprocessors: {
'test/**/*.js': ['babel'],
'src/**/*.js': ['babel']
},
babelPreprocessor: {
options: {
sourceMap: 'inline',
presets: [ 'stage-1'],
plugins: [
'transform-decorators-legacy',
]
}
},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
// logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: [
'Chrome',
'Safari',
'Firefox'
],
singleRun: false
});
};
|
Add test for invalid bearer token
|
from oauth2_consumer.middleware import AuthenticationMiddleware
from .test_cases import MiddlewareTestCase
class TestMiddleware(MiddlewareTestCase):
def test_no_token(self):
request = self.factory.get("/")
AuthenticationMiddleware().process_request(request)
self.assertEqual(request.auth_type, None)
self.assertFalse(hasattr(request, "acess_token"))
self.assertFalse(hasattr(request, "user"))
def test_invalid_handler(self):
request = self.factory.get("/")
request.META["HTTP_AUTHORIZATION"] = "type token"
AuthenticationMiddleware().process_request(request)
self.assertEqual(request.auth_type, "type")
def test_invalid_bearer_token(self):
request = self.factory.get("/")
request.META["HTTP_AUTHORIZATION"] = "bearer invalid"
AuthenticationMiddleware().process_request(request)
self.assertEqual(request.auth_type, "bearer")
|
from oauth2_consumer.middleware import AuthenticationMiddleware
from .test_cases import MiddlewareTestCase
class TestMiddleware(MiddlewareTestCase):
def test_no_token(self):
request = self.factory.get("/")
AuthenticationMiddleware().process_request(request)
self.assertEqual(request.auth_type, None)
self.assertFalse(hasattr(request, "acess_token"))
self.assertFalse(hasattr(request, "user"))
def test_invalid_handler(self):
request = self.factory.get("/")
request.META["HTTP_AUTHORIZATION"] = "type token"
AuthenticationMiddleware().process_request(request)
print request
self.assertEqual(request.auth_type, "type")
|
Fix not waiting for paper key approval
|
/* @flow */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import HiddenString from '../../../util/hidden-string'
import {sawPaperKey} from '../../../actions/signup'
import Render from './index.render'
class Success extends Component {
render () {
return (
<Render
title={this.props.title}
paperkey={this.props.paperkey}
onFinish={this.props.onFinish}
onBack={this.props.onBack}
/>
)
}
}
Success.propTypes = {
paperkey: React.PropTypes.instanceOf(HiddenString).isRequired,
onFinish: React.PropTypes.func.isRequired
}
export default connect(
state => ({paperkey: state.signup.paperkey}),
dispatch => ({
onFinish: () => dispatch(sawPaperKey()),
onBack: () => {}
})
)(Success)
|
/* @flow */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import HiddenString from '../../../util/hidden-string'
import {sawPaperKey} from '../../../actions/signup'
import Render from './index.render'
class Success extends Component {
render () {
return (
<Render
title={this.props.title}
paperkey={this.props.paperkey}
onFinish={this.props.onFinish}
onBack={this.props.onBack}
/>
)
}
}
Success.propTypes = {
paperkey: React.PropTypes.instanceOf(HiddenString).isRequired,
onFinish: React.PropTypes.func.isRequired
}
export default connect(
state => ({paperkey: state.signup.paperkey}),
dispatch => ({
onFinish: dispatch(sawPaperKey()),
onBack: () => {}
})
)(Success)
|
Fix issue where pandas.Index doesn't have str method
(Index.str was only introduced in pandas 0.19.2)
|
import pandas as pd
def load_datadict(filepath, trim_index=True, trim_all=False):
df = pd.read_csv(filepath, index_col=0)
if trim_index:
df.index = df.index.to_series().str.strip()
if trim_all:
df = df.applymap(lambda x: x.strip() if type(x) is str else x)
return df
def insert_rows_at(main_df, index_name, inserted_df, insert_before=False):
# Not checking if index exists because that will be apparent from error
# NOTE: This will not work with duplicate indices
pre_df = main_df.loc[:index_name]
post_df = main_df.loc[index_name:]
# Both pre_ and post_ contain the value at index_name, so one needs to
# drop it
if not insert_before:
pre_df = pre_df.drop(index_name)
else:
post_df = post_df.drop(index_name)
return pd.concat([pre_df, inserted_df, post_df],
axis=0)
|
import pandas as pd
def load_datadict(filepath, trim_index=True, trim_all=False):
df = pd.read_csv(filepath, index_col=0)
if trim_index:
df.index = df.index.str.strip()
if trim_all:
df = df.applymap(lambda x: x.strip() if type(x) is str else x)
return df
def insert_rows_at(main_df, index_name, inserted_df, insert_before=False):
# Not checking if index exists because that will be apparent from error
# NOTE: This will not work with duplicate indices
pre_df = main_df.loc[:index_name]
post_df = main_df.loc[index_name:]
# Both pre_ and post_ contain the value at index_name, so one needs to
# drop it
if not insert_before:
pre_df = pre_df.drop(index_name)
else:
post_df = post_df.drop(index_name)
return pd.concat([pre_df, inserted_df, post_df],
axis=0)
|
Add file sorting in the example script
|
#!/bin/python
# installation:
# pip install pytz pyuploadcare~=2.1.0
import pytz
from datetime import timedelta, datetime
import time
from pyuploadcare import conf
from pyuploadcare.api_resources import FileList, FilesStorage
MAX_LIFETIME = 30 # days
conf.pub_key = 'demopublickey'
conf.secret = 'demoprivatekey'
dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME)
if __name__ == '__main__':
print 'Selecting files to be deleted...'
uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff,
ordering='-datetime_uploaded',
stored=True,
request_limit=500)]
print 'Batch delete of selected files'
ts1 = time.time()
fs = FilesStorage(uuid_list)
fs.delete()
ts2 = time.time()
print 'Operation completed in %f seconds' % (ts2 - ts1)
|
#!/bin/python
# installation:
# pip install pytz pyuploadcare~=2.1.0
import pytz
from datetime import timedelta, datetime
import time
from pyuploadcare import conf
from pyuploadcare.api_resources import FileList, FilesStorage
MAX_LIFETIME = 30 # days
conf.pub_key = 'demopublickey'
conf.secret = 'demoprivatekey'
dt_cutoff = datetime.now(pytz.utc) - timedelta(days=MAX_LIFETIME)
if __name__ == '__main__':
print 'Selecting files to be deleted...'
uuid_list = [f.uuid for f in FileList(starting_point=dt_cutoff,
stored=True,
request_limit=500)]
print 'Batch delete of selected files'
ts1 = time.time()
fs = FilesStorage(uuid_list)
fs.delete()
ts2 = time.time()
print 'Operation completed in %f seconds' % (ts2 - ts1)
|
ui: Use ViewPlaceholder instead of custom code
Instead of using a custom View with custom styles use the
ViewPlaceholder component.
|
/* @flow */
import React, { PureComponent } from 'react';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ViewPlaceholder, ZulipButton } from '../common';
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<ViewPlaceholder height={20} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
|
/* @flow */
import React, { PureComponent } from 'react';
import { View, StyleSheet } from 'react-native';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ZulipButton } from '../common';
const componentStyles = StyleSheet.create({
divider: {
height: 20,
},
});
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<View style={componentStyles.divider} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
|
Send router back to DI
The routes set here are not actually being set, it just coincidentally works with a single demo module due to the "defaultNamespace" set in services.php
|
<?php
$router = $di->get("router");
foreach ($application->getModules() as $key => $module) {
$namespace = str_replace('Module','Controllers', $module["className"]);
$router->add('/'.$key.'/:params', array(
'namespace' => $namespace,
'module' => $key,
'controller' => 'index',
'action' => 'index',
'params' => 1
))->setName($key);
$router->add('/'.$key.'/:controller/:params', array(
'namespace' => $namespace,
'module' => $key,
'controller' => 1,
'action' => 'index',
'params' => 2
));
$router->add('/'.$key.'/:controller/:action/:params', array(
'namespace' => $namespace,
'module' => $key,
'controller' => 1,
'action' => 2,
'params' => 3
));
}
$di->set("router", $router);
|
<?php
$router = $di->get("router");
foreach ($application->getModules() as $key => $module) {
$namespace = str_replace('Module','Controllers', $module["className"]);
$router->add('/'.$key.'/:params', array(
'namespace' => $namespace,
'module' => $key,
'controller' => 'index',
'action' => 'index',
'params' => 1
))->setName($key);
$router->add('/'.$key.'/:controller/:params', array(
'namespace' => $namespace,
'module' => $key,
'controller' => 1,
'action' => 'index',
'params' => 2
));
$router->add('/'.$key.'/:controller/:action/:params', array(
'namespace' => $namespace,
'module' => $key,
'controller' => 1,
'action' => 2,
'params' => 3
));
}
|
Update logdir after config was moved
|
<?php
namespace Redports\Master;
/**
* Configuration class to store various static settings.
*
* @author Bernhard Froehlich <decke@bluelife.at>
* @copyright 2015 Bernhard Froehlich
* @license BSD License (2 Clause)
*
* @link https://freebsd.github.io/redports/
*/
class Config
{
protected static $settings = array(
'debug' => true,
'datasource' => '/var/run/redis/redis.sock',
'logdir' => __DIR__.'/../../../logs',
'https_only' => true,
'ircbridgetoken' => '',
'userconfig' => array(
'jails' => array('10.1-RELEASE-amd64', '10.1-RELEASE-i386'),
'notify' => 'commit', /* commit, email, none */
),
);
public static function get($property)
{
if (isset(self::$settings[$property])) {
return self::$settings[$property];
}
return false;
}
public static function getDatabaseHandle()
{
if (isset($GLOBALS['redis'])) {
return $GLOBALS['redis'];
}
return false;
}
}
|
<?php
namespace Redports\Master;
/**
* Configuration class to store various static settings.
*
* @author Bernhard Froehlich <decke@bluelife.at>
* @copyright 2015 Bernhard Froehlich
* @license BSD License (2 Clause)
*
* @link https://freebsd.github.io/redports/
*/
class Config
{
protected static $settings = array(
'debug' => true,
'datasource' => '/var/run/redis/redis.sock',
'logdir' => __DIR__.'/../logs',
'https_only' => true,
'ircbridgetoken' => '',
'userconfig' => array(
'jails' => array('10.1-RELEASE-amd64', '10.1-RELEASE-i386'),
'notify' => 'commit', /* commit, email, none */
),
);
public static function get($property)
{
if (isset(self::$settings[$property])) {
return self::$settings[$property];
}
return false;
}
public static function getDatabaseHandle()
{
if (isset($GLOBALS['redis'])) {
return $GLOBALS['redis'];
}
return false;
}
}
|
Add ssl random bytes generator
|
<?php
/**
* Class Csrf
*
* @package Faulancer\Security
* @author Florian Knapp <office@florianknapp.de>
*/
namespace Faulancer\Security;
use Faulancer\Session\SessionManager;
/**
* Class Csrf
*/
class Csrf
{
/**
* Generates a token and save it to session
* @return string
*/
public static function getToken()
{
$token = bin2hex(openssl_random_pseudo_bytes(32));
self::saveToSession($token);
return $token;
}
/**
* Check if token is valid
* @return boolean
*/
public static function isValid()
{
return isset($_POST['csrf']) && $_POST['csrf'] === SessionManager::instance()->getFlashbag('csrf');
}
/**
* Saves token into session
* @param $token
*/
private static function saveToSession($token)
{
SessionManager::instance()->setFlashbag('csrf', $token);
}
}
|
<?php
/**
* Class Csrf
*
* @package Faulancer\Security
* @author Florian Knapp <office@florianknapp.de>
*/
namespace Faulancer\Security;
use Faulancer\Session\SessionManager;
/**
* Class Csrf
*/
class Csrf
{
/**
* Generates a token and save it to session
* @return string
*/
public static function getToken()
{
$token = bin2hex(random_bytes(32));
self::saveToSession($token);
return $token;
}
/**
* Check if token is valid
* @return boolean
*/
public static function isValid()
{
return isset($_POST['csrf']) && $_POST['csrf'] === SessionManager::instance()->getFlashbag('csrf');
}
/**
* Saves token into session
* @param $token
*/
private static function saveToSession($token)
{
SessionManager::instance()->setFlashbag('csrf', $token);
}
}
|
Set `canRetransform` flag to `false` in instrumentation.
We do not need to retransform classes once they are loaded.
All instrumentation byte-code is pushed at loading time.
This fixes a problem with Java 7 that was failing to add
a transformer because we did not declare retransformation
capability in `MANIFEST.MF` file in Java agent jar.
Java 6 allowed to add transformer due to a bug.
|
/* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
* by using ASM library for byte-code manipulation.
*/
public class ProfilingAgent {
public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
// NOTE: we are adding transformer that won't be applied to classes that are already loaded
// This should be ok because premain should be executed before main is executed so Scala library
// and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
// not depend on Scala library. In case our assumptions are wrong we can always insert call to
// inst.retransformClasses.
inst.addTransformer(new ASMTransformer(), false);
}
}
|
/* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
* by using ASM library for byte-code manipulation.
*/
public class ProfilingAgent {
public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
// NOTE: we are adding transformer that won't be applied to classes that are already loaded
// This should be ok because premain should be executed before main is executed so Scala library
// and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
// not depend on Scala library. In case our assumptions are wrong we can always insert call to
// inst.retransformClasses.
inst.addTransformer(new ASMTransformer(), true);
}
}
|
Use Optional and supplier to match the servlet filter
|
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import org.slf4j.MDC;
import java.util.UUID;
public class RequestTrackerClientFilter extends ClientFilter {
private static final Supplier<String> ID_SUPPLIER = new Supplier<String>() {
@Override
public String get() {
return UUID.randomUUID().toString();
}
};
@Override
public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException {
// As getNext() is final in ClientFilter and cannot be stubbed in test classes, all work is
// performed in the protected doWork method which can be unit tested.
// That the filter hands off to the next in the chain can only be tested in an integration test
return getNext().handle(doWork(clientRequest));
}
protected ClientRequest doWork(ClientRequest clientRequest) {
Optional<String> requestId = Optional.fromNullable(MDC.get("Request-Tracker"));
clientRequest.getHeaders().add("X-Request-Tracker", requestId.or(ID_SUPPLIER));
return clientRequest;
}
}
|
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import org.slf4j.MDC;
import java.util.UUID;
public class RequestTrackerClientFilter extends ClientFilter {
@Override
public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException {
// As getNext() is final in ClientFilter and cannot be stubbed in test classes, all work is
// performed in the protected doWork method which can be unit tested.
// That the filter hands off to the next in the chain can only be tested in an integration test
return getNext().handle(doWork(clientRequest));
}
protected ClientRequest doWork(ClientRequest clientRequest) {
String logId= MDC.get("Request-Tracker");
if(logId == null) {
logId = UUID.randomUUID().toString();
}
clientRequest.getHeaders().add("X-Request-Tracker", logId);
return clientRequest;
}
}
|
Fix jshint and missing semicolon
|
import Ember from 'ember';
import {module, test} from 'qunit';
import startApp from 'unicodeparty/tests/helpers/start-app';
let application;
function getChars() {
return new Set(Ember.$('.emoji-char').toArray().map(el => el.innerText));
}
module('Acceptance | search', {
beforeEach() {
application = startApp();
},
afterEach() {
Ember.run(application, 'destroy');
},
});
test('search for horse emoji', function (assert) {
visit('/');
andThen(() => {
assert.equal(currentURL(), '/');
});
fillIn('input', 'horse');
andThen(() => {
let characters = getChars();
assert.equal(Ember.$('.emoji-tile').length, 4, '4 horse emoji');
assert.ok(!characters.has('🎈'), 'balloon emoji not found');
assert.ok(characters.has('🐴'), 'horse emoji found');
});
});
test('search for flag emoji (HU)', function (assert) {
visit('/');
fillIn('input', 'hungary');
andThen(() => {
assert.equal(Ember.$('.emoji-name').length, 1, '1 Hungarian flag found');
assert.equal(Ember.$('.emoji-name').text(), 'Hungary',
'Emoji has correct name');
});
});
|
import Ember from 'ember';
import {module, test} from 'qunit';
import startApp from 'unicodeparty/tests/helpers/start-app';
let application;
function getChars() {
return new Set(Ember.$('.emoji-char').toArray().map(el => el.innerText));
}
module('Acceptance | search', {
beforeEach() {
application = startApp();
},
afterEach() {
Ember.run(application, 'destroy');
},
});
test('search for horse emoji', function (assert) {
visit('/');
andThen(() => {
assert.equal(currentURL(), '/');
});
fillIn('input', 'horse');
andThen(() => {
let characters = getChars();
assert.equal(Ember.$('.emoji-tile').length, 4, '4 horse emoji');
assert.ok(!characters.has('🎈'), 'balloon emoji not found');
assert.ok(characters.has('🐴'), 'horse emoji found');
});
});
test('search for flag emoji (HU)', function (assert) {
visit('/');
fillIn('input', 'hungary');
andThen(() => {
assert.equal(Ember.$('.emoji-name').length, 1, '1 Hungarian flag found');
assert.equal(Ember.$('.emoji-name').text(), 'Hungary', 'Emoji has correct name')
});
});
|
Send plugin_activated event on activation.
|
/**
* Activation component.
*
* This JavaScript loads on every admin page. Reserved for later.
*
* 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.
*/
/**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
import { render } from '@wordpress/element';
import { doAction } from '@wordpress/hooks';
/**
* External dependencies
*/
import { loadTranslations, sendAnalyticsTrackingEvent } from 'GoogleUtil';
import 'GoogleComponents/notifications';
/**
* Internal dependencies
*/
import { ActivationApp } from './components/activation/activation-app';
domReady( () => {
const renderTarget = document.getElementById( 'js-googlesitekit-activation' );
if ( renderTarget ) {
loadTranslations();
sendAnalyticsTrackingEvent( 'plugin_setup', 'plugin_activated' );
render( <ActivationApp />, renderTarget );
/**
* Action triggered when the ActivationApp is loaded.
*/
doAction( 'googlesitekit.moduleLoaded', 'Activation' );
}
} );
|
/**
* Activation component.
*
* This JavaScript loads on every admin page. Reserved for later.
*
* 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.
*/
/**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
import { render } from '@wordpress/element';
import { doAction } from '@wordpress/hooks';
/**
* External dependencies
*/
import { loadTranslations } from 'GoogleUtil';
import 'GoogleComponents/notifications';
/**
* Internal dependencies
*/
import { ActivationApp } from './components/activation/activation-app';
domReady( () => {
const renderTarget = document.getElementById( 'js-googlesitekit-activation' );
if ( renderTarget ) {
loadTranslations();
render( <ActivationApp />, renderTarget );
/**
* Action triggered when the ActivationApp is loaded.
*/
doAction( 'googlesitekit.moduleLoaded', 'Activation' );
}
} );
|
Bump version number to 0.5
|
from setuptools import setup
with open('README.rst') as f:
long_desc = f.read()
setup(
name='ttrss-python',
version='0.5',
description='A client library for the Tiny Tiny RSS web API',
long_description=long_desc,
url='https://github.com/Vassius/ttrss-python',
author='Markus Wiik',
author_email='vassius@gmail.com',
packages=['ttrss'],
package_data={'': ['README.rst']},
include_package_data=True,
install_requires=['requests>=1.1.0'],
provides=['ttrss'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
|
from setuptools import setup
with open('README.rst') as f:
long_desc = f.read()
setup(
name='ttrss-python',
version='0.4',
description='A client library for the Tiny Tiny RSS web API',
long_description=long_desc,
url='https://github.com/Vassius/ttrss-python',
author='Markus Wiik',
author_email='vassius@gmail.com',
packages=['ttrss'],
package_data={'': ['README.rst']},
include_package_data=True,
install_requires=['requests>=1.1.0'],
provides=['ttrss'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Fix not movable map after drag zoom (web)
|
export default function dragZoom(map) {
const $map = map._container;
let isDoubleTap = false;
let isDragging = false;
let startZoom = 0;
let startY = 0;
$map.addEventListener('touchstart', (e) => {
// Cancel drag zoom with multiple fingers.
if (e.touches.length > 1) return (isDragging = false);
// Check for double tap.
if (!isDoubleTap) {
isDoubleTap = true;
setTimeout(() => {
isDoubleTap = false;
}, 300);
return;
}
map.dragging.disable();
startZoom = map.getZoom();
startY = e.touches[0].pageY;
isDragging = true;
});
$map.addEventListener('touchend', (e) => {
isDragging = false;
map.dragging.enable();
});
$map.addEventListener('touchmove', (e) => {
if (isDragging) map.setZoom(startZoom - (startY - e.touches[0].pageY) / 80);
});
}
|
export default function dragZoom(map) {
const $map = map._container;
let isDoubleTap = false;
let isDragging = false;
let startZoom = 0;
let startY = 0;
$map.addEventListener('touchstart', (e) => {
// Cancel drag zoom with multiple fingers.
if (e.touches.length > 1) return (isDragging = false);
// Check for double tap.
if (!isDoubleTap) {
isDoubleTap = true;
setTimeout(() => {
isDoubleTap = false;
}, 300);
return;
}
map.dragging.disable();
startZoom = map.getZoom();
startY = e.touches[0].pageY;
isDragging = true;
});
$map.addEventListener('touchend', (e) => {
isDragging = false;
});
$map.addEventListener('touchmove', (e) => {
if (isDragging) map.setZoom(startZoom - (startY - e.touches[0].pageY) / 80);
});
}
|
Create a global variable to select each main component in the DOM
|
/*-----------------------------------------------------------------
Modular - JS Extension
Made by @esr360
http://github.com/esr360/Modular/
-----------------------------------------------------------------*/
//-----------------------------------------------------------------
// Convert CSS config to JS
//-----------------------------------------------------------------
// Get styles' configuration
var stylesConfigJSON = document.getElementById("stylesConfigJSON");
// Remove quotes from computed JSON
function removeQuotes(json) {
json = json.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, '');
return json;
}
// Convert computed JSON to camelCase
function camelCase(json) {
json = json.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
return json;
}
// Convert the config to JS
function getStylesConfig(camelCase) {
var style = null;
style = window.getComputedStyle(stylesConfigJSON, '::before');
style = style.content;
style = removeQuotes(style);
if(camelCase) {
style = camelCase(style);
}
return JSON.parse(style);
}
// Store configuartion data in a variable
var module = getStylesConfig();
// CamelCase the config
var moduleCC = getStylesConfig(camelCase);
// Create a global variable to select each main component in the DOM
var componentIndex = 0;
$.each(module, function(component) {
var componentCC = moduleCC[Object.keys(moduleCC)[componentIndex]]['name'];
window[componentCC] = '.' + component + ', [class*="' + component + '-"]';
componentIndex++;
});
|
/*-----------------------------------------------------------------
Modular - JS Extension
Made by @esr360
http://github.com/esr360/Modular/
-----------------------------------------------------------------*/
//-----------------------------------------------------------------
// Convert CSS config to JS
//-----------------------------------------------------------------
// Get styles' configuration
var stylesConfigJSON = document.getElementById("stylesConfigJSON");
// Remove quotes from computed JSON
function removeQuotes(json) {
json = json.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, '');
return json;
}
// Convert computed JSON to camelCase
function camelCase(json) {
json = json.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
return json;
}
// Convert the config to JS
function getStylesConfig(camelCase) {
var style = null;
style = window.getComputedStyle(stylesConfigJSON, '::before');
style = style.content;
style = removeQuotes(style);
if(camelCase) {
style = camelCase(style);
}
return JSON.parse(style);
}
// Store configuartion data in a variable
var module = getStylesConfig();
// CamelCase the config
var moduleCC = getStylesConfig(camelCase);
|
Make ARIA attrs actually update.
|
$(function() {
var panelContent = $('#panel-content');
/**
* Toggles the ARIA expanded and hidden attributes' state.
*
* @param Object elem The element on which to toggle the attribute.
*/
function toggleAria(elem) {
var expandedState = elem.attr('aria-expanded') === 'true' ? 'false' : 'true';
var hiddenState = elem.attr('aria-hidden') === 'true' ? 'false' : 'true';
elem.attr('aria-hidden', hiddenState);
elem.attr('aria-expanded', expandedState);
}
$('#panel-toggle').click(function(event) {
var panelContent = $(this).next();
var icon = $('.navpanel-icon', this);
icon.toggleClass('expanded');
panelContent.toggle();
toggleAria(panelContent);
});
});
|
$(function() {
var panelContent = $('#panel-content');
/**
* Toggles the ARIA expanded and hidden attributes' state.
*
* @param Object elem The element on which to toggle the attribute.
*/
function toggleAria(elem) {
var expandedState = elem.attr('aria-expanded') === 'true' ? 'false' : 'true';
var hiddenState = elem.attr('aria-hidden') === 'true' ? 'false' : 'true';
elem.attr('aria-hidden', state);
elem.attr('aria-expanded', state);
}
$('#panel-toggle').click(function(event) {
var panelContent = $(this).next();
var icon = $('.navpanel-icon', this);
icon.toggleClass('expanded');
panelContent.toggle();
toggleAria(panelContent);
});
});
|
fix: Make the card name more clear on a multiple result
|
const utilities = require('./utilities');
const limited = (card) => card.limited ? ' | limited' : '';
const unique = (card) => card.unique ? ' | unique' : '';
const points = (card) => `${card.points}pt${card.points > 1 ? 's': ''}`;
const multiCard = (card) => `\n• *${card.name}* (${card.slot}) use \`/card ${card.name} (${card.slot})\` or \`/card #id ${utilities.cardId(card)}\``;
function cardReduce(currentString, card) {
if(typeof currentString === 'object') {
currentString = cardReduce('', currentString);
}
return currentString + multiCard(card);
}
const templates = {
// Template for a single card
card: (card) => `${card.name} (${card.slot}${limited(card)}${unique(card)}): ${points(card)}\n${card.text}`,
// Template for multiple cards
multiple: (cards, query) => {
let cardString = cards.reduce(cardReduce);
return `I found more than one card matching *'${query.text}'*:${cardString}`;
},
// Template for no results
notFound: (query) => `Sorry i couldn't find a card for *'${query.text}'*`
};
module.exports = templates;
|
const utilities = require('./utilities');
const limited = (card) => card.limited ? ' | limited' : '';
const unique = (card) => card.unique ? ' | unique' : '';
const points = (card) => `${card.points}pt${card.points > 1 ? 's': ''}`;
const multiCard = (card) => `\n• ${card.name} (${card.slot}) use \`/card ${card.name} (${card.slot})\` or \`/card #id ${utilities.cardId(card)}\``;
function cardReduce(currentString, card) {
if(typeof currentString === 'object') {
currentString = cardReduce('', currentString);
}
return currentString + multiCard(card);
}
const templates = {
// Template for a single card
card: (card) => `${card.name} (${card.slot}${limited(card)}${unique(card)}): ${points(card)}\n${card.text}`,
// Template for multiple cards
multiple: (cards, query) => {
let cardString = cards.reduce(cardReduce);
return `I found more than one card matching *'${query.text}'*:${cardString}`;
},
// Template for no results
notFound: (query) => `Sorry i couldn't find a card for *'${query.text}'*`
};
module.exports = templates;
|
Make sure @Dependency is marked as final
|
package arez.doc.examples.at_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.Dependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
@Nonnull
private final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@Dependency
@Nonnull
public final Person getPerson()
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@Dependency( action = Dependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
|
package arez.doc.examples.at_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.Dependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
@Nonnull
private final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@Dependency
@Nonnull
public Person getPerson()
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@Dependency( action = Dependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
|
Add styles for buttons and author
|
var getGradient = function () {
var red1 = Math.floor(Math.random() * 256);
var green1 = Math.floor(Math.random() * 256);
var blue1 = Math.floor(Math.random() * 256);
var red2 = Math.floor(Math.random() * 256);
var green2 = Math.floor(Math.random() * 256);
var blue2 = Math.floor(Math.random() * 256);
var rgb1 = 'rgb(' + red1 + ',' + green1 + ',' + blue1 + ')';
var rgb2 = 'rgb(' + red2 + ',' + green2 + ',' + blue2 + ')';
var webkitLinearGradient = '-webkit-linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';
var linearGradient = 'linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';
$('body').css('background-color', rgb1);
$('button').css('background-color', rgb1);
$('#quote').css('color', rgb1);
$('#author').css('color', rgb1);
};
|
var getGradient = function () {
var red1 = Math.floor(Math.random() * 256);
var green1 = Math.floor(Math.random() * 256);
var blue1 = Math.floor(Math.random() * 256);
var red2 = Math.floor(Math.random() * 256);
var green2 = Math.floor(Math.random() * 256);
var blue2 = Math.floor(Math.random() * 256);
var rgb1 = 'rgb(' + red1 + ',' + green1 + ',' + blue1 + ')';
var rgb2 = 'rgb(' + red2 + ',' + green2 + ',' + blue2 + ')';
var webkitLinearGradient = '-webkit-linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';
var linearGradient = 'linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';
$('body').css('background-color', rgb1);
$('#quote').css('color', rgb1);
};
|
Fix undefined index notice bug
|
<?php
namespace JoeTannenbaum\PHPushbullet;
class Device {
/**
* The fields that we want to retrieve for the device
*
* @var array $fields
*/
protected $fields = [
'nickname',
'iden',
'model',
'type',
'active',
'pushable',
'manufacturer',
'created',
];
public function __construct( Array $attr )
{
foreach ( $this->fields as $field )
{
$method = 'set' . ucwords( $field );
if ( method_exists( $this, $method ) )
{
// If there is a setter for this field, use that
$this->$field = $this->$method( $attr[ $field ] );
}
else
{
// Otherwise just set the property
$this->$field = isset($attr[ $field ]) ? $attr[ $field ] : null;
}
}
}
/**
* Format the date so that it's readable
*
* @param integer $date
* @return string
*/
protected function setCreated( $date )
{
return date( 'Y-m-d h:i:sA T', $date );
}
}
|
<?php
namespace JoeTannenbaum\PHPushbullet;
class Device {
/**
* The fields that we want to retrieve for the device
*
* @var array $fields
*/
protected $fields = [
'nickname',
'iden',
'model',
'type',
'active',
'pushable',
'manufacturer',
'created',
];
public function __construct( Array $attr )
{
foreach ( $this->fields as $field )
{
$method = 'set' . ucwords( $field );
if ( method_exists( $this, $method ) )
{
// If there is a setter for this field, use that
$this->$field = $this->$method( $attr[ $field ] );
}
else
{
// Otherwise just set the property
$this->$field = $attr[ $field ];
}
}
}
/**
* Format the date so that it's readable
*
* @param integer $date
* @return string
*/
protected function setCreated( $date )
{
return date( 'Y-m-d h:i:sA T', $date );
}
}
|
Use new api docs urls
|
package main
import (
"github.com/dynport/dgtk/cli"
"github.com/phrase/phraseapp-go/phraseapp"
)
func ApplyNonRestRoutes(r *cli.Router, cfg *phraseapp.Config) {
r.Register("pull", &PullCommand{Config: *cfg}, "Download locales from your PhraseApp project.\n You can provide parameters supported by the locales#download endpoint https://developers.phraseapp.com/api/#locales_download\n in your configuration (.phraseapp.yml) for each source.\n See our configuration guide for more information https://phraseapp.com/docs/developers/cli/configuration/")
r.Register("push", &PushCommand{Config: *cfg}, "Upload locales to your PhraseApp project.\n You can provide parameters supported by the uploads#create endpoint https://developers.phraseapp.com/api/#uploads_create\n in your configuration (.phraseapp.yml) for each source.\n See our configuration guide for more information https://phraseapp.com/docs/developers/cli/configuration/")
r.Register("init", &InitCommand{Config: *cfg}, "Configure your PhraseApp client.")
r.Register("upload/cleanup", &UploadCleanupCommand{Config: *cfg}, "Delete unmentioned keys for given upload")
r.RegisterFunc("info", infoCommand, "Info about version and revision of this client")
}
|
package main
import (
"github.com/dynport/dgtk/cli"
"github.com/phrase/phraseapp-go/phraseapp"
)
func ApplyNonRestRoutes(r *cli.Router, cfg *phraseapp.Config) {
r.Register("pull", &PullCommand{Config: *cfg}, "Download locales from your PhraseApp project.\n You can provide parameters supported by the locales#download endpoint http://docs.phraseapp.com/api/v2/locales/#download\n in your configuration (.phraseapp.yml) for each source.\n See our configuration guide for more information http://docs.phraseapp.com/developers/cli/configuration/")
r.Register("push", &PushCommand{Config: *cfg}, "Upload locales to your PhraseApp project.\n You can provide parameters supported by the uploads#create endpoint http://docs.phraseapp.com/api/v2/uploads/#create\n in your configuration (.phraseapp.yml) for each source.\n See our configuration guide for more information http://docs.phraseapp.com/developers/cli/configuration/")
r.Register("init", &InitCommand{Config: *cfg}, "Configure your PhraseApp client.")
r.Register("upload/cleanup", &UploadCleanupCommand{Config: *cfg}, "Delete unmentioned keys for given upload")
r.RegisterFunc("info", infoCommand, "Info about version and revision of this client")
}
|
Support Native Props For Lists
|
import React from 'react';
import {
ListView,
} from 'react-native';
import { List, ListItem } from 'react-native-elements';
import EmptyView from '../EmptyView';
export default (props) => {
const { loading, loadSuccess, data, dataSource, loadingTip, loadFailTip, emptyTip, renderRow, containerStyle = {}, ...other } = props;
if (loading) {
return (
<EmptyView
tip={loadingTip.tip}
subTip={loadingTip.subTip}
/>
);
}
if (!loadSuccess) {
return (
<EmptyView
tip={loadFailTip.tip}
subTip={loadFailTip.subTip}
/>
);
}
if (data.length === 0) {
return (
<EmptyView
tip={emptyTip.tip}
subTip={emptyTip.subTip}
/>
);
}
return (
<ListView
{...other}
style={containerStyle}
renderRow={renderRow}
dataSource={dataSource}
/>
);
};
|
import React from 'react';
import {
ListView,
} from 'react-native';
import { List, ListItem } from 'react-native-elements';
import EmptyView from '../EmptyView';
export default ({ loading, loadSuccess, data, dataSource, loadingTip, loadFailTip, emptyTip, renderRow, containerStyle = {} }) => {
if (loading) {
return (
<EmptyView
tip={loadingTip.tip}
subTip={loadingTip.subTip}
/>
);
}
if (!loadSuccess) {
return (
<EmptyView
tip={loadFailTip.tip}
subTip={loadFailTip.subTip}
/>
);
}
if (data.length === 0) {
return (
<EmptyView
tip={emptyTip.tip}
subTip={emptyTip.subTip}
/>
);
}
return (
<ListView
style={containerStyle}
renderRow={renderRow}
dataSource={dataSource}
/>
);
};
|
Test 4.2: use the max frame size from the server's SETTINGS frame
The test now does a settings handshake and uses the server's settings
to determine the max frame size (then sends a frame 1 byte longer).
Previously the test used the value of the default setting.
|
package h2spec
import (
"github.com/bradfitz/http2"
"github.com/bradfitz/http2/hpack"
)
func FrameSizeTestGroup() *TestGroup {
tg := NewTestGroup("4.2", "Frame Size")
tg.AddTestCase(NewTestCase(
"Sends large size frame that exceeds the SETTINGS_MAX_FRAME_SIZE",
"The endpoint MUST send a FRAME_SIZE_ERROR error.",
func(ctx *Context) (expected []Result, actual Result) {
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
hdrs := []hpack.HeaderField{
pair(":method", "GET"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = false
hp.EndHeaders = true
hp.BlockFragment = http2Conn.EncodeHeader(hdrs)
http2Conn.fr.WriteHeaders(hp)
max_size, ok := http2Conn.Settings[http2.SettingMaxFrameSize]
if( !ok ) {
max_size = 18384
}
http2Conn.fr.WriteData(1, true, []byte(dummyData(int(max_size) + 1)))
actualCodes := []http2.ErrCode{http2.ErrCodeFrameSize}
return TestStreamError(ctx, http2Conn, actualCodes)
},
))
return tg
}
|
package h2spec
import (
"github.com/bradfitz/http2"
"github.com/bradfitz/http2/hpack"
)
func FrameSizeTestGroup() *TestGroup {
tg := NewTestGroup("4.2", "Frame Size")
tg.AddTestCase(NewTestCase(
"Sends large size frame that exceeds the SETTINGS_MAX_FRAME_SIZE",
"The endpoint MUST send a FRAME_SIZE_ERROR error.",
func(ctx *Context) (expected []Result, actual Result) {
http2Conn := CreateHttp2Conn(ctx, false)
defer http2Conn.conn.Close()
http2Conn.fr.WriteSettings()
hdrs := []hpack.HeaderField{
pair(":method", "GET"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = false
hp.EndHeaders = true
hp.BlockFragment = http2Conn.EncodeHeader(hdrs)
http2Conn.fr.WriteHeaders(hp)
http2Conn.fr.WriteData(1, true, []byte(dummyData(16385)))
actualCodes := []http2.ErrCode{http2.ErrCodeFrameSize}
return TestStreamError(ctx, http2Conn, actualCodes)
},
))
return tg
}
|
joystick: Replace tabs by space in example
Signed-off-by: Francois Berder <59eaf4bb0211c66c3d7532da6d77ecf42a779d82@outlook.fr>
|
#!/usr/bin/env python3
"""This example shows how to use the Joystick Click wrapper of the LetMeCreate.
It continuously reads the position of the joystick, prints it in the terminal
and displays a pattern on the LED's based on the x coordinate.
The Joystick Click must be inserted in Mikrobus 1 before running this program.
"""
from letmecreate.core import i2c
from letmecreate.core import led
from letmecreate.click import joystick
OFFSET = 98
MAXIMUM = OFFSET2
def get_led_mask(perc):
div = int((1. - perc)led.LED_CNT)
if div > led.LED_CNT:
div = led.LED_CNT
mask = 0
for i in range(div):
mask |= (1 << i)
return mask
i2c.init()
led.init()
while True:
pos = joystick.get_position()
print('{} {}'.format(pos[0], pos[1]))
mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM))
led.switch_on(mask)
led.switch_off(~mask)
i2c.release()
led.release()
|
#!/usr/bin/env python3
"""This example shows how to use the Joystick Click wrapper of the LetMeCreate.
It continuously reads the position of the joystick, prints it in the terminal
and displays a pattern on the LED's based on the x coordinate.
The Joystick Click must be inserted in Mikrobus 1 before running this program.
"""
from letmecreate.core import i2c
from letmecreate.core import led
from letmecreate.click import joystick
OFFSET = 98
MAXIMUM = OFFSET2
def get_led_mask(perc):
div = int((1. - perc)led.LED_CNT)
if div > led.LED_CNT:
div = led.LED_CNT
mask = 0
for i in range(div):
mask |= (1 << i)
return mask
i2c.init()
led.init()
while True:
pos = joystick.get_position()
print('{} {}'.format(pos[0], pos[1]))
mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM))
led.switch_on(mask)
led.switch_off(~mask)
i2c.release()
led.release()
|
Add a fix for changing empty option of depencendy fieldset only if a value was set before
|
<?php
namespace DlcUseCase\Form;
use DlcUseCase\Form\BasePriority;
use Zend\Form\Element;
use Zend\Form\Form as ZendForm;
use Zend\Form\FormInterface;
class EditUseCase extends BaseUseCase
{
public function init()
{
parent::init();
$this->setLabel('Edit use case');
}
public function bind($useCase, $flags = FormInterface::VALUES_NORMALIZED)
{
parent::bind($useCase, $flags);
if ($useCase->getType() != null) {
$this->byName['type']->setValue($useCase->getType()->getId());
}
if ($useCase->getCategory() != null) {
$this->byName['category']->setValue($useCase->getCategory()->getId());
}
if ($useCase->getPriority() != null) {
$this->byName['priority']->setValue($useCase->getPriority()->getId());
}
$dependenciesCollection = $this->byName['dependencies'];
foreach ($dependenciesCollection->getFieldsets() as $fieldset) {
if ($fieldset->byName['toNode']->getValue() != null) {
$fieldset->byName['toNode']->setEmptyOption('Delete this dependency');
}
}
}
}
|
<?php
namespace DlcUseCase\Form;
use DlcUseCase\Form\BasePriority;
use Zend\Form\Element;
use Zend\Form\Form as ZendForm;
use Zend\Form\FormInterface;
class EditUseCase extends BaseUseCase
{
public function init()
{
parent::init();
$this->setLabel('Edit use case');
}
public function bind($useCase, $flags = FormInterface::VALUES_NORMALIZED)
{
parent::bind($useCase, $flags);
if ($useCase->getType() != null) {
$this->byName['type']->setValue($useCase->getType()->getId());
}
if ($useCase->getCategory() != null) {
$this->byName['category']->setValue($useCase->getCategory()->getId());
}
if ($useCase->getPriority() != null) {
$this->byName['priority']->setValue($useCase->getPriority()->getId());
}
$dependenciesCollection = $this->byName['dependencies'];
foreach ($dependenciesCollection->getFieldsets() as $fieldset) {
$fieldset->byName['toNode']->setEmptyOption('Delete this dependency');
}
}
}
|
Load test 170 per process
|
'use strict';
const config = {};
/**
* Heroku makes it available to help calculate correct concurrency
* @see https://devcenter.heroku.com/articles/node-concurrency#tuning-the-concurrency-level
*/
config.memoryAvailable = parseInt(process.env.MEMORY_AVAILABLE, 10);
/**
* Expected MAX memory footprint of a single concurrent process in Megabytes.
*
* NOTE: This value is the basis to calculate the Procfile server flag: --max_old_space_size=<size>
* The value in the Procfile is 90% of the estimated processMemory here.
* Based on a Heroku recommendation. @see https://blog.heroku.com/node-habits-2016#7-avoid-garbage
*/
config.processMemory = 170;
/**
* Calculate total amount of concurrent processes to fork
* based on available memory and estimated process memory footprint
*/
config.total = config.memoryAvailable ?
Math.floor(config.memoryAvailable / config.processMemory) : 1;
module.exports = config;
|
'use strict';
const config = {};
/**
* Heroku makes it available to help calculate correct concurrency
* @see https://devcenter.heroku.com/articles/node-concurrency#tuning-the-concurrency-level
*/
config.memoryAvailable = parseInt(process.env.MEMORY_AVAILABLE, 10);
/**
* Expected MAX memory footprint of a single concurrent process in Megabytes.
*
* NOTE: This value is the basis to calculate the Procfile server flag: --max_old_space_size=<size>
* The value in the Procfile is 90% of the estimated processMemory here.
* Based on a Heroku recommendation. @see https://blog.heroku.com/node-habits-2016#7-avoid-garbage
*/
config.processMemory = 200;
/**
* Calculate total amount of concurrent processes to fork
* based on available memory and estimated process memory footprint
*/
config.total = config.memoryAvailable ?
Math.floor(config.memoryAvailable / config.processMemory) : 1;
module.exports = config;
|
Remove www from footer links
|
import React from 'react'
import './style.scss'
const Footer = () => {
return (
<div className="footer container">
<hr/>
<div className="grid">
<p className="left">
© 2013 - { new Date().getUTCFullYear() } IPv6-adresse.dk
<span className="sep">·</span>
<a href="https://twitter.com/ipv6dk" title="@ipv6dk på Twitter" target="_blank" rel="noreferrer">@ipv6dk</a>
<span className="sep">·</span>
<a href="mailto:ipv6@ipv6-adresse.dk" title="Send en mail!">ipv6@ipv6-adresse.dk</a>
</p>
<p className="right">
Et projekt af <a href="https://emilstahl.dk" title="Emils hjemmeside" target="_blank" rel="noreferrer">Emil Stahl</a>
<span className="sep">·</span>
<a href="https://twitter.com/emilstahl" title="@emilstahl på Twitter" target="_blank" rel="noreferrer">@emilstahl</a>
</p>
</div>
</div>
);
}
export default Footer;
|
import React from 'react'
import './style.scss'
const Footer = () => {
return (
<div className="footer container">
<hr/>
<div className="grid">
<p className="left">
© 2013 - { new Date().getUTCFullYear() } IPv6-adresse.dk
<span className="sep">·</span>
<a href="https://www.twitter.com/ipv6dk" title="@ipv6dk på Twitter" target="_blank" rel="noreferrer">@ipv6dk</a>
<span className="sep">·</span>
<a href="mailto:ipv6@ipv6-adresse.dk" title="Send en mail!">ipv6@ipv6-adresse.dk</a>
</p>
<p className="right">
Et projekt af <a href="https://www.emilstahl.dk" title="Emils hjemmeside" target="_blank" rel="noreferrer">Emil Stahl</a>
<span className="sep">·</span>
<a href="https://www.twitter.com/emilstahl" title="@emilstahl på Twitter" target="_blank" rel="noreferrer">@emilstahl</a>
</p>
</div>
</div>
);
}
export default Footer;
|
Make no gui test random all tracks
|
package test
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
"github.com/fabiofalci/sconsify/events"
"github.com/fabiofalci/sconsify/spotify"
ui "github.com/fabiofalci/sconsify/ui"
"github.com/howeyc/gopass"
sp "github.com/op/go-libspotify/spotify"
)
func main2() {
username, pass := credentials()
events := events.InitialiseEvents()
go spotify.Initialise(username, pass, events)
playlists := <-events.WaitForPlaylists()
allTracks := getAllTracks(playlists).Contents()
for {
index := rand.Intn(len(allTracks))
track := allTracks[index]
events.ToPlay <- track
println(<-events.WaitForStatus())
<-events.NextPlay
}
}
func getAllTracks(playlists map[string]*sp.Playlist) *ui.Queue {
queue := ui.InitQueue()
for _, playlist := range playlists {
playlist.Wait()
for i := 0; i < playlist.Tracks(); i++ {
track := playlist.Track(i).Track()
track.Wait()
queue.Add(track)
}
}
return queue
}
func credentials() (*string, *[]byte) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Username: ")
username, _ := reader.ReadString('\n')
username = strings.Trim(username, " \n\r")
fmt.Print("Password: ")
pass := gopass.GetPasswd()
return &username, &pass
}
|
package test
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/fabiofalci/sconsify/events"
"github.com/fabiofalci/sconsify/spotify"
"github.com/howeyc/gopass"
)
func main2() {
username, pass := credentials()
events := events.InitialiseEvents()
go spotify.Initialise(username, pass, events)
playlists := <-events.WaitForPlaylists()
playlist := playlists["Ramones"]
playlist.Wait()
track := playlist.Track(3).Track()
track.Wait()
events.ToPlay <- track
println(track.Name())
<-events.WaitForStatus()
<-events.NextPlay
}
func credentials() (*string, *[]byte) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Username: ")
username, _ := reader.ReadString('\n')
username = strings.Trim(username, " \n\r")
fmt.Print("Password: ")
pass := gopass.GetPasswd()
return &username, &pass
}
|
Fix compiling problem for runtime variables
|
from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
value = assemble(Mul)
elif op == '/':
value = assemble(Div)
elif op == '%':
value = assemble(Mod)
else:
raise RuntimeError('unknown operator: ' + op)
commands.append(value)
def int_aexp(commands, env, i):
commands.append(assemble(Push, i))
def var_aexp(commands, env, name):
var_type = Environment.get_var_type(env, name)
var_value = Environment.get_var(env, name)
if var_type == 'String':
String.compile_get(commands, env, var_value)
else:
commands.append(assemble(Load, var_value))
|
from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
value = assemble(Mul)
elif op == '/':
value = assemble(Div)
elif op == '%':
value = assemble(Mod)
else:
raise RuntimeError('unknown operator: ' + op)
commands.append(value)
def int_aexp(commands, env, i):
commands.append(assemble(Push, i))
def var_aexp(commands, env, name):
var_type = Environment.get_var_type(env, name)
var_value = Environment.get_var(env, name)
if var_type == 'IntAexp':
commands.append(assemble(Load, var_value))
elif var_type == 'Char':
commands.append(assemble(Load, var_value))
elif var_type == 'String':
String.compile_get(commands, env, var_value)
|
Update error in 3.7 release
|
import os
import re
import sys
import platform
import subprocess
import multiprocessing
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion
cores = multiprocessing.cpu_count()*1.25
threads="-j" + str(int(cores))
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
def readme():
with open("PYTHONREADME.md", "r") as fh:
return fh.read()
def operatingsystem():
if (platform.platform().find("Darwin") >= 0):
return "Operating System :: MacOS"
else:
return "Operating System :: POSIX :: Linux"
setup(
name='sharkbite',
version='1.2.0.1',
author='Marc Parisi',
author_email='phrocker@apache.org',
url='https://docs.sharkbite.io/',
description='Apache Accumulo and Apache HDFS Python Connector',
long_description=readme(),
long_description_content_type='text/markdown',
ext_modules=[CMakeExtension('sharkbite.pysharkbite')],
zip_safe=False,
classifiers=[
"Programming Language :: C++",
"License :: OSI Approved :: Apache Software License",
operatingsystem(),
],
python_requires='>=3.6',
packages=['sharkbite']
)
|
import os
import re
import sys
import platform
import subprocess
import multiprocessing
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion
cores = multiprocessing.cpu_count()*1.25
threads="-j" + str(int(cores))
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
def readme():
with open("PYTHONREADME.md", "r") as fh:
return fh.read()
def operatingsystem():
if (platform.platform().find("Darwin") >= 0):
return "Operating System :: MacOS"
else:
return "Operating System :: POSIX :: Linux"
setup(
name='sharkbite',
version='1.2.0.0',
author='Marc Parisi',
author_email='phrocker@apache.org',
url='https://docs.sharkbite.io/',
description='Apache Accumulo and Apache HDFS Python Connector',
long_description=readme(),
long_description_content_type='text/markdown',
ext_modules=[CMakeExtension('sharkbite.pysharkbite')],
zip_safe=False,
classifiers=[
"Programming Language :: C++",
"License :: OSI Approved :: Apache Software License",
operatingsystem(),
],
python_requires='>=3.6',
packages=['sharkbite']
)
|
Add support for project assets like parallax and other files
|
const fs = require('fs');
const path = require('path');
const express = require('express');
const router = express.Router();
router.get('/', function (req, res) {
res.send('Add a Project or Owner id to the URL bar!');
});
router.get('/:owner', [
require('./owner-project-list'),
require('./redirect-to-project')
]);
router.get([
'/:owner/:project',
'/:owner/:project/report',
'/:owner/:project/presentation'
], [
require('./cache-project'),
require('./render-project')
]);
// :type is the /report or /presentation url fragment
// since it's virtual we map the file path by omitting it
router.get('/:owner/:project/:type/:asset', function (req, res, next) {
const p = req.params;
res.sendFile(path.join(req.app.locals.cacheDir, p.owner, p.project, p.asset));
});
// reveal.js assets
router.use('/:owner/:project/presentation', express.static('public/reveal'));
module.exports = router;
|
const fs = require('fs');
const path = require('path');
const express = require('express');
const router = express.Router();
router.get('/', function (req, res) {
res.send('Add a Project or Owner id to the URL bar!');
});
router.get('/:owner', [
require('./owner-project-list'),
require('./redirect-to-project')
]);
router.get([
'/:owner/:project',
'/:owner/:project/report',
'/:owner/:project/presentation'
], [
require('./cache-project'),
require('./render-project')
]);
// reveal.js assets
router.use('/:owner/:project/presentation', express.static('public/reveal'));
// pull presentation.md from project dir
router.get('/:owner/:project/presentation/presentation.md', function (req, res) {
const mdPath = path.join(req.app.locals.cacheDir, req.params.owner, req.params.project, 'presentation.md');
fs.readFile(mdPath, {encoding: 'utf8'}, (err, data) => {
if (err) throw err
res.send(data);
});
});
module.exports = router;
|
Update semantic version to 1.0
PiperOrigin-RevId: 258839428
Change-Id: Idac6ba6750e5fa2c53de0d9a56554d99cc8dcbb8
|
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Package metadata for dm_env.
This is kept in a separate module so that it can be imported from setup.py, at
a time when dm_env's dependencies may not have been installed yet.
"""
__version__ = '1.0' # https://www.python.org/dev/peps/pep-0440/
|
# pylint: disable=g-bad-file-header
# Copyright 2019 The dm_env Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Package metadata for dm_env.
This is kept in a separate module so that it can be imported from setup.py, at
a time when dm_env's dependencies may not have been installed yet.
"""
__version__ = '1.0a0' # https://www.python.org/dev/peps/pep-0440/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.