text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use ROOT local when converting enum constants
Otherwise this will fail on some systems, e.g.
those with Turkish locale.
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.compile.processing;
import java.util.Locale;
/**
* The different kinds of annotation processors that the incremental compiler knows how to handle.
* See the user guide chapter on incremental annotation processing for more information.
*/
public enum IncrementalAnnotationProcessorType {
ISOLATING,
AGGREGATING,
DYNAMIC,
UNKNOWN;
public String getProcessorOption() {
return "org.gradle.annotation.processing." + name().toLowerCase(Locale.ROOT);
}
}
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.compile.processing;
/**
* The different kinds of annotation processors that the incremental compiler knows how to handle.
* See the user guide chapter on incremental annotation processing for more information.
*/
public enum IncrementalAnnotationProcessorType {
ISOLATING,
AGGREGATING,
DYNAMIC,
UNKNOWN;
public String getProcessorOption() {
return "org.gradle.annotation.processing." + name().toLowerCase();
}
}
|
Test for incorrect serialisation of PacketLocation
Although the `serialize` method is returning the right thing, when we
serialize it with the `OpenPGPJsonEncoder`, it's being serialized as a
JSON array. Test to capture that behaviour.
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_json_serializing():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION, cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_serialize():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION.serialize(), cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
Watch dist files on browsersync
|
var webpack = require('webpack');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
context: __dirname,
entry: './src/whoami.js',
output: {
path: './dist',
filename: 'whoami.min.js',
libraryTarget: 'var',
library: 'whoami'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
plugins: [
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
files: 'dist/*.*',
server: {
baseDir: ['dist']
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true
})
],
resolve: {
extensions: ['', '.js']
}
}
|
var webpack = require('webpack');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
context: __dirname,
entry: './src/whoami.js',
output: {
path: './dist',
filename: 'whoami.min.js',
libraryTarget: 'var',
library: 'whoami'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
plugins: [
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
server: {
baseDir: ['dist']
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true
})
],
resolve: {
extensions: ['', '.js']
}
}
|
Change permissions model to not require id
|
/**
* Permissions.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
id:
{
type: "integer",
primaryKey: true,
unique: true,
autoIncrement: true,
},
role_id:
{
type: "integer",
required: true
},
model:
{
type: "string",
lowercase: true,
required: true
},
self:
{
type: "boolean",
defaultsTo: false
},
other:
{
type: "boolean",
defaultsTo: false
}
}
};
|
/**
* Permissions.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
id:
{
type: "integer",
primaryKey: true,
unique: true,
autoIncrement: true,
required: true
},
role_id:
{
type: "integer",
required: true
},
model:
{
type: "string",
lowercase: true,
required: true
},
self:
{
type: "boolean",
defaultsTo: false
},
other:
{
type: "boolean",
defaultsTo: false
}
}
};
|
[RUN_TESTS] Move all imports to top-of-module, don't hide cleanup output.
|
#!/usr/bin/env python3
"""Run tests under a consistent environment...
Whether run from the terminal, in CI or from the editor this file makes sure
the tests are run in a consistent environment.
"""
#------------------------------------------------------------------------------
# Py2C - A Python to C++ compiler
# Copyright (C) 2014 Pradyun S. Gedam
#------------------------------------------------------------------------------
# Local modules
import cleanup
# Standard library
import sys
from os.path import join, realpath, dirname
# Third Party modules
import nose
import coverage
cleanup.REMOVE_GENERATED_AST = False
cleanup.main()
base_dir = realpath(dirname(__file__))
root_dir = join(dirname(base_dir), "py2c")
REPORT = True
if "--dont-report" in sys.argv:
sys.argv.remove("--dont-report")
REPORT = False
cov = coverage.coverage(config_file=join(base_dir, ".coveragerc"))
cov.start()
success = nose.run(
env={
"NOSE_INCLUDE_EXE": "True",
"NOSE_WITH_HTML_REPORT": "True",
"NOSE_WITH_SPECPLUGIN": "True"
},
defaultTest=root_dir,
)
cov.stop()
cov.save()
if success and REPORT:
cov.html_report()
cov.report()
sys.exit(0 if success else 1)
|
#!/usr/bin/env python3
"""Run tests under a consistent environment...
Whether run from the terminal, in CI or from the editor this file makes sure
the tests are run in a consistent environment.
"""
#------------------------------------------------------------------------------
# Py2C - A Python to C++ compiler
# Copyright (C) 2014 Pradyun S. Gedam
#------------------------------------------------------------------------------
import sys
from os.path import join, realpath, dirname
# Local modules
import cleanup
cleanup.REMOVE_GENERATED_AST = False
cleanup.PRINT_OUTPUT = False
cleanup.main()
# Third Party modules
import nose
import coverage
base_dir = realpath(dirname(__file__))
root_dir = join(dirname(base_dir), "py2c")
REPORT = True
if "--dont-report" in sys.argv:
sys.argv.remove("--dont-report")
REPORT = False
cov = coverage.coverage(config_file=join(base_dir, ".coveragerc"))
cov.start()
success = nose.run(
env={
"NOSE_INCLUDE_EXE": "True",
"NOSE_WITH_HTML_REPORT": "True",
"NOSE_WITH_SPECPLUGIN": "True"
},
defaultTest=root_dir,
)
cov.stop()
cov.save()
if success and REPORT:
cov.html_report()
cov.report()
sys.exit(0 if success else 1)
|
Watch changes over json files
|
// Modules required for this task
var gulp = require('gulp'),
environments = require('gulp-environments');
// Define main directories
var assets = 'assets/',
development = environments.development;
// Watch for changes in our custom assets
gulp.task('watch', function() {
// watch only if in development ENV
if (development()) {
// Watch .js files
gulp.watch(assets + 'app/*.js', ['app']);
gulp.watch(assets + 'app/core/**/*.js', ['angularCore']);
gulp.watch(assets + 'app/features/**/*.js', ['angularFeatures']);
gulp.watch(assets + 'app/features/**/*.json', ['angularFeatures']);
gulp.watch(assets + 'app/widgets/**/*.js', ['angularWidgets']);
gulp.watch(assets + 'app/widgets/**/*.json', ['angularWidgets']);
gulp.watch(assets + 'app/data/**/*.js', ['angularData']);
// Watch .css files
gulp.watch(assets + '**/*.less', ['less']);
// Watch image files
gulp.watch(assets + 'content/images/**/*', ['images']);
// Watch the Jade files in the Assets folder
gulp.watch(assets + '**/*.jade', ['cleanAssetsHtml']);
}
});
|
// Modules required for this task
var gulp = require('gulp'),
environments = require('gulp-environments');
// Define main directories
var assets = 'assets/',
development = environments.development;
// Watch for changes in our custom assets
gulp.task('watch', function() {
// watch only if in development ENV
if (development()) {
// Watch .js files
gulp.watch(assets + 'app/*.js', ['app']);
gulp.watch(assets + 'app/core/**/*.js', ['angularCore']);
gulp.watch(assets + 'app/features/**/*.js', ['angularFeatures']);
gulp.watch(assets + 'app/widgets/**/*.js', ['angularWidgets']);
gulp.watch(assets + 'app/data/**/*.js', ['angularData']);
// Watch .css files
gulp.watch(assets + '**/*.less', ['less']);
// Watch image files
gulp.watch(assets + 'content/images/**/*', ['images']);
// Watch the Jade files in the Assets folder
gulp.watch(assets + '**/*.jade', ['cleanAssetsHtml']);
}
});
|
Remove custom extend to use the one from Backbone
|
var _ = require('underscore'),
Backbone = require('backbone'),
ControlBones;
ControlBones = function(options) {
var self = this;
// Copy all options to object
_.each(options, function(value, key) {
self[key] = value;
});
};
ControlBones.prototype = {
classes: ''
};
/**
* This is called to render the view using
* the latest data from the model.
*/
ControlBones.prototype.render = function() {
// noop
};
/**
* @return Backbone.Model
*/
ControlBones.prototype._createSummaryModel = function() {
return new Backbone.Model({
'header': this.title,
'classes': this.classes
});
};
// Benefit from Backbone.Events
_.extend(ControlBones.prototype, Backbone.Events);
// Snag the extend function from Backbone.Model
ControlBones.extend = Backbone.Model.extend;
module.exports = ControlBones;
|
var _ = require('underscore'),
Backbone = require('backbone'),
ControlBones;
ControlBones = function(options) {
var self = this;
// Copy all options to object
_.each(options, function(value, key) {
self[key] = value;
});
};
ControlBones.prototype = {
classes: ''
};
/**
* This is called to render the view using
* the latest data from the model.
*/
ControlBones.prototype.render = function() {
// noop
};
/**
* @return Backbone.Model
*/
ControlBones.prototype._createSummaryModel = function() {
return new Backbone.Model({
'header': this.title,
'classes': this.classes
});
};
// Benefit from Backbone.Events
_.extend(ControlBones.prototype, Backbone.Events);
ControlBones.extend = function(prototypeAdditions) {
var parent = this,
child;
child = function(){
return parent.apply(this, arguments);
};
_.extend(child, parent);
_.extend(child.prototype, parent.prototype);
if (prototypeAdditions) {
_.extend(child.prototype, prototypeAdditions);
}
return child;
};
module.exports = ControlBones;
|
Make pagination choices multiples of the base per_page
|
<?
/**
* This is implemented by the _pagination partial and hydrated
* by the Bkwld\Decoy\Html\Paginator class to render pagination.
* It is based on /laravel/framework/src/Illuminate/Pagination/views/slider.php
* The paginator is only shown if there are more results than the smallest
* per_page option.
*/
$presenter = new Illuminate\Pagination\BootstrapPresenter($paginator);
if ($paginator->getTotal() > Bkwld\Decoy\Controllers\Base::$per_page): ?>
<div class="pagination">
<?// The list of pages ?>
<? if ($paginator->getLastPage() > 1): ?>
<ul>
<?=$presenter->render(); ?>
</ul>
<? endif ?>
<?// Per page selector
$options = array(
Bkwld\Decoy\Controllers\Base::$per_page,
Bkwld\Decoy\Controllers\Base::$per_page * 2,
'all');
$count = Input::get('count', $options[0]); ?>
<ul class="per-page">
<li class="disabled"><span>Show</span></li>
<? foreach($options as $option): ?>
<? if ($count == $option): ?>
<?=$presenter->getActivePageWrapper(ucfirst($option))?>
<? else: ?>
<?=$presenter->getPageLinkWrapper($paginator->addQuery('count', $option)->getUrl(1), ucfirst($option))?>
<? endif ?>
<? endforeach ?>
</ul>
</div>
<? endif ?>
|
<?
/**
* This is implemented by the _pagination partial and hydrated
* by the Bkwld\Decoy\Html\Paginator class to render pagination.
* It is based on /laravel/framework/src/Illuminate/Pagination/views/slider.php
* The paginator is only shown if there are more results than the smallest
* per_page option.
*/
$presenter = new Illuminate\Pagination\BootstrapPresenter($paginator);
if ($paginator->getTotal() > Bkwld\Decoy\Controllers\Base::$per_page): ?>
<div class="pagination">
<?// The list of pages ?>
<? if ($paginator->getLastPage() > 1): ?>
<ul>
<?=$presenter->render(); ?>
</ul>
<? endif ?>
<?// Per page selector
$options = array(Bkwld\Decoy\Controllers\Base::$per_page, 40, 'all');
$count = Input::get('count', $options[0]); ?>
<ul class="per-page">
<li class="disabled"><span>Show</span></li>
<? foreach($options as $option): ?>
<? if ($count == $option): ?>
<?=$presenter->getActivePageWrapper(ucfirst($option))?>
<? else: ?>
<?=$presenter->getPageLinkWrapper($paginator->addQuery('count', $option)->getUrl(1), ucfirst($option))?>
<? endif ?>
<? endforeach ?>
</ul>
</div>
<? endif ?>
|
Make login required for /flag in either case.
|
<?php
/**
* api: php
* title: Freshcode.club
* description: FLOSS software release tracking website
* version: 0.3.1
* author: mario
* license: AGPL
*
* Implements a freshmeat/freecode-like directory for open source
* release publishing / tracking.
*
*/
#-- init
include("config.php");
#-- dispatch
switch ($page = $_GET->id["page"]) {
case "index":
case "projects":
case "feed":
case "links":
case "tags":
case "login":
include("page_$page.php");
break;
case "flag":
case "submit":
if ((LOGIN_REQUIRED or $page === "flag") and empty($_SESSION["openid"])) {
exit(include("page_login.php"));
}
include("page_$page.php");
break;
case "admin":
if (!in_array($_SESSION["openid"], $moderator_ids)) {
exit(include("page_login.php"));
}
include("page_admin.php");
break;
default:
include("page_error.php");
}
?>
|
<?php
/**
* api: php
* title: Freshcode.club
* description: FLOSS software release tracking website
* version: 0.3
* author: mario
* license: AGPL
*
* Implements a freshmeat/freecode-like directory for open source
* release publishing / tracking.
*
*/
#-- init
include("config.php");
#-- dispatch
switch ($page = $_GET->id["page"]) {
case "index":
case "projects":
case "feed":
case "links":
case "tags":
case "login":
include("page_$page.php");
break;
case "flag":
case "submit":
if (LOGIN_REQUIRED and empty($_SESSION["openid"])) {
exit(include("page_login.php"));
}
include("page_$page.php");
break;
case "admin":
if (!in_array($_SESSION["openid"], $moderator_ids)) {
exit(include("page_login.php"));
}
include("page_admin.php");
break;
default:
include("page_error.php");
}
?>
|
Handle dashboard redirect when there are no Child objects.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.mixins import (LoginRequiredMixin,
PermissionRequiredMixin)
from django.urls import reverse
from django.views.generic.base import TemplateView, RedirectView
from django.views.generic.detail import DetailView
from core.models import Child
class DashboardRedirect(LoginRequiredMixin, RedirectView):
# Show the overall dashboard or a child dashboard if one Child instance.
def get(self, request, *args, **kwargs):
children = Child.objects.count()
if children == 0:
# TODO: Create some sort of welcome page.
self.url = reverse('child-add')
elif children == 1:
child_instance = Child.objects.first()
self.url = reverse('dashboard-child', args={child_instance.slug})
else:
self.url = reverse('dashboard')
return super(DashboardRedirect, self).get(request, *args, **kwargs)
class Dashboard(LoginRequiredMixin, TemplateView):
template_name = 'dashboard/dashboard.html'
class ChildDashboard(PermissionRequiredMixin, DetailView):
model = Child
permission_required = ('core.view_child',)
template_name = 'dashboard/child.html'
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.mixins import (LoginRequiredMixin,
PermissionRequiredMixin)
from django.urls import reverse
from django.views.generic.base import TemplateView, RedirectView
from django.views.generic.detail import DetailView
from core.models import Child
class DashboardRedirect(LoginRequiredMixin, RedirectView):
# Show the overall dashboard or a child dashboard if one Child instance.
def get(self, request, *args, **kwargs):
if Child.objects.count() == 1:
child_instance = Child.objects.first()
self.url = reverse('dashboard-child', args={child_instance.slug})
else:
self.url = reverse('dashboard')
return super(DashboardRedirect, self).get(request, *args, **kwargs)
class Dashboard(LoginRequiredMixin, TemplateView):
template_name = 'dashboard/dashboard.html'
class ChildDashboard(PermissionRequiredMixin, DetailView):
model = Child
permission_required = ('core.view_child',)
template_name = 'dashboard/child.html'
|
Add timezone support to timestamp helper methods
|
import datetime
import pytz
this_timezone = pytz.timezone('Europe/London')
def timestamp_to_ticks(dt):
"""Converts a datetime to ticks (seconds since Epoch)"""
delta = (dt - datetime.datetime(1970, 1, 1))
ticks = int(delta.total_seconds())
return ticks
def ticks_to_timestamp(ticks):
"""Converts ticks (seconds since Epoch) to a datetime"""
delta = datetime.timedelta(seconds=ticks)
new_timestamp = datetime.datetime(1970, 1, 1) + delta
return new_timestamp
def ticks_utc_now():
"""Returns the current timestamp in ticks"""
time_now = datetime.datetime.utcnow()
ticks = int(timestamp_to_ticks(time_now))
return ticks
def ticks_local_now():
time_now = datetime.datetime.now(tz=this_timezone)
ticks = int(timestamp_to_ticks(time_now))
return ticks
def mobile_number_string_to_int(mobile_string):
"""Converts mobile numbers from a string to an integer"""
return int(mobile_string)
def redact_mobile_number(mobile_string):
"""Takes a mobile number as a string, and redacts all but the last 3 digits"""
return str.format('XXXXX XXX{0}', mobile_string[-3:])
|
import datetime
def to_ticks(dt):
"""Converts a timestamp to ticks"""
return (dt - datetime.datetime(1970, 1, 1)).total_seconds()
def ticks_to_timestamp(ticks):
"""Converts ticks to a timestamp"""
converted = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=3700)
return converted
def ticks_now():
"""Returns the current timestamp in ticks"""
return int(to_ticks(datetime.datetime.utcnow()))
def mobile_number_string_to_int(mobile_string):
"""Converts mobile numbers from a string to an integer"""
return int(mobile_string)
def redact_mobile_number(mobile_string):
"""Takes a mobile number as a string, and redacts all but the last 3 digits"""
return str.format('XXXXX XXX{0}', mobile_string[-3:])
|
Add interface documentation and cleanup
|
<?php namespace Aedart\Scaffold\Contracts\Templates\Data;
use Aedart\Model\Contracts\Arrays\ChoicesAware;
use Aedart\Model\Contracts\Integers\IdAware;
use Aedart\Model\Contracts\Integers\TypeAware;
use Aedart\Model\Contracts\Strings\QuestionAware;
use Aedart\Model\Contracts\Strings\ValueAware;
use Aedart\Util\Interfaces\Populatable;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use JsonSerializable;
/**
* Template Data Property
*
* A data object that contains the final
* value which can be used inside a template and or
* meta information on how to obtain the value.
*
* Each property has a type, which can be used to
* determine how the value must be obtained.
*
* @author Alin Eugen Deac <aedart@gmail.com>
* @package Aedart\Scaffold\Contracts\Templates\Data
*/
interface Property extends IdAware,
TypeAware,
QuestionAware,
ChoicesAware,
ValueAware,
ValidationAware,
PostProcessAware,
ArrayAccess,
Arrayable,
Jsonable,
JsonSerializable,
Populatable
{
}
|
<?php namespace Aedart\Scaffold\Contracts\Templates\Data;
use Aedart\Model\Contracts\Arrays\ChoicesAware;
use Aedart\Model\Contracts\Integers\IdAware;
use Aedart\Model\Contracts\Integers\TypeAware;
use Aedart\Model\Contracts\Strings\QuestionAware;
use Aedart\Model\Contracts\Strings\ValueAware;
use Aedart\Util\Interfaces\Populatable;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use JsonSerializable;
/**
* Template Data Property
*
* TODO: Desc...
*
* @author Alin Eugen Deac <aedart@gmail.com>
* @package Aedart\Scaffold\Contracts\Templates\Data
*/
interface Property extends IdAware,
TypeAware,
QuestionAware,
ChoicesAware,
ValueAware,
ValidationAware,
PostProcessAware,
ArrayAccess,
Arrayable,
Jsonable,
JsonSerializable,
Populatable
{
}
|
Fix velocity_capsule description and drag formula
Drag force should be quadratically dependent on speed instead of linearly dependent.
|
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float
#put inside pod
class Aero(Component):
"""Place holder for real aerodynamic calculations of the capsule"""
#Inputs
coef_drag = Float(1, iotype="in", desc="capsule drag coefficient")
area_capsule = Float(18000, iotype="in", units="cm**2", desc="capsule frontal area")
velocity_capsule = Float(600, iotype="in", units="m/s", desc="capsule velocity")
rho = Float(iotype="in", units="kg/m**3", desc="tube air density")
gross_thrust = Float(iotype="in", units="N", desc="nozzle gross thrust")
#Outputs
net_force = Float(iotype="out", desc="Net force with drag considerations", units="N")
drag = Float(iotype="out", units="N", desc="Drag Force")
def execute(self):
#Drag = 0.5*Cd*rho*Veloc**2*Area
self.drag = 0.5*self.coef_drag*self.rho*self.velocity_capsule**2*self.area_capsule
self.net_force = self.gross_thrust - self.drag
|
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float
#put inside pod
class Aero(Component):
"""Place holder for real aerodynamic calculations of the capsule"""
#Inputs
coef_drag = Float(1, iotype="in", desc="capsule drag coefficient")
area_capsule = Float(18000, iotype="in", units="cm**2", desc="capsule frontal area")
velocity_capsule = Float(600, iotype="in", units="m/s", desc="capsule frontal area")
rho = Float(iotype="in", units="kg/m**3", desc="tube air density")
gross_thrust = Float(iotype="in", units="N", desc="nozzle gross thrust")
#Outputs
net_force = Float(iotype="out", desc="Net force with drag considerations", units="N")
drag = Float(iotype="out", units="N", desc="Drag Force")
def execute(self):
#Drag = 0.5*Cd*rho*Veloc*Area
self.drag = 0.5*self.coef_drag*self.rho*self.velocity_capsule*self.area_capsule
self.net_force = self.gross_thrust - self.drag
|
Disable feeds/announcements temporarily, it should be back alive now
|
# -*- coding: utf-8 -*-
#from apps.announcements.feeds import AnnouncementsFeed
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
#feeds = {
# 'announcements': AnnouncementsFeed,
#}
handler500 = 'apps.login.views.server_error'
urlpatterns = patterns('',
(r'^$', 'apps.accounts.views.index'),
(r'^about/', 'apps.accounts.views.about'),
# (r'^announcements/', 'apps.announcements.views.announcements'),
(r'^dionysos/', 'apps.dionysos.views.dionysos'),
(r'^eclass/', 'apps.eclass.views.eclass'),
# (r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
(r'^library/', 'apps.library.views.library'),
(r'^login/', 'apps.login.views.cronos_login'),
(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login'}),
(r'^preferences/', 'apps.accounts.views.accounts_settings'),
(r'^refrigerators/', 'apps.refrigerators.views.refrigerators'),
(r'^teachers/', 'apps.teachers.views.teachers'),
)
urlpatterns += staticfiles_urlpatterns()
|
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from cronos.announcements.feeds import AnnouncementsFeed
feeds = {
'announcements': AnnouncementsFeed,
}
handler500 = 'cronos.login.views.server_error'
urlpatterns = patterns('',
(r'^$', 'cronos.accounts.views.index'),
(r'^about/', 'cronos.accounts.views.about'),
(r'^announcements/', 'cronos.announcements.views.announcements'),
(r'^dionysos/', 'cronos.dionysos.views.dionysos'),
(r'^eclass/', 'cronos.eclass.views.eclass'),
(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
(r'^library/', 'cronos.library.views.library'),
(r'^login/', 'cronos.login.views.cronos_login'),
(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login'}),
(r'^preferences/', 'cronos.accounts.views.accounts_settings'),
(r'^refrigerators/', 'cronos.refrigerators.views.refrigerators'),
(r'^teachers/', 'cronos.teachers.views.teachers'),
)
urlpatterns += staticfiles_urlpatterns()
|
Remove unnecessary code from setValueForStyles
Close #1734
|
/* eslint-disable */
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* From React 16.3.0
* @noflow
*/
import dangerousStyleValue from '../dangerousStyleValue';
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
function setValueForStyles(node, styles) {
const style = node.style;
for (let styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
const isCustomProperty = styleName.indexOf('--') === 0;
const styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
if (styleName === 'float') {
styleName = 'cssFloat';
}
if (isCustomProperty) {
style.setProperty(styleName, styleValue);
} else {
style[styleName] = styleValue;
}
}
}
export default setValueForStyles;
|
/* eslint-disable */
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* From React 16.3.0
* @noflow
*/
import dangerousStyleValue from '../dangerousStyleValue';
import hyphenateStyleName from 'hyphenate-style-name';
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
function setValueForStyles(node, styles) {
const style = node.style;
for (let styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
const isCustomProperty = styleName.indexOf('--') === 0;
const styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
if (styleName === 'float') {
styleName = 'cssFloat';
}
if (isCustomProperty) {
const name = isCustomProperty ? styleName : hyphenateStyleName(styleName);
style.setProperty(name, styleValue);
} else {
style[styleName] = styleValue;
}
}
}
export default setValueForStyles;
|
Remove commented thunk code in saga
|
/** @babel */
/** global atom */
import { delay } from 'redux-saga'
import { put, call, select, take, fork } from 'redux-saga/effects'
import { run } from 'node-jq'
import { ACTIONS as ACTION } from './constants'
const ONE_SEC = 1000
function * jq () {
while (true) {
const action = yield take(ACTION.JQ_FILTER_REQUEST)
const activePaneItem = yield select(state => state.activePaneItem)
const { payload: { filter } } = action
const filePath = activePaneItem.buffer.file.path
try {
const result = yield run(filter, filePath)
yield call(ACTION.OPEN_MODAL, result)
} catch (e) {
yield call(ACTION.JQ_FILTER_FAILURE)
}
yield call(delay, ONE_SEC)
}
}
export default function * sagas () {
yield [
fork(jq)
]
}
|
/** @babel */
/** global atom */
import { delay } from 'redux-saga'
import { put, call, select, take, fork } from 'redux-saga/effects'
import { run } from 'node-jq'
import { ACTIONS as ACTION } from './constants'
const ONE_SEC = 1000
// const jq = (filter) => {
// return (dispatch, getState) => {
// const { activePaneItem } = getState()
// return run(filter, activePaneItem.getText(), { input: 'string' }).then(
// output => dispatch(jqFilterSuccess(output)),
// error => dispatch(jqFilterFailure(error))
// )
// }
// }
function * jq () {
while (true) {
const action = yield take(ACTION.JQ_FILTER_REQUEST)
const activePaneItem = yield select(state => state.activePaneItem)
const { payload: { filter } } = action
const filePath = activePaneItem.buffer.file.path
try {
const result = yield run(filter, filePath)
yield call(ACTION.OPEN_MODAL, result)
} catch (e) {
yield call(ACTION.JQ_FILTER_FAILURE)
}
yield call(delay, ONE_SEC)
}
}
export default function * sagas () {
yield [
fork(jq)
]
}
|
Fix saving not accepting new format with secret
|
<?php
require_once('setup.php');
function clean($string)
{
return preg_replace('/[^A-Za-z0-9_:]/', '', $string); // Removes special chars.
}
$post_data = clean($_POST['data']);
$id = $_POST['id'];
if ($post_data && $id && strlen($post_data) < 20010) {
if ($id && is_numeric($id)) {
$db_data = explode(":", $redis->get($id));
$user_data = explode(":", $post_data);
if (count($user_data) > 0 && hash_equals($user_data[0], $db_data[0])) {
$redis->set($id, $post_data);
http_response_code(200);
header('Content-Type: application/json');
echo(json_encode(["ok"]));
return;
} else {
http_response_code(403);
return;
}
}
}
http_response_code(400);
|
<?php
require_once('setup.php');
function clean($string)
{
return preg_replace('/[^A-Za-z0-9_:]/', '', $string); // Removes special chars.
}
$post_data = clean($_POST['data']);
$id = $_POST['id'];
$secret = $_POST['secret'];
if ($post_data && $id && $secret && strlen($post_data) < 20010) {
if ($id && is_numeric($id)) {
$db_data = explode(":", $redis->get($id));
if (hash_equals($secret, $db_data[0])) {
$redis->set($id, $secret . ":" . $post_data);
http_response_code(200);
header('Content-Type: application/json');
echo(json_encode(["ok"]));
return;
} else {
http_response_code(403);
return;
}
}
}
http_response_code(400);
|
Allow example visualizations to be passed only an options object
|
import candela from './../../src/candela';
import mainContent from './index.jade';
import visContent from './vis.jade';
import 'javascript-detect-element-resize/detect-element-resize';
import './index.styl';
import iris from '../../src/vcharts/data/iris.json';
import visualizations from './visualizations.json';
let datasets = {
iris
};
let visMap = {};
visualizations.forEach((v) => {
visMap[v.hash] = v;
});
function showPage () {
let pageId = 'main';
if (window.location.hash.length > 1) {
pageId = window.location.hash.slice(1);
}
if (pageId === 'main') {
document.getElementsByTagName('body')[0].innerHTML = mainContent({
visualizations
});
} else {
let properties = visMap[pageId];
document.getElementsByTagName('body')[0].innerHTML = visContent(
properties
);
let el = document.getElementById('vis-element');
let vis;
if (properties.data) {
vis = new candela.components[properties.component](el, datasets[properties.data], properties.options);
} else {
vis = new candela.components[properties.component](el, properties.options);
}
vis.render();
window.addResizeListener(el, () => vis.render());
}
}
window.addEventListener('load', () => {
showPage();
window.addEventListener('hashchange', showPage, false);
});
|
import candela from './../../src/candela';
import mainContent from './index.jade';
import visContent from './vis.jade';
import 'javascript-detect-element-resize/detect-element-resize';
import './index.styl';
import iris from '../../src/vcharts/data/iris.json';
import visualizations from './visualizations.json';
let datasets = {
iris
};
let visMap = {};
visualizations.forEach((v) => {
visMap[v.hash] = v;
});
function showPage () {
let pageId = 'main';
if (window.location.hash.length > 1) {
pageId = window.location.hash.slice(1);
}
if (pageId === 'main') {
document.getElementsByTagName('body')[0].innerHTML = mainContent({
visualizations
});
} else {
let properties = visMap[pageId];
document.getElementsByTagName('body')[0].innerHTML = visContent(
properties
);
let el = document.getElementById('vis-element');
let vis = new candela.components[properties.component](
el,
datasets[properties.data],
properties.options
);
vis.render();
window.addResizeListener(el, () => vis.render());
}
}
window.addEventListener('load', () => {
showPage();
window.addEventListener('hashchange', showPage, false);
});
|
Make view-port bigger, disable JavaScript.
|
var fs = require('fs'),
page = new WebPage(),
address, output, size;
page.settings.userAgent = 'Portrayal (https://github.com/engagedc/portrayal) 1.0.0';
page.settings.javascriptEnabled = false;
if (phantom.args.length < 2 || phantom.args.length > 3) {
console.log('Usage: rasterize.js URL filename');
phantom.exit();
} else {
address = phantom.args[0];
output = phantom.args[1];
page.viewportSize = { width: 1400, height: 800 };
page.onConsoleMessage = function(msg) { console.log(msg); };
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 350);
}
});
}
|
var fs = require('fs'),
page = new WebPage(),
address, output, size;
page.settings.userAgent = 'Portrayal (https://github.com/engagedc/portrayal) 1.0.0';
if (phantom.args.length < 2 || phantom.args.length > 3) {
console.log('Usage: rasterize.js URL filename');
phantom.exit();
} else {
address = phantom.args[0];
output = phantom.args[1];
page.viewportSize = { width: 1280, height: 600 };
page.onConsoleMessage = function(msg) { console.log(msg); };
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 350);
}
});
}
|
Update Consent Dto to have shareSensitivityCategoriesEnabled attribute
#14280 - As a developer I will make consent share/not share type configurable at Deployment Time to support patient UI - Backend
|
package gov.samhsa.c2s.c2suiapi.infrastructure.dto;
import gov.samhsa.c2s.common.validator.constraint.PresentOrFuture;
import lombok.Data;
import org.hibernate.validator.constraints.ScriptAssert;
import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
@Data
@ScriptAssert(
lang = "javascript",
alias = "_",
script = "_.startDate != null && _.endDate != null && _.startDate.isBefore(_.endDate)",
message = "consent end date must be after consent start date")
public class ConsentDto {
private Long id;
@NotNull
@Future
private LocalDate endDate;
@Valid
@NotNull
private IdentifiersDto fromProviders;
@Valid
@NotNull
private IdentifiersDto purposes;
@Valid
@NotNull
private IdentifiersDto sensitivityCategories;
@NotNull
@PresentOrFuture
private LocalDate startDate;
@Valid
@NotNull
private IdentifiersDto toProviders;
@NotNull
private boolean shareSensitivityCategoriesEnabled;
}
|
package gov.samhsa.c2s.c2suiapi.infrastructure.dto;
import gov.samhsa.c2s.common.validator.constraint.PresentOrFuture;
import lombok.Data;
import org.hibernate.validator.constraints.ScriptAssert;
import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
@Data
@ScriptAssert(
lang = "javascript",
alias = "_",
script = "_.startDate != null && _.endDate != null && _.startDate.isBefore(_.endDate)",
message = "consent end date must be after consent start date")
public class ConsentDto {
private Long id;
@NotNull
@Future
private LocalDate endDate;
@Valid
@NotNull
private IdentifiersDto fromProviders;
@Valid
@NotNull
private IdentifiersDto sharePurposes;
@Valid
@NotNull
private IdentifiersDto shareSensitivityCategories;
@NotNull
@PresentOrFuture
private LocalDate startDate;
@Valid
@NotNull
private IdentifiersDto toProviders;
}
|
Make home controller loading future grid window(s)
|
<?php
/**
* Scheduler Home controller
*/
class SchedulerHomeManagerController extends SchedulerManagerController {
/**
* The pagetitle to put in the <title> attribute.
* @return null|string
*/
public function getPageTitle() {
return $this->modx->lexicon('scheduler');
}
/**
* Register all the needed javascript files.
*/
public function loadCustomCssJs() {
$this->addCss($this->scheduler->config['cssUrl'].'mgr.css');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/windows.tasks.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/grid.tasks.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/windows.future.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/grid.future.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/grid.history.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/panels/home.js');
$this->addLastJavascript($this->scheduler->config['jsUrl'].'mgr/sections/home.js');
}
}
|
<?php
/**
* Scheduler Home controller
*/
class SchedulerHomeManagerController extends SchedulerManagerController {
/**
* The pagetitle to put in the <title> attribute.
* @return null|string
*/
public function getPageTitle() {
return $this->modx->lexicon('scheduler');
}
/**
* Register all the needed javascript files.
*/
public function loadCustomCssJs() {
$this->addCss($this->scheduler->config['cssUrl'].'mgr.css');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/windows.tasks.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/grid.tasks.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/grid.history.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/widgets/grid.future.js');
$this->addJavascript($this->scheduler->config['jsUrl'].'mgr/panels/home.js');
$this->addLastJavascript($this->scheduler->config['jsUrl'].'mgr/sections/home.js');
}
}
|
Switch to client side redirect
|
Router.configure({
layoutTemplate: 'layout',
notFoundTemplate: 'notFound'
});
Router.route('/', {name: 'home'});
Router.route('/why');
Router.route('/how');
Router.route('/what');
Router.route('/what/:name', {
name: 'product',
data: function() {
return Products.findOne({name: this.params.name});
},
routeName: function() {
return 'product-' + this.params.name;
}
});
Router.route('/careers');
Router.route('/careers/:name', {
name: 'job',
data: function() {
return Jobs.findOne({name: this.params.name}) || Interns.findOne({name: this.params.name});
},
routeName: function() {
return 'job-' + this.params.name;
}
});
Router.route('/styleguide/base');
Router.route('/styleguide/case-study');
Router.route('/case-studies/verso/', {
action: function() {
this.redirect('product', {name: 'verso'});
}
});
|
Router.configure({
layoutTemplate: 'layout',
notFoundTemplate: 'notFound'
});
Router.route('/', {name: 'home'});
Router.route('/why');
Router.route('/how');
Router.route('/what');
Router.route('/what/:name', {
name: 'product',
data: function() {
return Products.findOne({name: this.params.name});
},
routeName: function() {
return 'product-' + this.params.name;
}
});
Router.route('/careers');
Router.route('/careers/:name', {
name: 'job',
data: function() {
return Jobs.findOne({name: this.params.name}) || Interns.findOne({name: this.params.name});
},
routeName: function() {
return 'job-' + this.params.name;
}
});
Router.route('/styleguide/base');
Router.route('/styleguide/case-study');
Router.route('/case-studies/verso/', {
where: 'server',
action: function() {
this.response.writeHead(301, {Location: Router.url('product', {name: 'verso'})});
this.response.end();
}
});
|
Make it grow up to be a real ClassLoader
|
package entitygen;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
/**
* Plain File-based class loader
* @author Ian Darwin
*/
public class FileClassLoader extends ClassLoader {
private final String dir;
public FileClassLoader(String dir) {
this.dir = dir;
}
@Override
public Class<?> loadClass(String className) throws ClassNotFoundException {
String fileName = dir + "/" + className.replaceAll("\\.", "/") + ".class";
if (new File(fileName).exists()) {
return nameToClass(className, fileName);
} else {
return getSystemClassLoader().loadClass(className);
}
}
public Class<?> nameToClass(String className, String fileName) {
try (InputStream is = new FileInputStream(fileName)) {
int n = is.available();
byte[] bytes = new byte[n];
int ret = is.read(bytes, 0, n);
if (ret != n) {
throw new IOException("Expected " + n + " bytes but read " + ret);
}
ByteBuffer data = ByteBuffer.wrap(bytes);
return defineClass(className, data, null);
} catch (IOException e) {
throw new RuntimeException("Couldnt open " + className + "(" + e + ")", e);
}
}
}
|
package entitygen;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
public class FileClassLoader extends ClassLoader {
public FileClassLoader() {
// Empty
}
public Class<?> nameToClass(String className, String fileName) {
try (InputStream is = new FileInputStream(fileName);) {
int n = is.available();
byte[] bytes = new byte[n];
int ret = is.read(bytes, 0, n);
if (ret != n) {
throw new IOException("Expected " + n + " bytes but read " + ret);
}
ByteBuffer data = ByteBuffer.wrap(bytes);
return defineClass(className, data, null);
} catch (IOException e) {
throw new RuntimeException("Couldnt open " + className + "(" + e + ")", e);
}
}
}
|
Add missing steps for building schema
|
import fs from 'fs';
import path from 'path';
import schema from '../src/server/schema';
import { graphql } from 'graphql';
import { introspectionQuery, printSchema } from 'graphql/utilities';
// Save JSON of full schema introspection for Babel Relay Plugin to use
(async () => {
const result = await (graphql(schema, introspectionQuery));
if (result.errors) {
console.error(
'ERROR introspecting schema: ',
JSON.stringify(result.errors, null, 2)
);
} else {
fs.writeFileSync(
path.join(__dirname, '../src/server', 'schema.json'),
JSON.stringify(result, null, 2)
);
}
})();
// Save user readable type system shorthand of schema
fs.writeFileSync(
path.join(__dirname, '../src/server', 'schema.graphql'),
printSchema(schema)
);
|
import fs from 'fs';
import path from 'path';
import schema from '../src/server/api/schema';
import { graphql } from 'graphql';
import { introspectionQuery, printSchema } from 'graphql/utilities';
// Save JSON of full schema introspection for Babel Relay Plugin to use
(async () => {
const result = await (graphql(schema, introspectionQuery));
if (result.errors) {
console.error(
'ERROR introspecting schema: ',
JSON.stringify(result.errors, null, 2)
);
} else {
fs.writeFileSync(
path.join(__dirname, '../src/server/api', 'schema.json'),
JSON.stringify(result, null, 2)
);
}
})();
// Save user readable type system shorthand of schema
fs.writeFileSync(
path.join(__dirname, '../src/server/api', 'schema.graphql'),
printSchema(schema)
);
|
Use get/set_property rather than direct accessors
|
import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.get_property('size')
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.set_property('x', x)
icon.set_property('y', y)
|
import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.props.size
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.props.x = x
icon.props.y = y
|
Update from travis build of arcgis-dijit-drilldown
|
define(["dojo/_base/declare","./_LocatorBase"],function(a,b){return a([b],{locatorType:"ABX",resultsPickList:null,streetGrouping:["STREET_DESCRIPTION","LOCALITY","TOWN_NAME","ADMINISTRATIVE_AREA"],premiseGrouping:["PAO_TEXT","PAO_END_SUFFIX","PAO_END_NUMBER","PAO_START_SUFFIX","PAO_START_NUMBER"],streetFields:{STREET_DESCRIPTOR:"STREET_DESCRIPTION",LOCALITY_NAME:"LOCALITY_NAME",TOWN_NAME:"TOWN_NAME",ADMINISTRATIVE_AREA:"ADMINISTRATIVE_AREA"},paoFields:{PAO_TEXT:"PAO_TEXT",PAO_START_NUMBER:"PAO_START_NUMBER",PAO_START_SUFFIX:"PAO_START_SUFFIX",PAO_END_NUMBER:"PAO_END_NUMBER",PAO_END_SUFFIX:"PAO_END_SUFFIX"},saoFields:{SAO_TEXT:"SAO_TEXT",SAO_START_NUMBER:"SAO_START_NUMBER",SAO_START_SUFFIX:"SAO_START_SUFFIX",SAO_END_NUMBER:"SAO_END_NUMBER",SAO_END_SUFFIX:"SAO_END_SUFFIX"}})});
|
define(["dojo/_base/declare","./_LocatorBase"],function(a,b){return a([b],{locatorType:"ABX",resultsPickList:null,streetGrouping:["STREET_DESCRIPTION","LOCALITY_NAME","TOWN_NAME","ADMINISTRATIVE_AREA"],premiseGrouping:["PAO_TEXT","PAO_END_SUFFIX","PAO_END_NUMBER","PAO_START_SUFFIX","PAO_START_NUMBER"],streetFields:{STREET_DESCRIPTOR:"STREET_DESCRIPTION",LOCALITY_NAME:"LOCALITY_NAME",TOWN_NAME:"TOWN_NAME",ADMINISTRATIVE_AREA:"ADMINISTRATIVE_AREA"},paoFields:{PAO_TEXT:"PAO_TEXT",PAO_START_NUMBER:"PAO_START_NUMBER",PAO_START_SUFFIX:"PAO_START_SUFFIX",PAO_END_NUMBER:"PAO_END_NUMBER",PAO_END_SUFFIX:"PAO_END_SUFFIX"},saoFields:{SAO_TEXT:"SAO_TEXT",SAO_START_NUMBER:"SAO_START_NUMBER",SAO_START_SUFFIX:"SAO_START_SUFFIX",SAO_END_NUMBER:"SAO_END_NUMBER",SAO_END_SUFFIX:"SAO_END_SUFFIX"}})});
|
Make sure ext.csrf is installed with WTForms
|
import os, sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from distutils.core import setup
import wtforms
setup(
name='WTForms',
version=wtforms.__version__,
url='http://wtforms.simplecodes.com/',
license='BSD',
author='Thomas Johansson, James Crasta',
author_email='wtforms@simplecodes.com',
description='A flexible forms validation and rendering library for python web development.',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=[
'wtforms',
'wtforms.fields',
'wtforms.widgets',
'wtforms.ext',
'wtforms.ext.appengine',
'wtforms.ext.csrf',
'wtforms.ext.dateutil',
'wtforms.ext.django',
'wtforms.ext.django.templatetags',
'wtforms.ext.sqlalchemy',
]
)
|
import os, sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from distutils.core import setup
import wtforms
setup(
name='WTForms',
version=wtforms.__version__,
url='http://wtforms.simplecodes.com/',
license='BSD',
author='Thomas Johansson, James Crasta',
author_email='wtforms@simplecodes.com',
description='A flexible forms validation and rendering library for python web development.',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=[
'wtforms',
'wtforms.fields',
'wtforms.widgets',
'wtforms.ext',
'wtforms.ext.appengine',
'wtforms.ext.dateutil',
'wtforms.ext.django',
'wtforms.ext.django.templatetags',
'wtforms.ext.sqlalchemy',
]
)
|
Update test file variable names
|
const test = require('tape');
const User = require('../../../models/User');
const { connect, add, remove } = require('../../database');
test('connection to database', async (assert) => {
const actual = await connect();
const expected = 0;
assert.equal(actual, expected, 'It should connect to the database without errors');
assert.end();
});
test('adding to database', async (assert) => {
const actual = await add(User, 'sample', 'secret');
const expected = 0;
await remove(User, 'sample');
assert.equal(actual, expected, 'It should add documents to the database without errors');
assert.end();
});
test('adding duplicates to database', async (assert) => {
await add(User, 'sample', 'secret');
const actual = await add(User, 'sample', 'secret');
const expected = 2;
await remove(User, 'sample');
assert.equal(actual, expected, 'It should not add duplicate documents to the database');
assert.end();
});
|
const test = require('tape');
const User = require('../../../models/User');
const { connect, add, remove } = require('../../database');
test('connection to database', async (assert) => {
const res = await connect();
assert.equal(res, 0, 'It should connect to the database without errors');
assert.end();
});
test('adding to database', async (assert) => {
const res = await add(User, 'sample', 'secret');
// try {
await remove(User, 'sample');
// } catch (e) { assert.fail(e); }
assert.equal(res, 0, 'It should add documents to the database without errors');
assert.end();
});
test('adding duplicates to database', async (assert) => {
await add(User, 'sample', 'secret');
const res = await add(User, 'sample', 'secret');
// try {
await remove(User, 'sample');
// } catch (e) {}
assert.equal(res, 2, 'It should not add duplicate documents to the database');
assert.end();
});
|
Revert "more fix are coming"
This reverts commit 39e778da34704836de55572f4e08509565a6e613.
|
<?php
/**
*
* @author Ananaskelly
*/
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\SearchGameFormRequest;
use Carbon\Carbon;
use Auth;
use App\GameType;
use App\Game;
use App\UserGame;
class GameController extends BaseController
{
/**
* Show the form for games params.
*
* @return
*/
public function search()
{
$gameTypesColumn = array_column(GameType::all('type_name')->toArray(), 'type_name');
$gameTypes = array_combine($gameTypesColumn, $gameTypesColumn);
return view('search', compact('gameTypes'));
}
/**
* Find game with params or create new game
*
* @return void
*/
public function create(SearchGameFormRequest $request)
{
Game::createGame($request->type, $request->status);
return redirect('/home');
}
}
|
<?php
/**
*
* @author Ananaskelly
*/
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\SearchGameFormRequest;
use Carbon\Carbon;
use Auth;
use App\GameType;
use App\Game;
use App\UserGame;
class GameController extends BaseController
{
/**
* Show the form for games params.
*
* @return
*/
public function search()
{
$gameTypesColumn = array_column(GameType::all('type_name')->toArray(), 'type_name');
$gameTypes = array_combine($gameTypesColumn, $gameTypesColumn);
$gameType = GameType::all('type_name', 'id');
return view('search', compact('gameTypes'));
}
/**
* Find game with params or create new game
*
* @return void
*/
public function create(SearchGameFormRequest $request)
{
$gameType = GameType::where('type_name', '=', $request->type)->first();
Game::createGame($gameType, $request->status);
return redirect('/home');
}
}
|
Add logger to auth constructor
|
import path from 'path';
export default function (container) {
container.set('remote-registry', function () {
let Route = require('../routes/auth-user-add').default;
return new Route();
});
container.set('express', function () {
let express = require('express');
let routes = require('../routes').default;
let app = express();
app.set('env', process.env.NODE_ENV || 'production');
routes(app, container);
return app;
});
container.set('validator', function () {
let PackageValidator = require('../util/validator').default;
return new PackageValidator(container.get('storage'));
});
container.set('auth', function () {
let Auth = require('../auth/index').default;
return new Auth(container.get('auth-adapter'), container.get('config'), container.get('logger'));
});
container.set('auth-adapter', function () {
let AuthAdapter;
if (container.get('config').auth.adapter === '/auth/json-db') {
AuthAdapter = require(path.join(__dirname, '..', container.get('config').auth.adapter)).default;
} else {
AuthAdapter = require(container.get('config').auth.adapter).default;
}
return new AuthAdapter(container.get('config'));
});
container.set('proxy', function () {
let Util = require('../util/package-proxy').default;
return new Util(container.get('config').proxyUrl);
});
}
|
import path from 'path';
export default function (container) {
container.set('remote-registry', function () {
let Route = require('../routes/auth-user-add').default;
return new Route();
});
container.set('express', function () {
let express = require('express');
let routes = require('../routes').default;
let app = express();
app.set('env', process.env.NODE_ENV || 'production');
routes(app, container);
return app;
});
container.set('validator', function () {
let PackageValidator = require('../util/validator').default;
return new PackageValidator(container.get('storage'));
});
container.set('auth', function () {
let Auth = require('../auth/index').default;
return new Auth(container.get('auth-adapter'), container.get('config'));
});
container.set('auth-adapter', function () {
let AuthAdapter;
if (container.get('config').auth.adapter === '/auth/json-db') {
AuthAdapter = require(path.join(__dirname, '..', container.get('config').auth.adapter)).default;
} else {
AuthAdapter = require(container.get('config').auth.adapter).default;
}
return new AuthAdapter(container.get('config'));
});
container.set('proxy', function () {
let Util = require('../util/package-proxy').default;
return new Util(container.get('config').proxyUrl);
});
container.set('logger', function () {
let Logger = require('../util/logger').default;
return new Logger();
});
}
|
Fix typo for Document model
|
import Attachment from "./models/attachment"
import AttachmentManager from "./models/attachment_manager"
import AttachmentPiece from "./models/attachment_piece"
import Block from "./models/block"
import Composition from "./models/composition"
import Document from "./models/document"
import Editor from "./models/editor"
import HTMLParser from "./models/html_parser"
import HTMLSanitizer from "./models/html_sanitizer"
import LineBreakInsertion from "./models/line_break_insertion"
import LocationMapper from "./models/location_mapper"
import ManagedAttachment from "./models/managed_attachment"
import Piece from "./models/piece"
import PointMapper from "./models/point_mapper"
import SelectionManager from "./models/selection_manager"
import SplittableList from "./models/splittable_list"
import StringPiece from "./models/string_piece"
import Text from "./models/text"
import UndoManager from "./models/undo_manager"
export default {
Attachment,
AttachmentManager,
AttachmentPiece,
Block,
Composition,
Document,
Editor,
HTMLParser,
HTMLSanitizer,
LineBreakInsertion,
LocationMapper,
ManagedAttachment,
Piece,
PointMapper,
SelectionManager,
SplittableList,
StringPiece,
Text,
UndoManager,
}
|
import Attachment from "./models/attachment"
import AttachmentManager from "./models/attachment_manager"
import AttachmentPiece from "./models/attachment_piece"
import Block from "./models/block"
import Composition from "./models/composition"
import Cocument from "./models/document"
import Editor from "./models/editor"
import HTMLParser from "./models/html_parser"
import HTMLSanitizer from "./models/html_sanitizer"
import LineBreakInsertion from "./models/line_break_insertion"
import LocationMapper from "./models/location_mapper"
import ManagedAttachment from "./models/managed_attachment"
import Piece from "./models/piece"
import PointMapper from "./models/point_mapper"
import SelectionManager from "./models/selection_manager"
import SplittableList from "./models/splittable_list"
import StringPiece from "./models/string_piece"
import Text from "./models/text"
import UndoManager from "./models/undo_manager"
export default {
Attachment,
AttachmentManager,
AttachmentPiece,
Block,
Composition,
Cocument,
Editor,
HTMLParser,
HTMLSanitizer,
LineBreakInsertion,
LocationMapper,
ManagedAttachment,
Piece,
PointMapper,
SelectionManager,
SplittableList,
StringPiece,
Text,
UndoManager,
}
|
Call the function back so that Gulp knows when the task completed.
|
var gulp = require("gulp");
var CFG = require("./utils/config.js");
var $ = require("gulp-load-plugins")();
var exec = require("child_process").exec;
var path = require("path");
var pkg = require(path.join("..", CFG.FILE.config.pkg));
/**
* style:doc
* Generates a living styleguide from the `doc` comments from all `lib/style/*.scss`.
* @see trulia.github.io/hologram
*/
gulp.task("style:doc", ["style:compile"], function(callback) {
var hologramProcess = exec([
"bundle",
"exec",
"hologram",
"--config",
CFG.FILE.config.hologram
].join(" "), function(err, stdout, stderr) {
$.util.log("[style:doc] stdout:", stdout);
$.util.log("[style:doc] stderr: ", stderr);
if(null !== err) {
$.util.log("[style:doc] err: ", err);
}
callback();
});
});
|
var gulp = require("gulp");
var CFG = require("./utils/config.js");
var $ = require("gulp-load-plugins")();
var exec = require("child_process").exec;
var path = require("path");
var pkg = require(path.join("..", CFG.FILE.config.pkg));
/**
* style:doc
* Generates a living styleguide from the `doc` comments from all `lib/style/*.scss`.
* @see trulia.github.io/hologram
*/
gulp.task("style:doc", ["style:compile"], function(callback) {
var hologramProcess = exec([
"bundle",
"exec",
"hologram",
"--config",
CFG.FILE.config.hologram
].join(" "), function(err, stdout, stderr) {
$.util.log("[style:doc] stdout:", stdout);
$.util.log("[style:doc] stderr: ", stderr);
if(null !== err) {
$.util.log("[style:doc] err: ", err);
}
});
});
|
Return types in page bundle
|
<?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ProducerBundle\Manager\Front;
use WellCommerce\Bundle\CoreBundle\Manager\Front\AbstractFrontManager;
use WellCommerce\Component\DataSet\Conditions\Condition\Eq;
use WellCommerce\Component\DataSet\Conditions\ConditionsCollection;
/**
* Class ProducerManager
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ProducerManager extends AbstractFrontManager
{
/**
* Returns a collection of dynamic conditions
*
* @return ConditionsCollection
*/
public function getCurrentProducerConditions() : ConditionsCollection
{
$conditions = new ConditionsCollection();
$conditions->add(new Eq('producerId', $this->getProducerContext()->getCurrentProducerIdentifier()));
return $conditions;
}
}
|
<?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ProducerBundle\Manager\Front;
use WellCommerce\Bundle\CoreBundle\Manager\Front\AbstractFrontManager;
use WellCommerce\Component\DataSet\Conditions\Condition\Eq;
use WellCommerce\Component\DataSet\Conditions\ConditionsCollection;
/**
* Class ProducerManager
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ProducerManager extends AbstractFrontManager
{
/**
* Returns a collection of dynamic conditions
*
* @return ConditionsCollection
*/
public function getCurrentProducerConditions()
{
$conditions = new ConditionsCollection();
$conditions->add(new Eq('producerId', $this->getProducerContext()->getCurrentProducerIdentifier()));
return $conditions;
}
}
|
Add exclude books cart page
|
// ==UserScript==
// @name Rakuten Mail Magazine Unchecker
// @namespace https://github.com/takamario/gm_script
// @description Rakuten Mail Magazine Unchecker
// @include https://order.step.rakuten.co.jp/rms/mall/basket/vc*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorder/*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorderquicknormalize/*
// @include https://books.step.rakuten.co.jp/rms/mall/book/bs*
// @exclude https://books.step.rakuten.co.jp/rms/mall/book/bs/Cart*
// ==/UserScript==
(function() {
var i, ipt = document.getElementsByTagName('input');
for (i in ipt) {
if (ipt[i].type === 'checkbox') {
ipt[i].checked = '';
}
}
})();
|
// ==UserScript==
// @name Rakuten Mail Magazine Unchecker
// @namespace https://github.com/takamario/gm_script
// @description Rakuten Mail Magazine Unchecker
// @include https://order.step.rakuten.co.jp/rms/mall/basket/vc*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorder/*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorderquicknormalize/*
// @include https://books.step.rakuten.co.jp/rms/mall/book/bs*
// ==/UserScript==
(function() {
var i, ipt = document.getElementsByTagName('input');
for (i in ipt) {
if (ipt[i].type === 'checkbox') {
ipt[i].checked = '';
}
}
})();
|
Return Midgard.Connection if one is opened. None otherwise
|
# coding=utf-8
import sys
import struct
import unittest
from test_000_config import TestConfig
from gi.repository import Midgard, GObject
class TestConnection(Midgard.Connection):
def __init__(self):
Midgard.init()
Midgard.Connection.__init__(self)
@staticmethod
def openConnection():
config = TestConfig()
mgd = Midgard.Connection()
if mgd.open_config(config) is True:
return mgd
print mgd.get_error_string()
return None
class TestMethods(unittest.TestCase):
def testOpenConfig(self):
config = TestConfig()
mgd = TestConnection()
self.assertEqual(mgd.get_error_string(), "MGD_ERR_OK")
self.assertTrue(mgd.open_config(config))
self.assertEqual(mgd.get_error_string(), "MGD_ERR_OK")
def testInheritance(self):
mgd = TestConnection()
self.assertIsInstance(mgd, GObject.GObject)
if __name__ == "__main__":
unittest.main()
|
# coding=utf-8
import sys
import struct
import unittest
from test_000_config import TestConfig
from gi.repository import Midgard, GObject
class TestConnection(Midgard.Connection):
def __init__(self):
Midgard.init()
Midgard.Connection.__init__(self)
@staticmethod
def openConnection():
config = TestConfig()
mgd = Midgard.Connection()
mgd.open_config(config)
return mgd
class TestMethods(unittest.TestCase):
def testOpenConfig(self):
config = TestConfig()
mgd = TestConnection()
self.assertEqual(mgd.get_error_string(), "MGD_ERR_OK")
self.assertTrue(mgd.open_config(config))
self.assertEqual(mgd.get_error_string(), "MGD_ERR_OK")
def testInheritance(self):
mgd = TestConnection()
self.assertIsInstance(mgd, GObject.GObject)
if __name__ == "__main__":
unittest.main()
|
Add ctrlAddItem function. Change some comments
|
/*
* Developed by Radu Puspana
* Date August 2017
* Version 1.0
*/
// module that handles the budget data using the module pattern
// IFEE creates a new scope. IFEE creates a closure for the vars/functions/objects
var budgetController = (function() {
// some code
})();
// UI module manipulates the UI of the app
var uiController = (function() {
// some code
})();
// App controller for communicating between the budgetController and the UIconroller
var controller = (function(budgetCtrl, UIctrl) {
var ctrlAddItem = function() {
// get the field input data(expense or income)
// add the item to the budget controller
// add the new item to the UI
// update the budget taking into account the expense/budget just entered
// display the newly calculated budget on the UI
console.log("You pressed enter and an item will be added to one of the tables and the budget will be updated")
}
// register click event for the button with the tick sign
document.querySelector(".add__btn").addEventListener("click", ctrlAddItem, false);
// register Enter keypress event for the global object. Used only for the ENTER key
document.addEventListener("keypress", function(event) {
// use event.which to assure comptatibility with IE 9..11, Edge 14, UC Browser for Android 11.4
// code 13 is returned when the "ENTER" key is pressed
if (event.key === "Enter" || event.which === 13) { ctrlAddItem(); }
}, false);
})(budgetController, uiController);
|
/*
* Developed by Radu Puspana
* Date August 2017
* Version 1.0
*/
// module that handles the budget data using the module pattern
// IFEE creates a new scope. IFEE creates a closure for the vars/functions/objects
var budgetController = (function() {
// some code
})();
// UI module manipulates the UI of the app
var uiController = (function() {
// some code
})();
// App controller for communicating between the budgetController and the UIconroller
var controller = (function(budgetCtrl, UIctrl) {
document.querySelector(".add__btn").addEventListener("click", function() {
console.log("button with .add__btn was clicked");
// get the field input data(expense or income)
// add the item to the budget controller
// add the new item to the UI
// update the budget taking into account the expense/budget just entered
// display the newly calculated budget on the UI
}, false);
// click event happens on the page, not on a specific elem. Used only for the ENTER key
document.addEventListener("keypress", function(event) {
}, false);
})(budgetController, uiController);
|
Make email lower case before checking exclusions
|
<?php
include("file.php");
$experiment = new Experiment($_REQUEST['exp']);
$page_header = $experiment->getName();
if ($experiment->getStatus() != 'open') {
$page = 'fully_subscribed';
}
else {
$excluded_email_addresses = $experiment->getExclusionEmails();
foreach ($experiment->getExclusions() as $exclusion) {
$alt_experiment = new Experiment($exclusion);
$excluded_email_addresses = array_merge($excluded_email_addresses, $alt_experiment->getExclusionEmails());
}
if (in_array(strtolower($_REQUEST['email']), $excluded_email_addresses)) {
$page = 'not_eligible';
$user = new User($experiment->owner);
}
else {
if ($experiment->getPerSlot() > 1) {
$additional_message = "<strong>This experiment requires {$experiment->getPerSlot()} participants per timeslot.</strong> You will not be guaranteed a place on the experiment until {$experiment->getPerSlot()} people have signed up for your slot. If possible, please choose a slot that someone else has already signed up for (highlighted in green). You’ll receive an email to confirm when your slot has been filled.";
}
}
}
?>
|
<?php
include("file.php");
$experiment = new Experiment($_REQUEST['exp']);
$page_header = $experiment->getName();
if ($experiment->getStatus() != 'open') {
$page = 'fully_subscribed';
}
else {
$excluded_email_addresses = $experiment->getExclusionEmails();
foreach ($experiment->getExclusions() as $exclusion) {
$alt_experiment = new Experiment($exclusion);
$excluded_email_addresses = array_merge($excluded_email_addresses, $alt_experiment->getExclusionEmails());
}
if (in_array($_REQUEST['email'], $excluded_email_addresses)) {
$page = 'not_eligible';
$user = new User($experiment->owner);
}
else {
if ($experiment->getPerSlot() > 1) {
$additional_message = "<strong>This experiment requires {$experiment->getPerSlot()} participants per timeslot.</strong> You will not be guaranteed a place on the experiment until {$experiment->getPerSlot()} people have signed up for your slot. If possible, please choose a slot that someone else has already signed up for (highlighted in green). You’ll receive an email to confirm when your slot has been filled.";
}
}
}
?>
|
Fix typo in unit test
|
/* eslint-env jasmine */
var editTypes = require('../helpers/edit-types')
var makeEditableElement = require('../helpers/make-editable-element')
var Edited = require('../../..')
describe('`detach` method', function () {
it('detaches the instance\'s event listener from the instance\'s element',
function () {
var element = makeEditableElement()
var onSensible = jasmine.createSpy()
var onAny = jasmine.createSpy()
var edited = new Edited(element, onSensible, onAny)
// just checking that the callback works
editTypes.characterAddition.triggerFunc.call(edited)
editTypes.space.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
// checking that `detach` method works
edited.detach()
editTypes.backwardsRemoval.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
})
})
|
/* eslint-env jasmine */
var editTypes = require('../helpers/edit-types')
var makeEditableElement = ('../helpers/make-editable-element')
var Edited = require('../../..')
describe('`detach` method', function () {
it('detaches the instance\'s event listener from the instance\'s element',
function () {
var element = makeEditableElement()
var onSensible = jasmine.createSpy()
var onAny = jasmine.createSpy()
var edited = new Edited(element, onSensible, onAny)
// just checking that the callback works
editTypes.characterAddition.triggerFunc.call(edited)
editTypes.space.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
// checking that `detach` method works
edited.detach()
editTypes.backwardsRemoval.triggerFunc.call(edited)
expect(onSensible.calls.count()).toBe(1)
expect(onAny.calls.count()).toBe(2)
})
})
|
Use a custom logger to not display timestamp
|
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
)
var logger = log.New(os.Stderr, "", 0)
func main() {
process(os.Args[1:], os.Stdout)
}
func process(args []string, output io.Writer) {
if len(args) == 0 {
missingArgument()
}
candidate := args[0]
if candidate == "" {
missingArgument()
}
fmt.Fprint(output, tryGetTemplate(candidate))
}
func tryGetTemplate(template string) string {
resp := get(fmt.Sprintf("https://raw.githubusercontent.com/github/gitignore/master/%s.gitignore", template))
defer resp.Body.Close()
if resp.StatusCode == 404 {
resp = get(fmt.Sprintf("https://raw.githubusercontent.com/github/gitignore/master/Global/%s.gitignore", template))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Fatal(err)
}
return string(body)
}
func get(url string) (resp *http.Response) {
resp, err := http.Get(url)
if err != nil {
logger.Fatal(err)
}
return resp
}
func missingArgument() {
logger.Fatal("Mandatory argument missing, use: chtignore <template>")
}
|
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
process(os.Args[1:], os.Stdout)
}
func process(args []string, output io.Writer) {
if len(args) == 0 {
log.Fatal("Mandatory argument missing: chtignore Java")
}
candidate := args[0]
if candidate == "" {
log.Fatal("Mandatory argument missing: chtignore Java")
}
fmt.Fprint(output, tryGetTemplate(candidate))
}
func tryGetTemplate(template string) string {
resp := get(fmt.Sprintf("https://raw.githubusercontent.com/github/gitignore/master/%s.gitignore", template))
defer resp.Body.Close()
if resp.StatusCode == 404 {
resp = get(fmt.Sprintf("https://raw.githubusercontent.com/github/gitignore/master/Global/%s.gitignore", template))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
return string(body)
}
func get(url string) (resp *http.Response) {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
return resp
}
|
Fix apiCall params not being set to object
|
// BASIC JSON RESPONSE EXAMPLE
// FEATURES DEMONSTRATED:
// "magic" adding :id route wildcard to API path ending in / (common REST paradigm)
// adding API params at request time
// pre and post API business logic
// creting res.renderData object which is sent to client as JSON response
// for more demonstration of yukon features - see kitchenSink.js, homePage.js, getSpecifcData.js, 404.js, submitForm.js
module.exports = function(app) {
return {
// routes can be a string, RegExp or array of either (to match multiple routes)
route : '/json/getData/:id',
// MAGIC ALERT: if the api path ends in a / the framework appends :id (req.params.id) from the route
apiCalls: [
{path: '/api/getdata/'},
],
preProcessor: function(req, res) {
this.debug('preProcessor called');
// business logic before API calls are made
this.apiCalls[0].params = {myParam: req.query.myParam}; // in real life don't forget to sanitize query params!
},
postProcessor: function(req, res) {
this.debug('postProcessor called');
// business logic after all API calls return, before sending res.renderData to client in res.send()
// sent as JSON to client
res.renderData = {
systemMsg: res.locals.data1.systemMsg,
msg: res.locals.data1.msg
};
}
};
};
|
// BASIC JSON RESPONSE EXAMPLE
// FEATURES DEMONSTRATED:
// "magic" adding :id route wildcard to API path ending in / (common REST paradigm)
// adding API params at request time
// pre and post API business logic
// creting res.renderData object which is sent to client as JSON response
// for more demonstration of yukon features - see kitchenSink.js, homePage.js, getSpecifcData.js, 404.js, submitForm.js
module.exports = function(app) {
return {
// routes can be a string, RegExp or array of either (to match multiple routes)
route : '/json/getData/:id',
// MAGIC ALERT: if the api path ends in a / the framework appends :id (req.params.id) from the route
apiCalls: [
{path: '/api/getdata/'},
],
preProcessor: function(req, res) {
this.debug('preProcessor called');
// business logic before API calls are made
this.apiCalls[0].params = req.query.myParam; // in real life don't forget to sanitize query params!
},
postProcessor: function(req, res) {
this.debug('postProcessor called');
// business logic after all API calls return, before sending res.renderData to client in res.send()
// sent as JSON to client
res.renderData = {
systemMsg: res.locals.data1.systemMsg,
msg: res.locals.data1.msg
};
}
};
};
|
Use the C Loader/Dumper when available
|
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import OrderedDict
import yaml
# Adapted from http://stackoverflow.com/a/21912744/812183
class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)):
pass
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
lambda loader, node: OrderedDict(loader.construct_pairs(node)),
)
class OrderedDumper(getattr(yaml, 'CSafeDumper', yaml.SafeDumper)):
pass
OrderedDumper.add_representer(
OrderedDict,
lambda dumper, data: dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items(),
),
)
def ordered_load(stream):
"""yaml.load which respects order for dictionaries in the yaml file.
:param stream: string or streamlike object.
"""
return yaml.load(stream, Loader=OrderedLoader)
def ordered_dump(obj, **kwargs):
"""yaml.dump which respects order for dictionaries in the yaml object.
:param obj: Yaml dumpable object
"""
return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
|
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import OrderedDict
import yaml
# Adapted from http://stackoverflow.com/a/21912744/812183
class OrderedLoader(yaml.loader.Loader):
pass
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
lambda loader, node: OrderedDict(loader.construct_pairs(node)),
)
class OrderedDumper(yaml.dumper.SafeDumper):
pass
OrderedDumper.add_representer(
OrderedDict,
lambda dumper, data: dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items(),
),
)
def ordered_load(stream):
"""yaml.load which respects order for dictionaries in the yaml file.
:param stream: string or streamlike object.
"""
return yaml.load(stream, Loader=OrderedLoader)
def ordered_dump(obj, **kwargs):
"""yaml.dump which respects order for dictionaries in the yaml object.
:param obj: Yaml dumpable object
"""
return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
|
Change thumbnails types to be map of structs
|
package main
import (
"encoding/json"
"io/ioutil"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type ThumbnailSize struct {
Width uint
Height uint
}
var ThumbnailSizes = map[string]ThumbnailSize{
"small": ThumbnailSize{100, 100},
"large": ThumbnailSize{500, 500},
}
type Config struct {
SourceFolderPath string `json:"source_folder_path"`
DestinationFolderPath string `json:"destination_folder_path"`
ThumbnailsFolderPath string `json:"thumbnails_folder_path"`
DatabaseConnectionString string `json:"database_connection_string"`
}
func LoadConfig(configPath string) (Config, error) {
var config Config
file, err := ioutil.ReadFile(configPath)
if err != nil {
return config, err
}
err = json.Unmarshal(file, &config)
return config, err
}
func SetupDatabase(connectionString string) gorm.DB {
db, err := gorm.Open("postgres", connectionString)
if err != nil {
panic("Unable to open database")
}
db.AutoMigrate(&Photo{}, &SimilarPhoto{})
return db
}
|
package main
import (
"encoding/json"
"io/ioutil"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
const Thumbnails = map[string][]int{
"small": []int{100, 100},
"large": []int{500, 500},
}
type Config struct {
SourceFolderPath string `json:"source_folder_path"`
DestinationFolderPath string `json:"destination_folder_path"`
ThumbnailsFolderPath string `json:"thumbnails_folder_path"`
DatabaseConnectionString string `json:"database_connection_string"`
}
func LoadConfig(configPath string) (Config, error) {
var config Config
file, err := ioutil.ReadFile(configPath)
if err != nil {
return config, err
}
err = json.Unmarshal(file, &config)
return config, err
}
func SetupDatabase(connectionString string) gorm.DB {
db, err := gorm.Open("postgres", connectionString)
if err != nil {
panic("Unable to open database")
}
db.AutoMigrate(&Photo{}, &SimilarPhoto{})
return db
}
|
Use pathlib in the target
|
#!/usr/bin/env python
import json
from pathlib import Path
from os import scandir
from os.path import (
join as path_join,
basename as to_basename,
splitext,
exists
)
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = Path('targets')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir()
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_path))
txt_path = _TARGETS_DIR_PATH / '{}.txt'.format(json_path.stem)
if txt_path.exists():
l.info('Existed and skip {}'.format(txt_path))
return
with json_path.open() as f:
d = json.load(f)
push_score_sum = sum(push_d['score'] for push_d in d['push_ds'])
with txt_path.open('w') as f:
f.write(str(push_score_sum))
l.info('Wrote into {}'.format(txt_path))
def generate_all(preprocessed_dir_path_str):
for path in Path(preprocessed_dir_path_str).iterdir():
generate_target_from(path)
if __name__ == '__main__':
generate_all('preprocessed')
|
#!/usr/bin/env python
import json
from os import scandir
from os.path import (
join as path_join,
basename as to_basename,
splitext,
exists
)
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = 'targets'
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_path))
basename = to_basename(json_path)
root, ext = splitext(basename)
txt_path = path_join(_TARGETS_DIR_PATH, '{}.txt'.format(root))
if exists(txt_path):
l.info('Existed and skip {}'.format(txt_path))
return
with open(json_path) as f:
d = json.load(f)
push_score_sum = sum(push_d['score'] for push_d in d['push_ds'])
with ptt_core.mkdir_n_open(txt_path, 'w') as f:
f.write(str(push_score_sum))
l.info('Wrote into {}'.format(txt_path))
def generate_all(preprocessed_dir_path):
for dir_entry in scandir(preprocessed_dir_path):
generate_target_from(dir_entry.path)
if __name__ == '__main__':
generate_all('preprocessed')
|
Replace --noinput with interactive=False in syncdb command call
|
from django.conf import settings
from django.core.management import call_command
def pytest_configure():
settings.configure(
ROOT_URLCONF='tests.urls',
ALLOWED_HOSTS=['testserver'],
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test'
}
},
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'rest_framework',
'tests',
]
)
try:
from django import setup
except ImportError:
call_command('syncdb', interactive=False)
else:
setup()
call_command('migrate')
|
from django.conf import settings
from django.core.management import call_command
def pytest_configure():
settings.configure(
ROOT_URLCONF='tests.urls',
ALLOWED_HOSTS=['testserver'],
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test'
}
},
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'rest_framework',
'tests',
]
)
try:
from django import setup
except ImportError:
call_command('syncdb', '--noinput')
else:
setup()
call_command('migrate')
|
Fix format of console_scripts and spelling of version
|
from setuptools import setup
import sys
# The argparse module was introduced in python 2.7 or python 3.2
REQUIRES = ["argparse"] if sys.version[:3] in ('2.6', '3.0', '3.1') else []
REQUIRES = REQUIRES + ["wand>=0.4.0"]
setup(
version='0.0.1',
name="anki-slides-import",
author="Utkarsh Upadhyay",
author_email="musically.ut@gmail.com",
description = "Convert text notes and slides into an Anki deck.",
license="MIT",
keywords="anki slides deck import",
install_requires=REQUIRES,
url="https://github.com/musically-ut/anki-slides-import",
packages=["slidesimport"],
entry_points={ "console_scripts": [ "slides2anki = slidesimport.slidesimport:run" ]},
classifiers = [
"License :: OSI Approved :: MIT License",
"Intended Audience :: Science/Research",
"Development Status :: 3 - Alpha",
"Operating System :: OS Independent",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.7",
"Natural Language :: English"
],
)
|
from setuptools import setup
import sys
# The argparse module was introduced in python 2.7 or python 3.2
REQUIRES = ["argparse"] if sys.version[:3] in ('2.6', '3.0', '3.1') else []
REQUIRES = REQUIRES + ["wand>=0.4.0"]
setup(
varsion='0.0.1',
name="anki-slides-import",
author="Utkarsh Upadhyay",
author_email="musically.ut@gmail.com",
description = "Convert text notes and slides into an Anki deck.",
license="MIT",
keywords="anki slides deck import",
install_requires=REQUIRES,
url="https://github.com/musically-ut/anki-slides-import",
packages=["slidesimport"],
entry_points={ "console_script": [ "slides2anki = slidesimport.run" ]},
classifiers = [
"License :: OSI Approved :: MIT License",
"Intended Audience :: Science/Research",
"Development Status :: 3 - Alpha",
"Operating System :: OS Independent",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.7",
"Natural Language :: English"
],
)
|
Add branch completions to checkout command
|
package ee.shy.cli.command;
import ee.shy.cli.Command;
import ee.shy.cli.HelptextBuilder;
import ee.shy.core.Repository;
import java.io.IOException;
/**
* A command to checkout.
*/
public class CheckoutCommand implements Command {
@Override
public void execute(String[] args) throws IOException {
Repository repository = Repository.newExisting();
repository.checkout(args[0]);
}
@Override
public String getHelp() {
return new HelptextBuilder()
.addWithArgs("<String>", "Checkouts to given commit or branch")
.addDescription("This command checkouts to commit with hash of <string>.")
.create();
}
@Override
public String getHelpBrief() {
return "Checkouts to given commit.";
}
@Override
public String[] getCompletion(String[] args) throws IOException {
Repository repository = Repository.newExisting();
return repository.getBranches().keySet().toArray(new String[0]);
}
}
|
package ee.shy.cli.command;
import ee.shy.cli.Command;
import ee.shy.cli.HelptextBuilder;
import ee.shy.core.Repository;
import java.io.IOException;
/**
* A command to checkout.
*/
public class CheckoutCommand implements Command {
@Override
public void execute(String[] args) throws IOException {
Repository repository = Repository.newExisting();
repository.checkout(args[0]);
}
@Override
public String getHelp() {
return new HelptextBuilder()
.addWithArgs("<String>", "Checkouts to given commit or branch")
.addDescription("This command checkouts to commit with hash of <string>.")
.create();
}
@Override
public String getHelpBrief() {
return "Checkouts to given commit.";
}
}
|
Rename functions to minimize verbosity
|
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
// You can use CoffeeScript in this file: http://coffeescript.org/
ListenFor = (function() {
var displaySection = function(section) {
$(section).on('click', '.interest', function(event) {
$('.main-content').hide('slow');
$(this).siblings('.main-content').show('slow');
});
}
var description = function() {
$('.description').on('click', function(event) {
event.preventDefault();
$(this).parent().siblings().removeClass('hidden');
})
}
var less = function() {
$('.hidden').on('click', '.less', function(event) {
event.preventDefault();
$(this).parent().addClass('hidden');
});
}
return {
section: displaySection,
description: description,
less: less
}
})();
$(document).ready(function() {
ListenFor.section('#projects');
ListenFor.section('#blog');
ListenFor.section('#resume');
ListenFor.section('#about');
ListenFor.section('#contact');
ListenFor.description();
ListenFor.less();
});
|
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
// You can use CoffeeScript in this file: http://coffeescript.org/
ListenFor = (function() {
var displaySectionListener = function(section) {
$(section).on('click', '.interest', function(event) {
$('.main-content').hide('slow');
$(this).siblings('.main-content').show('slow');
});
}
var descriptionListener = function() {
$('.description').on('click', function(event) {
event.preventDefault();
$(this).parent().siblings().removeClass('hidden');
// still need to implement a way to hide the description
})
}
var lessListener = function() {
$('.hidden').on('click', '.less', function(event) {
event.preventDefault();
$(this).parent().addClass('hidden');
});
}
return {
section: displaySectionListener,
description: descriptionListener,
less: lessListener
}
})();
$(document).ready(function() {
ListenFor.section('#projects');
ListenFor.section('#blog');
ListenFor.section('#resume');
ListenFor.section('#about');
ListenFor.section('#contact');
ListenFor.description();
ListenFor.less();
});
|
Use 'open' instead of 'file' (no longer available in Python 3).
|
# wwwhisper - web access control.
# Copyright (C) 2013-2022 Jan Wrobel <jan@mixedbit.org>
import os
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.decorators.cache import cache_page
from django.views.generic import View
from wwwhisper_auth import http
class Asset:
"""Stores a static file to be returned by requests."""
def __init__(self, prefix, *args):
assert prefix is not None
self.body = open(os.path.join(prefix, *args)).read()
class StaticFileView(View):
""" A view to serve a single static file."""
asset = None
@method_decorator(cache_control(private=True, max_age=60 * 60 * 5))
def get(self, request):
return self.do_get(self.asset.body)
class HtmlFileView(StaticFileView):
def do_get(self, body):
return http.HttpResponseOKHtml(body)
class JsFileView(StaticFileView):
def do_get(self, body):
return http.HttpResponseOKJs(body)
|
# wwwhisper - web access control.
# Copyright (C) 2013 Jan Wrobel <jan@mixedbit.org>
import os
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.decorators.cache import cache_page
from django.views.generic import View
from wwwhisper_auth import http
class Asset:
"""Stores a static file to be returned by requests."""
def __init__(self, prefix, *args):
assert prefix is not None
self.body = file(os.path.join(prefix, *args)).read()
class StaticFileView(View):
""" A view to serve a single static file."""
asset = None
@method_decorator(cache_control(private=True, max_age=60 * 60 * 5))
def get(self, request):
return self.do_get(self.asset.body)
class HtmlFileView(StaticFileView):
def do_get(self, body):
return http.HttpResponseOKHtml(body)
class JsFileView(StaticFileView):
def do_get(self, body):
return http.HttpResponseOKJs(body)
|
Expand type does use brush blocks.
|
<?php
declare(strict_types=1);
namespace BlockHorizons\BlockSniper\brush\types;
use BlockHorizons\BlockSniper\brush\BaseType;
use pocketmine\block\Block;
use pocketmine\math\Facing;
/*
* Expands the terrain with blocks below it.
*/
class ExpandType extends BaseType{
public const ID = self::TYPE_EXPAND;
/**
* @return \Generator
*/
public function fill() : \Generator{
$undoBlocks = [];
foreach($this->blocks as $block){
/** @var Block $block */
if($block->getId() === Block::AIR){
$closedSides = 0;
foreach(Facing::ALL as $direction){
$sideBlock = $this->side($block, $direction);
if($sideBlock->getId() !== Block::AIR){
$closedSides++;
}
}
if($closedSides >= 2){
$undoBlocks[] = $block;
}
}
}
foreach($undoBlocks as $selectedBlock){
yield $selectedBlock;
$this->putBlock($selectedBlock, $this->randomBrushBlock());
}
}
/**
* @return string
*/
public function getName() : string{
return "Expand";
}
}
|
<?php
declare(strict_types=1);
namespace BlockHorizons\BlockSniper\brush\types;
use BlockHorizons\BlockSniper\brush\BaseType;
use pocketmine\block\Block;
use pocketmine\math\Facing;
/*
* Expands the terrain with blocks below it.
*/
class ExpandType extends BaseType{
public const ID = self::TYPE_EXPAND;
/**
* @return \Generator
*/
public function fill() : \Generator{
$undoBlocks = [];
foreach($this->blocks as $block){
/** @var Block $block */
if($block->getId() === Block::AIR){
$closedSides = 0;
foreach(Facing::ALL as $direction){
$sideBlock = $this->side($block, $direction);
if($sideBlock->getId() !== Block::AIR){
$closedSides++;
}
}
if($closedSides >= 2){
$undoBlocks[] = $block;
}
}
}
foreach($undoBlocks as $selectedBlock){
yield $selectedBlock;
$this->putBlock($selectedBlock, $this->randomBrushBlock());
}
}
/**
* @return string
*/
public function getName() : string{
return "Expand";
}
/**
* @return bool
*/
public function usesBlocks() : bool{
return false;
}
}
|
Use native doc.getElementById when available
SimpleDOM doesn't have `getElementById`, but in a browser it is
more efficient to use the native `getElementById` instead of walking the
dom.
|
/*
* Implement some helpers methods for interacting with the DOM,
* be it Fastboot's SimpleDOM or a browser's version.
*/
export function getActiveElement() {
if (typeof document === 'undefined') {
return null;
} else {
return document.activeElement;
}
}
function childNodesOfElement(element) {
let children = [];
let child = element.firstChild;
while (child) {
children.push(child);
child = child.nextSibling;
}
return children;
}
export function findElementById(doc, id) {
if (doc.getElementById) {
return doc.getElementById(id);
}
let nodes = childNodesOfElement(doc);
let node;
while (nodes.length) {
node = nodes.shift();
if (node.getAttribute && node.getAttribute('id') === id) {
return node;
}
nodes = childNodesOfElement(node).concat(nodes);
}
}
|
/*
* Implement some helpers methods for interacting with the DOM,
* be it Fastboot's SimpleDOM or a browser's version.
*/
export function getActiveElement() {
if (typeof document === 'undefined') {
return null;
} else {
return document.activeElement;
}
}
function childNodesOfElement(element) {
let children = [];
let child = element.firstChild;
while (child) {
children.push(child);
child = child.nextSibling;
}
return children;
}
export function findElementById(doc, id) {
let nodes = childNodesOfElement(doc);
let node;
while (nodes.length) {
node = nodes.shift();
if (node.getAttribute && node.getAttribute('id') === id) {
return node;
}
nodes = childNodesOfElement(node).concat(nodes);
}
}
|
Use isEmpty() instead of comparing to empty array in country service
|
angular.module('yds').service('CountrySelectionService', function($rootScope) {
var countries = [];
var subscribe = function(scope, callback) {
var unregister = $rootScope.$on('country-selection-service-change', callback);
scope.$on('$destroy', unregister);
return unregister;
};
var notifySubscribers = function() {
$rootScope.$emit('country-selection-service-change');
};
var setCountries = function(newCountries) {
if (!_.isEqual(countries, newCountries)) {
countries = newCountries;
notifySubscribers();
}
};
var getCountries = function() {
return countries;
};
var clearCountries = function() {
if (!_.isEmpty(countries)) {
countries = [];
notifySubscribers();
}
};
return {
subscribe: subscribe,
setCountries: setCountries,
getCountries: getCountries,
clearCountries: clearCountries
};
});
|
angular.module('yds').service('CountrySelectionService', function($rootScope) {
var countries = [];
var subscribe = function(scope, callback) {
var unregister = $rootScope.$on('country-selection-service-change', callback);
scope.$on('$destroy', unregister);
return unregister;
};
var notifySubscribers = function() {
$rootScope.$emit('country-selection-service-change');
};
var setCountries = function(newCountries) {
if (!_.isEqual(countries, newCountries)) {
countries = newCountries;
notifySubscribers();
}
};
var getCountries = function() {
return countries;
};
var clearCountries = function() {
if (!_.isEqual(countries, [])) {
countries = [];
notifySubscribers();
}
};
return {
subscribe: subscribe,
setCountries: setCountries,
getCountries: getCountries,
clearCountries: clearCountries
};
});
|
Add port to Neo4j bolt connection
|
package hu.bme.mit.codemodel.rifle.database;
import java.util.HashMap;
import java.util.Map;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
/**
* Created by steindani on 3/13/16.
*/
public class DbServicesManager {
protected static Map<String, DbServices> dbServices = new HashMap<>();
protected static final String USER = "neo4j";
protected static final String PASSWORD = "neo4j";
synchronized
public static DbServices getDbServices(String branchId) {
if (!dbServices.containsKey(branchId)) {
final Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic(USER, PASSWORD));
final DbServices dbs = new DbServices(driver);
dbServices.put(branchId, dbs);
}
return dbServices.get(branchId);
}
}
|
package hu.bme.mit.codemodel.rifle.database;
import java.util.HashMap;
import java.util.Map;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
/**
* Created by steindani on 3/13/16.
*/
public class DbServicesManager {
protected static Map<String, DbServices> dbServices = new HashMap<>();
protected static final String USER = "neo4j";
protected static final String PASSWORD = "neo4j";
synchronized
public static DbServices getDbServices(String branchId) {
if (!dbServices.containsKey(branchId)) {
final Driver driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic(USER, PASSWORD));
final DbServices dbs = new DbServices(driver);
dbServices.put(branchId, dbs);
}
return dbServices.get(branchId);
}
}
|
Check for autoincrement before executing the instruction
|
class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
increment = self.bytecodes[self.pc].autoincrement
self.bytecodes[self.pc].execute(self)
if increment:
self.pc += 1
|
class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
self.bytecodes[self.pc].execute(self)
if self.bytecodes[self.pc].autoincrement:
self.pc += 1
|
Use pkg_resources to resolve the version. Requires that the necessary package metadata have been built before building docs.
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pkg_resources
extensions = [
'sphinx.ext.autodoc',
'rst.linker',
]
# General information about the project.
project = 'skeleton'
copyright = '2016 Jason R. Coombs'
# The short X.Y version.
version = pkg_resources.require(project)[0].version
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
link_files = {
'CHANGES.rst': dict(
using=dict(
GH='https://github.com',
project=project,
),
replace=[
dict(
pattern=r"(Issue )?#(?P<issue>\d+)",
url='{GH}/jaraco/{project}/issues/{issue}',
),
dict(
pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n",
with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n",
),
],
),
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
'rst.linker',
]
# General information about the project.
project = 'skeleton'
copyright = '2016 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
link_files = {
'CHANGES.rst': dict(
using=dict(
GH='https://github.com',
project=project,
),
replace=[
dict(
pattern=r"(Issue )?#(?P<issue>\d+)",
url='{GH}/jaraco/{project}/issues/{issue}',
),
dict(
pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n",
with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n",
),
],
),
}
|
Upgrade version to 0.0.15 (remove numpy dep)
Signed-off-by: Fabrice Normandin <ee438dab901b32439200d6bb23a0e635234ed3f0@gmail.com>
|
import sys
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
packages = setuptools.find_namespace_packages(include=['simple_parsing*'])
print("PACKAGES FOUND:", packages)
print(sys.version_info)
setuptools.setup(
name="simple_parsing",
version="0.0.15",
author="Fabrice Normandin",
author_email="fabrice.normandin@gmail.com",
description="A small utility for simplifying and cleaning up argument parsing scripts.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/lebrice/SimpleParsing",
packages=packages,
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
install_requires=[
"typing_inspect",
"dataclasses;python_version<'3.7'",
],
)
|
import sys
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
packages = setuptools.find_namespace_packages(include=['simple_parsing*'])
print("PACKAGES FOUND:", packages)
print(sys.version_info)
setuptools.setup(
name="simple_parsing",
version="0.0.14.post1",
author="Fabrice Normandin",
author_email="fabrice.normandin@gmail.com",
description="A small utility for simplifying and cleaning up argument parsing scripts.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/lebrice/SimpleParsing",
packages=packages,
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
install_requires=[
"typing_inspect",
"dataclasses;python_version<'3.7'",
],
)
|
Fix sorting dictionary key, value pairs in Python 3.
|
from __future__ import unicode_literals
from .conf import BREAKPOINTS
def _get_device_type(width):
"Returns the type based on set breakpoints."
sorted_types = sorted(BREAKPOINTS.items(), key=lambda x: x[1] or 0)
default_type = None
for name, cutoff in sorted_types:
if cutoff is None:
default_type = name
elif width <= cutoff:
return name
return default_type
def device_info(request):
"Add processed device info into the template context."
default = {'width': None, 'height': None}
info = getattr(request, 'device_info', default)
width = info.get('width', None)
if width is not None:
info['type'] = _get_device_type(width)
else:
info['type'] = None
return {'device_info': info}
|
from __future__ import unicode_literals
from .conf import BREAKPOINTS
def _get_device_type(width):
"Returns the type based on set breakpoints."
sorted_types = sorted(BREAKPOINTS.items(), key=lambda x: x[1])
default_type = None
for name, cutoff in sorted_types:
if cutoff is None:
default_type = name
elif width <= cutoff:
return name
return default_type
def device_info(request):
"Add processed device info into the template context."
default = {'width': None, 'height': None}
info = getattr(request, 'device_info', default)
width = info.get('width', None)
if width is not None:
info['type'] = _get_device_type(width)
else:
info['type'] = None
return {'device_info': info}
|
Make CraftingTweaks integration use RegisterProviderV2 so it doesn't trigger on older versions of CraftingTweaks.
|
package refinedstorage.integration;
import com.google.common.base.Function;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import refinedstorage.block.EnumGridType;
import refinedstorage.container.ContainerGrid;
public class IntegrationCraftingTweaks {
public static final String MOD_ID = "craftingtweaks";
public static void register() {
if(Loader.isModLoaded(MOD_ID)) {
NBTTagCompound tagCompound = new NBTTagCompound();
tagCompound.setString("ContainerClass", ContainerGrid.class.getName());
tagCompound.setString("ContainerCallback", ContainerCallback.class.getName());
tagCompound.setInteger("GridSlotNumber", 36);
tagCompound.setString("AlignToGrid", "left");
FMLInterModComms.sendMessage(MOD_ID, "RegisterProviderV2", tagCompound);
}
}
public static class ContainerCallback implements Function<ContainerGrid, Boolean> {
@Override
public Boolean apply(ContainerGrid containerGrid) {
return containerGrid.getGrid().getType() == EnumGridType.CRAFTING;
}
}
}
|
package refinedstorage.integration;
import com.google.common.base.Function;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import refinedstorage.block.EnumGridType;
import refinedstorage.container.ContainerGrid;
public class IntegrationCraftingTweaks {
public static final String MOD_ID = "craftingtweaks";
public static void register() {
if(Loader.isModLoaded(MOD_ID)) {
NBTTagCompound tagCompound = new NBTTagCompound();
tagCompound.setString("ContainerClass", ContainerGrid.class.getName());
tagCompound.setString("ContainerCallback", ContainerCallback.class.getName());
tagCompound.setInteger("GridSlotNumber", 36);
tagCompound.setString("AlignToGrid", "left");
FMLInterModComms.sendMessage(MOD_ID, "RegisterProvider", tagCompound);
}
}
public static class ContainerCallback implements Function<ContainerGrid, Boolean> {
@Override
public Boolean apply(ContainerGrid containerGrid) {
return containerGrid.getGrid().getType() == EnumGridType.CRAFTING;
}
}
}
|
Fix parsing error in ERR_NEEDMOREPARAMS
|
var
extend = req('/utilities/extend'),
ServerMessage = req('/lib/server/message'),
ReplyNumerics = req('/constants/reply-numerics'),
CommandValidator = req('/validators/command'),
ErrorReasons = req('/constants/error-reasons'),
InvalidCommandError = req('/lib/errors/invalid-command');
class NeedMoreParamsMessage extends ServerMessage {
setAttemptedCommand(command) {
CommandValidator.validate(command);
this.attempted_command = command;
}
getAttemptedCommand() {
CommandValidator.validate(this.attempted_command);
return this.attempted_command;
}
applyParsedParams(middle_params, trailing_param) {
this.addTargetFromString(middle_params.shift());
this.setAttemptedCommand(middle_params.shift());
this.setBody(trailing_param);
}
serializeParams() {
var
targets = this.serializeTargets(),
command = this.getAttemptedCommand(),
body = this.getBody();
return `${targets} ${command} :${body}`;
}
toError() {
return new InvalidCommandError(
this.getAttemptedCommand(),
ErrorReasons.NOT_ENOUGH_PARAMETERS
);
}
}
extend(NeedMoreParamsMessage.prototype, {
reply_numeric: ReplyNumerics.ERR_NEEDMOREPARAMS,
body: 'Not enough parameters.',
attempted_command: null
});
module.exports = NeedMoreParamsMessage;
|
var
extend = req('/utilities/extend'),
ServerMessage = req('/lib/server/message'),
ReplyNumerics = req('/constants/reply-numerics'),
CommandValidator = req('/validators/command'),
ErrorReasons = req('/constants/error-reasons'),
InvalidCommandError = req('/lib/errors/invalid-command');
class NeedMoreParamsMessage extends ServerMessage {
setAttemptedCommand(command) {
CommandValidator.validate(command);
this.attempted_command = command;
}
getAttemptedCommand() {
CommandValidator.validate(this.attempted_command);
return this.command;
}
applyParsedParams(middle_params, trailing_param) {
this.addTargetFromString(middle_params.shift());
this.setAttemptedCommand(middle_params.shift());
this.setBody(trailing_param);
}
serializeParams() {
var
targets = this.serializeTargets(),
command = this.getAttemptedCommand(),
body = this.getBody();
return `${targets} ${command} :${body}`;
}
toError() {
return new InvalidCommandError(
this.getAttemptedCommand(),
ErrorReasons.NOT_ENOUGH_PARAMETERS
);
}
}
extend(NeedMoreParamsMessage.prototype, {
reply_numeric: ReplyNumerics.ERR_NEEDMOREPARAMS,
body: 'Not enough parameters.'
});
module.exports = NeedMoreParamsMessage;
|
Allow init DB via env variable
|
'use strict';
// Production specific configuration
// ==================================
var production = {
server: {
staticDir : '/../../dist'
},
// MongoDB connection options
mongodb: {
uri: 'mongodb://localhost/devnews-dev'
},
seedDB: false
};
if (process.env.INIT_DB) {
production.seedDB = true;
}
// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.MONGOLAB_URI) {
production.mongodb.uri = process.env.MONGOLAB_URI;
} else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
production.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
process.env.OPENSHIFT_APP_NAME;
}
module.exports = production;
|
'use strict';
// Production specific configuration
// ==================================
var production = {
server: {
staticDir : '/../../dist'
},
// MongoDB connection options
mongodb: {
uri: 'mongodb://localhost/devnews-dev'
},
seedDB: false
};
// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.MONGOLAB_URI) {
production.mongodb.uri = process.env.MONGOLAB_URI;
} else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
production.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
process.env.OPENSHIFT_APP_NAME;
}
module.exports = production;
|
Use the `this` constructor as suggested by @cbeust
This makes constructors more maintainable: one constructor does the
processing.
|
/**
* Copyright (C) 2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.beust.jcommander;
/**
* Thrown when a command was expected.
*
* @author Cedric Beust <cedric@beust.com>
*/
@SuppressWarnings("serial")
public class MissingCommandException extends ParameterException {
/**
* the command passed by the user.
*/
private final String unknownCommand;
public MissingCommandException(String message) {
this(message, null);
}
public MissingCommandException(String message, String command) {
super(message);
this.unknownCommand = command;
}
public String getUnknownCommand() {
return unknownCommand;
}
}
|
/**
* Copyright (C) 2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.beust.jcommander;
/**
* Thrown when a command was expected.
*
* @author Cedric Beust <cedric@beust.com>
*/
@SuppressWarnings("serial")
public class MissingCommandException extends ParameterException {
/**
* the command passed by the user.
*/
private final String unknownCommand;
public MissingCommandException(String message) {
super(message);
this.unknownCommand = null;
}
public MissingCommandException(String message, String command) {
super(message);
this.unknownCommand = command;
}
public String getUnknownCommand() {
return unknownCommand;
}
}
|
test(SdkCommon): Remove unnecessary extension and change header class reference
|
package com.ibm.watson.common;
import com.ibm.cloud.sdk.core.http.HttpHeaders;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertTrue;
public class SdkCommonTest {
@Test
public void testGetDefaultHeaders() {
String serviceName = "test_name";
String serviceVersion = "v1";
String operationId = "test_method";
Map<String, String> defaultHeaders = SdkCommon.getDefaultHeaders(serviceName, serviceVersion, operationId);
assertTrue(defaultHeaders.containsKey(WatsonHttpHeaders.X_IBMCLOUD_SDK_ANALYTICS));
String analyticsHeaderValue = defaultHeaders.get(WatsonHttpHeaders.X_IBMCLOUD_SDK_ANALYTICS);
assertTrue(analyticsHeaderValue.contains(serviceName));
assertTrue(analyticsHeaderValue.contains(serviceVersion));
assertTrue(analyticsHeaderValue.contains(operationId));
assertTrue(defaultHeaders.containsKey(HttpHeaders.USER_AGENT));
assertTrue(defaultHeaders.get(HttpHeaders.USER_AGENT).startsWith("watson-apis-java-sdk/"));
}
}
|
package com.ibm.watson.common;
import com.ibm.cloud.sdk.core.http.HttpHeaders;
import com.ibm.cloud.sdk.core.test.WatsonServiceUnitTest;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertTrue;
public class SdkCommonTest extends WatsonServiceUnitTest {
@Test
public void testGetDefaultHeaders() {
String serviceName = "test_name";
String serviceVersion = "v1";
String operationId = "test_method";
Map<String, String> defaultHeaders = SdkCommon.getDefaultHeaders(serviceName, serviceVersion, operationId);
assertTrue(defaultHeaders.containsKey(HttpHeaders.X_IBMCLOUD_SDK_ANALYTICS));
String analyticsHeaderValue = defaultHeaders.get(HttpHeaders.X_IBMCLOUD_SDK_ANALYTICS);
assertTrue(analyticsHeaderValue.contains(serviceName));
assertTrue(analyticsHeaderValue.contains(serviceVersion));
assertTrue(analyticsHeaderValue.contains(operationId));
assertTrue(defaultHeaders.containsKey(HttpHeaders.USER_AGENT));
assertTrue(defaultHeaders.get(HttpHeaders.USER_AGENT).startsWith("watson-apis-java-sdk/"));
}
}
|
Switch dropconnect to native op
|
package org.deeplearning4j.util;
import org.deeplearning4j.nn.api.Layer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.DropOut;
import org.nd4j.linalg.api.ops.impl.transforms.DropOutInverted;
import org.nd4j.linalg.factory.Nd4j;
/**
* @author Adam Gibson
*/
public class Dropout {
private Dropout() {
}
/**
* Apply drop connect to the given variable
* @param layer the layer with the variables
* @param variable the variable to apply
* @return the post applied drop connect
*/
public static INDArray applyDropConnect(Layer layer,String variable) {
INDArray result = layer.getParam(variable).dup();
Nd4j.getExecutioner().exec(new DropOut(result, result, layer.conf().getLayer().getDropOut()));
return result;
}
/**
* Apply dropout to the given input
* and return the drop out mask used
* @param input the input to do drop out on
* @param dropout the drop out probability
*/
public static void applyDropout(INDArray input,double dropout) {
Nd4j.getExecutioner().exec(new DropOutInverted(input, dropout));
}
}
|
package org.deeplearning4j.util;
import org.deeplearning4j.nn.api.Layer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.DropOutInverted;
import org.nd4j.linalg.factory.Nd4j;
/**
* @author Adam Gibson
*/
public class Dropout {
private Dropout() {
}
/**
* Apply drop connect to the given variable
* @param layer the layer with the variables
* @param variable the variable to apply
* @return the post applied drop connect
*/
public static INDArray applyDropConnect(Layer layer,String variable) {
return layer.getParam(variable).mul(Nd4j.getDistributions().createBinomial(1,layer.conf().getLayer().getDropOut()).sample(layer.getParam(variable).shape()));
}
/**
* Apply dropout to the given input
* and return the drop out mask used
* @param input the input to do drop out on
* @param dropout the drop out probability
*/
public static void applyDropout(INDArray input,double dropout) {
Nd4j.getExecutioner().exec(new DropOutInverted(input, dropout));
}
}
|
Rewrite as a Pest PHP test
|
<?php
use function Pest\Laravel\get;
test('Lising page exists', function($url) {
get($url)->assertStatus(200);
})->with([
'Machines listing' => '/machines',
'Test equipment listing' => '/testequipment',
'Test equipment calibration dates liisting' => '/testequipment/caldates',
]);
// namespace Tests\Feature;
// use Tests\TestCase;
// class ListingsTest extends TestCase
// {
// /**
// * Test that the Listings pages load via HTTP requests.
// *
// * @dataProvider ListingPages
// *
// * @return void
// **/
// public function testListingPagesLoadViaHttp($pageName, $value)
// {
// $this->get($pageName)->assertStatus(200);
// }
// public function listingPages(): array
// {
// return [
// 'Machines listing' => ['/machines', 'Equipment Inventory - Active'],
// 'Test equipment listing' => ['/testequipment', 'Equipment Inventory - Test Equipment'],
// 'Test equipment cal dates listing' => ['/testequipment/caldates', 'Recent Test Equipment Calibration Dates'],
// ];
// }
//}
|
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ListingsTest extends TestCase
{
/**
* Test that the Listings pages load via HTTP requests.
*
* @dataProvider ListingPages
*
* @return void
**/
public function testListingPagesLoadViaHttp($pageName, $value)
{
$this->get($pageName)->assertStatus(200);
}
public function listingPages(): array
{
return [
'Machines listing' => ['/machines', 'Equipment Inventory - Active'],
'Test equipment listing' => ['/testequipment', 'Equipment Inventory - Test Equipment'],
'Test equipment cal dates listing' => ['/testequipment/caldates', 'Recent Test Equipment Calibration Dates'],
];
}
}
|
Rename some constants and strings
|
/*
* Copyright 2016 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cd.go.contrib.elasticagents.docker;
public interface Constants {
String PLUGIN_ID = "cd.go.contrib.elastic-agents.docker";
String EXTENSION_NAME = "elastic-agent";
// requests that the plugin makes to the server
String REQUEST_SERVER_PREFIX = "go.processor";
String REQUEST_SERVER_DISABLE_AGENT = REQUEST_SERVER_PREFIX + ".elasticagent.disable-agents";
String REQUEST_SERVER_DELETE_AGENT = REQUEST_SERVER_PREFIX + ".elasticagent.delete-agents";
String REQUEST_SERVER_GET_PLUGIN_SETTINGS = REQUEST_SERVER_PREFIX + ".plugin-settings.get";
String REQUEST_SERVER_LIST_AGENTS = REQUEST_SERVER_PREFIX + ".elasticagent.list-agents";
// internal use only
String CREATED_BY_LABEL_KEY = "Elastic-Agent-Created-By";
}
|
/*
* Copyright 2016 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cd.go.contrib.elasticagents.docker;
public interface Constants {
String PLUGIN_ID = "cd.go.contrib.elastic-agents.docker";
String EXTENSION_NAME = "elastic-agent";
// requests that the plugin makes to the server
String REQUEST_SERVER_PREFIX = "go.processor";
String REQUEST_SERVER_DISABLE_AGENT = REQUEST_SERVER_PREFIX + ".elasticagent.disable-agent";
String REQUEST_SERVER_DELETE_AGENT = REQUEST_SERVER_PREFIX + ".elasticagent.delete-agent";
String REQUEST_SERVER_GET_PLUGIN_SETTINGS = REQUEST_SERVER_PREFIX + ".plugin-settings.get";
String REQUEST_SERVER_LIST_AGENTS = REQUEST_SERVER_PREFIX + ".elasticagent.list";
// internal use only
String CREATED_BY_LABEL_KEY = "Elastic-Agent-Created-By";
}
|
[LIB] Add support for a class to be applied to the Popover component
|
import React from 'react';
import PropTypes from 'prop-types';
import { autobind } from 'core-decorators';
import { Popover, Position, Button } from "@blueprintjs/core";
@autobind
class MenuButton extends React.Component {
static propTypes = {
menu: PropTypes.element,
iconName: PropTypes.string,
text: PropTypes.string,
loading: PropTypes.bool,
buttonClass: PropTypes.string,
popoverClass: PropTypes.string,
position: PropTypes.oneOf(Object.keys(Position).map(
(value) => {
let num = parseInt(value);
if (isNaN(num)) return value;
else return num;
}
))
}
static defaultProps = {
loading: false,
position: Position.BOTTOM_RIGHT
}
render() {
return (
<Popover className={this.props.popoverClass} content={this.props.menu} position={this.props.position} isDisabled={this.props.loading}>
<Button
type='button'
loading={this.props.loading}
className={this.props.buttonClass}
iconName={this.props.iconName}
>
{this.props.text}
</Button>
</Popover>
);
}
}
export default MenuButton;
|
import React from 'react';
import PropTypes from 'prop-types';
import { autobind } from 'core-decorators';
import { Popover, Position, Button } from "@blueprintjs/core";
@autobind
class MenuButton extends React.Component {
static propTypes = {
menu: PropTypes.element,
iconName: PropTypes.string,
text: PropTypes.string,
loading: PropTypes.bool,
buttonClass: PropTypes.string,
position: PropTypes.oneOf(Object.keys(Position).map(
(value) => {
let num = parseInt(value);
if (isNaN(num)) return value;
else return num;
}
))
}
static defaultProps = {
loading: false,
position: Position.BOTTOM_RIGHT
}
render() {
return (
<Popover content={this.props.menu} position={this.props.position} isDisabled={this.props.loading}>
<Button
type='button'
loading={this.props.loading}
className={this.props.buttonClass}
iconName={this.props.iconName}
>
{this.props.text}
</Button>
</Popover>
);
}
}
export default MenuButton;
|
Introduce ErrUnexpectedTokenType, which our unmarshaller machines should start returning here on out.
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us>
|
package obj
import (
"fmt"
"reflect"
. "github.com/polydawn/refmt/tok"
)
// ErrInvalidUnmarshalTarget describes an invalid argument passed to UnmarshalDriver.Bind.
// (Unmarshalling must target a non-nil pointer so that it can address the value.)
type ErrInvalidUnmarshalTarget struct {
Type reflect.Type
}
func (e ErrInvalidUnmarshalTarget) Error() string {
if e.Type == nil {
return "invalid unmarshal target (nil)"
}
if e.Type.Kind() != reflect.Ptr {
return "invalid unmarshal target (non-pointer " + e.Type.String() + ")"
}
return "invalid unmarshal target: (nil " + e.Type.String() + ")"
}
// ErrUnmarshalIncongruent is the error returned when unmarshalling cannot
// coerce the tokens in the stream into the variables the unmarshal is targetting,
// for example if a map open token comes when an int is expected.
type ErrUnmarshalIncongruent struct {
Token Token
Value reflect.Value
}
func (e ErrUnmarshalIncongruent) Error() string {
return fmt.Sprintf("cannot assign %s to %s field", e.Token, e.Value.Kind())
}
type ErrUnexpectedTokenType struct {
Got TokenType // Token in the stream that triggered the error.
Expected string // Freeform string describing valid token types. Often a summary like "array close or start of value", or "map close or key".
}
func (e ErrUnexpectedTokenType) Error() string {
return fmt.Sprintf("unexpected %s token; expected %s", e.Got, e.Expected)
}
|
package obj
import (
"fmt"
"reflect"
. "github.com/polydawn/refmt/tok"
)
// ErrInvalidUnmarshalTarget describes an invalid argument passed to UnmarshalDriver.Bind.
// (Unmarshalling must target a non-nil pointer so that it can address the value.)
type ErrInvalidUnmarshalTarget struct {
Type reflect.Type
}
func (e ErrInvalidUnmarshalTarget) Error() string {
if e.Type == nil {
return "invalid unmarshal target (nil)"
}
if e.Type.Kind() != reflect.Ptr {
return "invalid unmarshal target (non-pointer " + e.Type.String() + ")"
}
return "invalid unmarshal target: (nil " + e.Type.String() + ")"
}
// ErrUnmarshalIncongruent is the error returned when unmarshalling cannot
// coerce the tokens in the stream into the variables the unmarshal is targetting,
// for example if a map open token comes when an int is expected.
type ErrUnmarshalIncongruent struct {
Token Token
Value reflect.Value
}
func (e ErrUnmarshalIncongruent) Error() string {
return fmt.Sprintf("cannot assign %s to %s field", e.Token, e.Value.Kind())
}
|
Make buck wrapper logs human-readable.
Summary: Simplify logging setup and make its format human-readable
Test Plan:
$ BUCK_WRAPPER_LOG_LEVEL=DEBUG buck run buck -- --version
buck version 64999e5d3b446c062da5c3cc282a2e78ce133c92
2017-12-05 14:08:08,073 [DEBUG][buck.py:80] [Errno 2] No such file or directory
perviously it would produce:
buck version 64999e5d3b446c062da5c3cc282a2e78ce133c92
[Errno 2] No such file or directory
which does not leave much to investigate
Reviewed By: sbalabanov
fbshipit-source-id: 2d0b977
|
#!/usr/bin/env python
from __future__ import print_function
import logging
import os
def setup_logging():
# Set log level of the messages to show.
level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')
level_name_to_level = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET,
}
level = level_name_to_level.get(level_name.upper(), logging.INFO)
logging.basicConfig(
level=level,
format=(
'%(asctime)s [%(levelname)s][%(filename)s:%(lineno)d] %(message)s'
))
|
#!/usr/bin/env python
from __future__ import print_function
import logging
import os
def setup_logging():
# Set log level of the messages to show.
logger = logging.getLogger()
level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')
level_name_to_level = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET,
}
level = level_name_to_level.get(level_name.upper(), logging.INFO)
logger.setLevel(level)
# Set formatter for log messages.
console_handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s')
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
|
Correct style of wheels exercise
|
"""Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
# rueda_izquierda = raw_input("Velocidad izquierda: ")
# rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
|
"""Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
#rueda_izquierda = raw_input("Velocidad izquierda: ")
#rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
|
Remove GL context test to verify that Travis CI works
|
// /* global document */
// import {WebGLRenderingContext} from '../../src/webgl';
import {createGLContext, hasWebGL, hasExtension, Program}
from '../../src/webgl';
import test from 'tape-catch';
test('WebGL#types', t => {
t.ok(typeof Program === 'function', 'Program is defined');
t.ok(typeof createGLContext === 'function', 'createGLContext is defined');
t.ok(typeof hasWebGL === 'function', 'hasWebGL is defined');
t.ok(typeof hasExtension === 'function', 'hasExtension is defined');
t.end();
});
// test('WebGL#headless', t => {
// const canvas = document.createElement('canvas');
// const gl = createGLContext(canvas);
// t.ok(gl instanceof WebGLRenderingContext);
// t.ok(hasWebGL(), 'hasWebGL() is true');
// t.notOk(hasExtension('noextension'), 'hasExtension(noextension) is false');
// t.end();
// });
|
/* global document */
import {createGLContext, hasWebGL, hasExtension, Program}
from '../../src/webgl';
import {WebGLRenderingContext} from '../../src/webgl';
import test from 'tape-catch';
test('WebGL#types', t => {
t.ok(typeof Program === 'function', 'Program is defined');
t.ok(typeof createGLContext === 'function', 'createGLContext is defined');
t.ok(typeof hasWebGL === 'function', 'hasWebGL is defined');
t.ok(typeof hasExtension === 'function', 'hasExtension is defined');
t.end();
});
test('WebGL#headless', t => {
const canvas = document.createElement('canvas');
const gl = createGLContext(canvas);
t.ok(gl instanceof WebGLRenderingContext);
t.ok(hasWebGL(), 'hasWebGL() is true');
t.notOk(hasExtension('noextension'), 'hasExtension(noextension) is false');
t.end();
});
|
Make it so that the example runs without error
|
from pupa.scrape import Scraper
from pupa.scrape.helpers import Legislator, Organization
class PersonScraper(Scraper):
def get_people(self):
# committee
tech = Organization('Technology', classification='committee')
tech.add_post('Chairman', 'chairman')
tech.add_source('https://example.com')
yield tech
# subcommittee
ecom = Organization('Subcommittee on E-Commerce',
parent=tech,
classification='committee')
ecom.add_source('https://example.com')
yield ecom
p = Legislator('Paul Tagliamonte', '6')
p.add_membership(tech, role='chairman')
p.add_source('https://example.com')
yield p
|
from pupa.scrape import Scraper
from pupa.scrape.helpers import Legislator, Organization
class PersonScraper(Scraper):
def get_people(self):
# committee
tech = Organization('Technology', classification='committee')
tech.add_post('Chairman', 'chairman')
tech.add_source('https://example.com')
yield tech
# subcommittee
ecom = Organization('Subcommittee on E-Commerce',
parent=tech,
classification='committee')
ecom.add_source('https://example.com')
yield ecom
p = Person('Paul Tagliamonte', district='6', chamber='upper')
p.add_committee_membership(tech, role='chairman')
p.add_source('https://example.com')
yield p
|
Rename orcomm pkg to app
|
import os
import uuid
from infosystem.common import authorization
from infosystem import database
from flask import Flask
from infosystem import system as system_module
from app import init_data
app = Flask(__name__)
app.config['BASEDIR'] = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['BASEDIR'] + '/infosystem.db'
system = system_module.System([
# TODO List here your modules
]
)
database.db.init_app(app)
with app.app_context():
database.db.create_all()
rows = system.subsystems['domain'].manager.count()
if (rows == 0):
init_data.do(system)
for subsystem in system.subsystems.values():
app.register_blueprint(subsystem)
def protect():
return authorization.protect(system)
app.before_request(protect)
def load_app():
return app
|
import os
import uuid
from infosystem.common import authorization
from infosystem import database
from flask import Flask
from infosystem import system as system_module
from orcomm import init_data
app = Flask(__name__)
app.config['BASEDIR'] = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['BASEDIR'] + '/infosystem.db'
system = system_module.System([
# TODO List here your modules
]
)
database.db.init_app(app)
with app.app_context():
database.db.create_all()
rows = system.subsystems['domain'].manager.count()
if (rows == 0):
init_data.do(system)
for subsystem in system.subsystems.values():
app.register_blueprint(subsystem)
def protect():
return authorization.protect(system)
app.before_request(protect)
def load_app():
return app
|
Remove the uniqueness rule here as it prevented saving changes when the email address was not changed.
|
<?php
namespace App\Validation\EntityRules;
use App\Entities\User;
use Somnambulist\EntityValidation\AbstractEntityRules;
class UserRules extends AbstractEntityRules
{
/**
* Return an array of rules for validating Users
*
* @param object $entity
* @return array
*/
protected function buildRules($entity)
{
return [
'name' => 'bail|required|min:2',
'email' => 'bail|required|email',
'password' => 'present',
];
}
/**
* @return array
*/
public function messages()
{
return [
'name' => 'Name must be at least two characters long.',
'email' => 'A person with that email address is already registered.',
'password' => 'Your password should be at least 8 characters long.',
];
}
/**
* Define the entity that this validator supports
*
* @param object $entity
* @return bool
*/
public function supports($entity)
{
return $entity instanceof User;
}
}
|
<?php
namespace App\Validation\EntityRules;
use App\Entities\User;
use Somnambulist\EntityValidation\AbstractEntityRules;
class UserRules extends AbstractEntityRules
{
/**
* Return an array of rules for validating Users
*
* @param object $entity
* @return array
*/
protected function buildRules($entity)
{
return [
'name' => 'bail|required|min:2',
'email' => 'bail|required|email|unique:'. User::class .',email',
'password' => 'present',
];
}
/**
* @return array
*/
public function messages()
{
return [
'name' => 'Name must be at least two characters long.',
'email' => 'A person with that email address is already registered.',
'password' => 'Your password should be at least 8 characters long.',
];
}
/**
* Define the entity that this validator supports
*
* @param object $entity
* @return bool
*/
public function supports($entity)
{
return $entity instanceof User;
}
}
|
Set loaded flag on a task to false. Only load the task template if the task is clicked on (preloading the templates for all tasks is an expensive operation when there are a decent (20+) number of tasks).
|
angular.module('materialscommons').factory('toUITask', toUITaskService);
/*@ngInject*/
function toUITaskService() {
return function(task) {
task.displayState = {
details: {
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0,
loadEditor: false
},
flags: {
starredClass: task.flags.starred ? 'fa-star' : 'fa-star-o',
flaggedClass: task.flags.flagged ? 'mc-flagged-color' : 'mc-flag-not-set'
},
selectedClass: '',
editTitle: true,
open: false,
maximize: false
};
task.loaded = false;
task.node = null;
}
}
|
angular.module('materialscommons').factory('toUITask', toUITaskService);
/*@ngInject*/
function toUITaskService() {
return function(task) {
task.displayState = {
details: {
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0,
loadEditor: false
},
flags: {
starredClass: task.flags.starred ? 'fa-star' : 'fa-star-o',
flaggedClass: task.flags.flagged ? 'mc-flagged-color' : 'mc-flag-not-set'
},
selectedClass: '',
editTitle: true,
open: false,
maximize: false
};
task.node = null;
}
}
|
Allow google/DDG results to fall back to URL if no title
- in some cases, where a page's title cannot be extracted (most websites work fine, PDFs depend on how the pdf metadata was set up) overview will fallback to displaying URL for title
- search injection result views didn't have this fallback, leading to minor inconsistencies
|
import React from 'react'
import PropTypes from 'prop-types'
import niceTime from 'src/util/nice-time'
import classNames from 'classnames'
import styles from './ResultItem.css'
const ResultItem = props => (
<div className={classNames(styles.result, styles[props.searchEngine])}>
<a
className={styles.title}
href={props.url}
onClick={props.onLinkClick}
target="_blank"
>
{props.title || props.url}
</a>
<p className={styles.url}>{props.url}</p>
<div className={styles.displayTime}>
{' '}
{niceTime(+props.displayTime)}{' '}
</div>
</div>
)
ResultItem.propTypes = {
searchEngine: PropTypes.string.isRequired,
displayTime: PropTypes.number.isRequired,
url: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
onLinkClick: PropTypes.func.isRequired,
}
export default ResultItem
|
import React from 'react'
import PropTypes from 'prop-types'
import niceTime from 'src/util/nice-time'
import classNames from 'classnames'
import styles from './ResultItem.css'
const ResultItem = props => (
<div className={classNames(styles.result, styles[props.searchEngine])}>
<a
className={styles.title}
href={props.url}
onClick={props.onLinkClick}
target="_blank"
>
{props.title}
</a>
<p className={styles.url}>{props.url}</p>
<div className={styles.displayTime}>
{' '}
{niceTime(+props.displayTime)}{' '}
</div>
</div>
)
ResultItem.propTypes = {
searchEngine: PropTypes.string.isRequired,
displayTime: PropTypes.number.isRequired,
url: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
onLinkClick: PropTypes.func.isRequired,
}
export default ResultItem
|
Update Posts. Just stillplugging a little bit at a time at the posting sections
|
//Posts for Blog
Posts = new Mongo.Collection('posts');
if (Meteor.isServer) {
Posts.allow({
insert: function (userId, doc) {
return true;
},
update: function (userId, doc, fieldNames, modifier) {
return true;
},
remove: function (userId, doc) {
return true;
}
});
}
Posts.attachSchema(new SimpleSchema({
title: {
type: String,
label: "Title",
max: 244
},
body: {
type: String,
label: "Body"
},
publishDate: {
type: Date,
autoform: {
type: 'hidden',
label: false
},
}
createdAt: {
type: Date,
autoform: {
type: 'hidden',
label: false
},
autoValue: function(){
return new Date();
}
}
tags: {
type: String,
label: "Body Style",
allowedValues: ['Convertibles', 'Coupes', 'Hatchbacks', 'Vans', 'Sedans', 'Suvs', 'Trucks', 'Wagons'],
optional: true
},
}));
|
//Posts for Blog
Posts = new Mongo.Collection('posts');
if (Meteor.isServer) {
Posts.allow({
insert: function (userId, doc) {
return true;
},
update: function (userId, doc, fieldNames, modifier) {
return true;
},
remove: function (userId, doc) {
return true;
}
});
}
Posts.attachSchema(new SimpleSchema({
title: {
type: String,
label: "Title",
max: 100
},
body: {
type: String,
label: "Body"
},
publishDate: {
type: String,
label: "Fuel Type",
allowedValues: ['Petrol', 'Diesel', 'Hybrid', 'Electric'],
},
tags: {
type: String,
label: "Body Style",
allowedValues: ['Convertibles', 'Coupes', 'Hatchbacks', 'Vans', 'Sedans', 'Suvs', 'Trucks', 'Wagons'],
optional: true
},
}));
|
Fix negative offsets in read_list
|
from typing import Iterable, Optional
from redis import Redis
def read_list(
redis_conn: Redis, key: str, *, chunk_size: int = 4096, last_n: Optional[int] = None
) -> Iterable[bytes]:
"""
Read a possibly large Redis list in chunks.
Avoids OOMs on the Redis side.
:param redis_conn: Redis connection
:param key: Key
:param chunk_size: How many lines to read per request.
:param last_n: Attempt to only read the last N lines.
:return:
"""
if not redis_conn.exists(key):
return
if chunk_size <= 0:
chunk_size = 4096
if last_n and last_n > 0:
offset = max(0, redis_conn.llen(key) - last_n)
else:
offset = 0
while offset < redis_conn.llen(key):
# Regarding that - 1 there, see this from https://redis.io/commands/lrange:
# > Note that if you have a list of numbers from 0 to 100, LRANGE list 0 10
# > will return 11 elements, that is, the rightmost item is included.
chunk = redis_conn.lrange(key, offset, offset + chunk_size - 1) or []
if not chunk:
break
yield from chunk
offset += chunk_size
|
from typing import Iterable, Optional
from redis import Redis
def read_list(
redis_conn: Redis, key: str, *, chunk_size: int = 4096, last_n: Optional[int] = None
) -> Iterable[bytes]:
"""
Read a possibly large Redis list in chunks.
Avoids OOMs on the Redis side.
:param redis_conn: Redis connection
:param key: Key
:param chunk_size: How many lines to read per request.
:param last_n: Attempt to only read the last N lines.
:return:
"""
if not redis_conn.exists(key):
return
if chunk_size <= 0:
chunk_size = 4096
if last_n and last_n > 0:
offset = redis_conn.llen(key) - last_n
else:
offset = 0
while offset < redis_conn.llen(key):
# Regarding that - 1 there, see this from https://redis.io/commands/lrange:
# > Note that if you have a list of numbers from 0 to 100, LRANGE list 0 10
# > will return 11 elements, that is, the rightmost item is included.
chunk = redis_conn.lrange(key, offset, offset + chunk_size - 1) or []
if not chunk:
break
yield from chunk
offset += chunk_size
|
Throw instead of returning an error
|
'use strict';
var getos = require('getos');
var execFile = require('child_process').execFile;
/**
* Get the current Linux distro
*
* @param {Function} cb
* @api public
*/
module.exports = function (cb) {
if (process.platform !== 'linux') {
throw new Error('Only Linux systems are supported');
}
execFile('lsb_release', ['-a', '--short'], function (err, stdout) {
var obj = {};
if (err) {
getos(function (err, res) {
if (err) {
cb(err);
return;
}
cb(null, { os: res });
});
}
stdout = stdout.split('\n');
obj.os = stdout[0];
obj.name = stdout[1];
obj.release = stdout[2];
obj.code = stdout[3];
cb(null, obj);
});
};
|
'use strict';
var getos = require('getos');
var execFile = require('child_process').execFile;
/**
* Get the current Linux distro
*
* @param {Function} cb
* @api public
*/
module.exports = function (cb) {
if (process.platform !== 'linux') {
cb(new Error('Only Linux systems are supported'));
return;
}
execFile('lsb_release', ['-a', '--short'], function (err, stdout) {
var obj = {};
if (err) {
getos(function (err, res) {
if (err) {
cb(err);
return;
}
cb(null, { os: res });
});
}
stdout = stdout.split('\n');
obj.os = stdout[0];
obj.name = stdout[1];
obj.release = stdout[2];
obj.code = stdout[3];
cb(null, obj);
});
};
|
Fix MethodType only takes two parameters
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
|
"""
Some extra picklers needed to gracefully dump and load a canvas.
"""
from future import standard_library
standard_library.install_aliases()
import copyreg
# Allow instancemethod to be pickled:
import types
def construct_instancemethod(funcname, self, clazz):
func = getattr(clazz, funcname)
return types.MethodType(func, self)
def reduce_instancemethod(im):
return (
construct_instancemethod,
(im.__func__.__name__, im.__self__, im.__self__.__class__),
)
copyreg.pickle(types.MethodType, reduce_instancemethod, construct_instancemethod)
# Allow cairo.Matrix to be pickled:
import cairo
def construct_cairo_matrix(*args):
return cairo.Matrix(*args)
def reduce_cairo_matrix(m):
return construct_cairo_matrix, tuple(m)
copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix)
# vim:sw=4:et:ai
|
"""
Some extra picklers needed to gracefully dump and load a canvas.
"""
from future import standard_library
standard_library.install_aliases()
import copyreg
# Allow instancemethod to be pickled:
import types
def construct_instancemethod(funcname, self, clazz):
func = getattr(clazz, funcname)
return types.MethodType(func, self, clazz)
def reduce_instancemethod(im):
return (
construct_instancemethod,
(im.__func__.__name__, im.__self__, im.__self__.__class__),
)
copyreg.pickle(types.MethodType, reduce_instancemethod, construct_instancemethod)
# Allow cairo.Matrix to be pickled:
import cairo
def construct_cairo_matrix(*args):
return cairo.Matrix(*args)
def reduce_cairo_matrix(m):
return construct_cairo_matrix, tuple(m)
copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix)
# vim:sw=4:et:ai
|
Resolve ES6-modules in multi-fulfiller roles
|
import {PropTypes} from 'react'
import {getUnfulfilledRoleComponent} from './components/UnfulfilledRole'
function Sanity({roles}) {
function getRole(roleName) {
const fulfiller = roles[roleName]
if (!fulfiller) {
return null
}
return Array.isArray(fulfiller)
? fulfiller.map(getModule)
: getModule(fulfiller)
}
function getComponents(wanted) {
return Object.keys(wanted).reduce((target, key) => {
const role = typeof wanted[key] === 'string'
? {name: wanted[key]}
: wanted[key]
target[key] = getRole(role.name) || getUnfulfilledRoleComponent(role)
return target
}, {})
}
function getPluginForRole(roleName) {
return roles[roleName] && roles[roleName].plugin
}
return {
getRole,
getComponents,
getPluginForRole
}
}
function getModule(fulfiller) {
return fulfiller.module.__esModule && fulfiller.module.default
? fulfiller.module.default
: fulfiller.module
}
export const sanityShape = {
sanity: PropTypes.shape({
getRole: PropTypes.func.isRequired,
getComponents: PropTypes.func.isRequired,
getPluginForRole: PropTypes.func.isRequired
})
}
export default Sanity
|
import {PropTypes} from 'react'
import {getUnfulfilledRoleComponent} from './components/UnfulfilledRole'
function Sanity({roles}) {
function getRole(roleName) {
const fulfiller = roles[roleName]
if (!fulfiller) {
return null
}
return fulfiller.module.__esModule && fulfiller.module.default
? fulfiller.module.default
: fulfiller.module
}
function getComponents(wanted) {
return Object.keys(wanted).reduce((target, key) => {
const role = typeof wanted[key] === 'string'
? {name: wanted[key]}
: wanted[key]
target[key] = getRole(role.name) || getUnfulfilledRoleComponent(role)
return target
}, {})
}
function getPluginForRole(roleName) {
return roles[roleName] && roles[roleName].plugin
}
return {
getRole,
getComponents,
getPluginForRole
}
}
export const sanityShape = {
sanity: PropTypes.shape({
getRole: PropTypes.func.isRequired,
getComponents: PropTypes.func.isRequired,
getPluginForRole: PropTypes.func.isRequired
})
}
export default Sanity
|
Revert "changing default db prefix"
This reverts commit 6211b7b3c8fec686bc81f5293d390a3946232cc2 because Perch doesn't obey it anyway.
|
<?php
// @todo-perch
define('PERCH_LICENSE_KEY', '');
define('PERCH_DB_PREFIX', 'perch3_');
define('PERCH_TZ', 'America/Edmonton');
define('PERCH_EMAIL_FROM', '<email@example.com>');
define('PERCH_EMAIL_FROM_NAME', '<Company Name>');
define('PERCH_LOGINPATH', '/perch');
define('PERCH_PATH', str_replace(DIRECTORY_SEPARATOR.'config', '', __DIR__));
define('PERCH_CORE', PERCH_PATH.DIRECTORY_SEPARATOR.'core');
define('PERCH_RESFILEPATH', PERCH_PATH.DIRECTORY_SEPARATOR.'resources');
define('PERCH_RESPATH', PERCH_LOGINPATH.'/resources');
define('PERCH_HTML5', true);
//define('PERCH_XHTML_MARKUP', false);
define('PERCH_RWD', false);
define('PERCH_SSL', true);
// see https://docs.grabaperch.com/docs/installing-perch/configuration/security/
define('PERCH_PARANOID', true);
define('PERCH_SCHEDULE_SECRET', '<secret>');
define('PERCH_EMAIL_METHOD', 'smtp');
define('PERCH_EMAIL_HOST', 'smtp.sparkpostmail.com');
define('PERCH_EMAIL_AUTH', true);
define('PERCH_EMAIL_SECURE', 'tls');
define('PERCH_EMAIL_PORT', 587);
require_once('config_private.php');
|
<?php
// @todo-perch
define('PERCH_LICENSE_KEY', '');
define('PERCH_DB_PREFIX', 'perch_');
define('PERCH_TZ', 'America/Edmonton');
define('PERCH_EMAIL_FROM', '<email@example.com>');
define('PERCH_EMAIL_FROM_NAME', '<Company Name>');
define('PERCH_LOGINPATH', '/perch');
define('PERCH_PATH', str_replace(DIRECTORY_SEPARATOR.'config', '', __DIR__));
define('PERCH_CORE', PERCH_PATH.DIRECTORY_SEPARATOR.'core');
define('PERCH_RESFILEPATH', PERCH_PATH.DIRECTORY_SEPARATOR.'resources');
define('PERCH_RESPATH', PERCH_LOGINPATH.'/resources');
define('PERCH_HTML5', true);
//define('PERCH_XHTML_MARKUP', false);
define('PERCH_RWD', false);
define('PERCH_SSL', true);
// see https://docs.grabaperch.com/docs/installing-perch/configuration/security/
define('PERCH_PARANOID', true);
define('PERCH_SCHEDULE_SECRET', '<secret>');
define('PERCH_EMAIL_METHOD', 'smtp');
define('PERCH_EMAIL_HOST', 'smtp.sparkpostmail.com');
define('PERCH_EMAIL_AUTH', true);
define('PERCH_EMAIL_SECURE', 'tls');
define('PERCH_EMAIL_PORT', 587);
require_once('config_private.php');
|
Fix wrong click-action binding for loggedin menu
Signed-off-by: Fran Diéguez <1a0d2d7b2e688322d0c86dcf5420732151ae4348@mabishu.com>
|
<?php
class Application_View_Helper_Loggedin extends Zend_View_Helper_Abstract
{
public function loggedin()
{
$menuLoggedIn = '';
$auth = Zend_Auth::getInstance();
$data = $auth->getStorage()->read();
$menuLoggedIn .= "<ul class='nav secondary-nav'>
<li class='dropdown'>
<a class='dropdown-toggle' data-toggle=\"dropdown\" href='#'>".$data['name']."</a>
<ul class='dropdown-menu'>
<li><a href='/usuarios/usuarios/modificardatos'>".Zend_Registry::get('Zend_Translate')->translate('m011')."</a></li>
<li><a href='#'>".Zend_Registry::get('Zend_Translate')->translate('m013')."</a></li>
<li class='divider'></li>
<li><a href='/usuarios/usuarios/logout'>".Zend_Registry::get('Zend_Translate')->translate('m012')."</a></li>
</ul>
</li>
</ul>";
return $menuLoggedIn;
}
}
|
<?php
class Application_View_Helper_Loggedin extends Zend_View_Helper_Abstract
{
public function loggedin()
{
$menuLoggedIn = '';
$auth = Zend_Auth::getInstance();
$data = $auth->getStorage()->read();
$menuLoggedIn .= "<ul class='nav secondary-nav'>
<li class='dropdown'>
<a class='dropdown-toggle' href='#'>".$data['name']."</a>
<ul class='dropdown-menu'>
<li><a href='/usuarios/usuarios/modificardatos'>".Zend_Registry::get('Zend_Translate')->translate('m011')."</a></li>
<li><a href='#'>".Zend_Registry::get('Zend_Translate')->translate('m013')."</a></li>
<li class='divider'></li>
<li><a href='/usuarios/usuarios/logout'>".Zend_Registry::get('Zend_Translate')->translate('m012')."</a></li>
</ul>
</li>
</ul>";
return $menuLoggedIn;
}
}
|
Fix travis CI build error (missing trailing comma)
|
'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
optipng: { optimizationLevel: 7 },
gifsicle: { optimizationLevel: 3 },
pngquant: { quality: '65-90', speed: 4 },
svgo: {
plugins: [
{ removeUnknownsAndDefaults: false },
{ cleanupIDs: false },
{ removeViewBox: false },
],
},
plugins: [imageminMozjpeg({ quality: 75 })],
disable: (config.enabled.watcher),
}),
],
};
|
'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
optipng: { optimizationLevel: 7 },
gifsicle: { optimizationLevel: 3 },
pngquant: { quality: '65-90', speed: 4 },
svgo: {
plugins: [
{ removeUnknownsAndDefaults: false },
{ cleanupIDs: false },
{ removeViewBox: false }
],
},
plugins: [imageminMozjpeg({ quality: 75 })],
disable: (config.enabled.watcher),
}),
],
};
|
Use prop() instead of removeAttr()
According to the jQuery upgrade guide:
> It is almost always a mistake to use .removeAttr("checked") on a DOM
> element. The only time it might be useful is if the DOM is later going
> to be serialized back to an HTML string. In all other cases,
> .prop("checked", false) should be used instead.
|
(function() {
"use strict";
App.LegislationAdmin = {
initialize: function() {
$(".legislation-process-form").find("[name$='enabled]'],[name$='[published]']").on({
change: function() {
var checkbox;
checkbox = $(this);
checkbox.closest("fieldset").find("input[type='date']").each(function() {
$(this).prop("disabled", !checkbox.is(":checked"));
});
}
}).trigger("change");
$("#nested_question_options").on("cocoon:after-insert", function() {
App.Globalize.refresh_visible_translations();
});
}
};
}).call(this);
|
(function() {
"use strict";
App.LegislationAdmin = {
initialize: function() {
$(".legislation-process-form").find("[name$='enabled]'],[name$='[published]']").on({
change: function() {
var checkbox;
checkbox = $(this);
checkbox.closest("fieldset").find("input[type='date']").each(function() {
if (checkbox.is(":checked")) {
$(this).removeAttr("disabled");
} else {
$(this).prop("disabled", true);
}
});
}
}).trigger("change");
$("#nested_question_options").on("cocoon:after-insert", function() {
App.Globalize.refresh_visible_translations();
});
}
};
}).call(this);
|
Drop recurring_cost in favour of pro_rata boolean
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var ProductType = require("./producttype_model");
var Location = require("./location_model");
var ProductSchema = new Schema({
name: String,
description: String,
location_id: { type: ObjectId, ref: 'Location' },
producttype_id: { type: ObjectId, ref: 'ProductType' },
price: { type: Number, validate: function(v) { return (v > 0); }, required: true },
member_discount: { type: Number, default: 0 },
topup_size: Number,
volume: Number,
xero_account: String,
xero_code: { type: String, index: true },
xero_id: String,
payment_options: [ { type: String, validate: /stuff|space|creditcard|account/, required: true } ],
self_service: { type: Boolean, default: false, index: true },
date_created: { type: Date, default: Date.now },
pro_rata: { type: Boolean, default: false, index: true },
_owner_id: ObjectId,
_deleted: { type: Boolean, default: false, index: true },
});
ProductSchema.set("_perms", {
admin: "crud",
owner: "r",
user: "r",
all: "r"
});
module.exports = mongoose.model('Product', ProductSchema);
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var ProductType = require("./producttype_model");
var Location = require("./location_model");
var ProductSchema = new Schema({
name: String,
description: String,
location_id: { type: ObjectId, ref: 'Location' },
producttype_id: { type: ObjectId, ref: 'ProductType' },
price: { type: Number, validate: function(v) { return (v > 0); }, required: true },
member_discount: { type: Number, default: 0 },
topup_size: Number,
volume: Number,
xero_account: String,
xero_code: { type: String, index: true },
xero_id: String,
payment_options: [ { type: String, validate: /stuff|space|creditcard|account/, required: true } ],
self_service: { type: Boolean, default: false, index: true },
date_created: { type: Date, default: Date.now },
recurring_cost: { type: String, validate: /once-off|monthly|annually/, default: "monthly" },
_owner_id: ObjectId,
_deleted: { type: Boolean, default: false, index: true },
});
ProductSchema.set("_perms", {
admin: "crud",
owner: "r",
user: "r",
all: "r"
});
module.exports = mongoose.model('Product', ProductSchema);
|
Patch out DNS resolver in makeService tests.
|
from vumi_http_proxy.servicemaker import (
Options, ProxyWorkerServiceMaker, client)
from vumi_http_proxy import http_proxy
from twisted.trial import unittest
from vumi_http_proxy.test import helpers
class TestOptions(unittest.TestCase):
def test_defaults(self):
options = Options()
options.parseOptions([])
self.assertEqual(options["port"], 8080)
self.assertEqual(str(options["interface"]), "0.0.0.0")
def test_override(self):
options = Options()
options.parseOptions(["--port", 8000])
options.parseOptions(["--interface", "127.0.0.1"])
self.assertEqual(options["port"], "8000")
self.assertEqual(str(options["interface"]), "127.0.0.1")
class TestProxyWorkerServiceMaker(unittest.TestCase):
def test_makeService(self):
options = Options()
options.parseOptions([])
self.patch(client, 'createResolver', lambda: helpers.TestResolver())
servicemaker = ProxyWorkerServiceMaker()
service = servicemaker.makeService(options)
self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory))
self.assertEqual(service.endpoint._interface, '0.0.0.0')
self.assertEqual(service.endpoint._port, 8080)
|
from vumi_http_proxy.servicemaker import Options, ProxyWorkerServiceMaker
from vumi_http_proxy import http_proxy
from twisted.trial import unittest
class TestOptions(unittest.TestCase):
def test_defaults(self):
options = Options()
options.parseOptions([])
self.assertEqual(options["port"], 8080)
self.assertEqual(str(options["interface"]), "0.0.0.0")
def test_override(self):
options = Options()
options.parseOptions(["--port", 8000])
options.parseOptions(["--interface", "127.0.0.1"])
self.assertEqual(options["port"], "8000")
self.assertEqual(str(options["interface"]), "127.0.0.1")
class TestProxyWorkerServiceMaker(unittest.TestCase):
def test_makeService(self):
options = Options()
options.parseOptions([])
servicemaker = ProxyWorkerServiceMaker()
service = servicemaker.makeService(options)
self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory))
self.assertEqual(service.endpoint._interface, '0.0.0.0')
self.assertEqual(service.endpoint._port, 8080)
|
Add test for Groovy findById() function
|
var should = require('should');
var mogwai = require('../');
var UserSchema = new mogwai.Schema({
name: String
});
User = mogwai.model('User', UserSchema);
var user;
describe('Model', function() {
it('should instantiate a new model', function() {
user = new User();
user.should.be.an.instanceOf(model);
});
it('should have properties', function() {
user.foo = 'bar';
user.should.have.property('foo', 'bar');
});
describe('save()', function() {
it('should insert a new model to the graph database', function(done) {
user.save(function(err, user, response) {
should.not.exist(err);
should.exist(response);
done();
});
});
});
describe('findById()', function() {
it('should find a user by id', function() {
user.scripts.findById(user._id).query(function(err, response) {
should.not.exist(err);
should.exist(response);
});
});
});
});
|
var should = require('should');
var mogwai = require('../');
var UserSchema = new mogwai.Schema({
name: String
});
User = mogwai.model('User', UserSchema);
var user;
describe('Model', function() {
it('should instantiate a new model', function() {
user = new User();
user.should.be.an.instanceOf(model);
});
it('should have properties', function() {
user.foo = 'bar';
user.should.have.property('foo', 'bar');
});
describe('save()', function() {
it('should insert a new model to the graph database', function(done) {
user.save(function(err, user, response) {
should.not.exist(err);
should.exist(response);
done();
});
});
});
});
|
Switch from JSX to render functions
|
// Webpack config to serve the JSX component with bundled styles
import path from 'path';
const demoPath = path.join(__dirname, './demo');
const sourcePath = path.join(__dirname, './src');
export default {
entry: {
js: [demoPath.concat('/render.js')],
},
output: {
path: demoPath,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.css$/,
loaders: [
'style-loader',
{
loader: 'css-loader',
query: {
modules: true,
},
},
],
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [
path.resolve(__dirname, 'node_modules'),
sourcePath,
],
},
};
|
// Webpack config to serve the JSX component with bundled styles
import path from 'path';
const demoPath = path.join(__dirname, './demo');
const jsxPath = path.join(__dirname, './jsx');
export default {
entry: {
js: [demoPath.concat('/render.js')],
},
output: {
path: demoPath,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.css$/,
loaders: [
'style-loader',
{
loader: 'css-loader',
query: {
modules: true,
},
},
],
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [
path.resolve(__dirname, 'node_modules'),
jsxPath,
],
},
};
|
Use io.open with encoding='utf-8' and flake8 compliance
|
import io
from setuptools import setup, find_packages
long_description = '\n'.join((
io.open('README.rst', encoding='utf-8').read(),
io.open('CHANGES.txt', encoding='utf-8').read()
))
setup(
name='more.forwarded',
version='0.3.dev0',
description="Forwarded header support for Morepath",
long_description=long_description,
author="Martijn Faassen",
author_email="faassen@startifact.com",
keywords='morepath forwarded',
license="BSD",
url="http://pypi.python.org/pypi/more.static",
namespace_packages=['more'],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'morepath > 0.13.2',
],
extras_require=dict(
test=[
'pytest >= 2.0',
'pytest-cov',
'WebTest >= 2.0.14'
],
),
)
|
from setuptools import setup, find_packages
long_description = (
open('README.rst').read()
+ '\n' +
open('CHANGES.txt').read())
setup(
name='more.forwarded',
version='0.3.dev0',
description="Forwarded header support for Morepath",
long_description=long_description,
author="Martijn Faassen",
author_email="faassen@startifact.com",
keywords='morepath forwarded',
license="BSD",
url="http://pypi.python.org/pypi/more.static",
namespace_packages=['more'],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'morepath > 0.13.2',
],
extras_require=dict(
test=[
'pytest >= 2.0',
'pytest-cov',
'WebTest >= 2.0.14'
],
),
)
|
Add path to XML schema
|
/*
* PerfClispe
*
*
* Copyright (c) 2014 Jakub Knetl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.perfclipse;
/**
* @author kuba
*
*/
public class PerfClipseConstants {
public static final String PERFCAKE_BUNDLE = "org.perfcake";
public static final String PERFCAKE_XML_SCHEMA_PATH = "schemas/perfcake-scenario-1.0.xsd";
public static final String PERFCAKE_SENDER_PACKAGE = "org.perfcake.message.sender";
public static final String PERFCAKE_GENERATOR_PACKAGE = "org.perfcake.message.generator";
public static final String PERFCAKE_REPORTER_PACKAGE = "org.perfcake.reporting.reporters";
public static final String PERFCAKE_DESTINATION_PACKAGE = "org.perfcake.reporting.destinations";
public static final String PERFCAKE_VALIDATOR_PACKAGE = "org.perfcake.validation";
}
|
/*
* PerfClispe
*
*
* Copyright (c) 2014 Jakub Knetl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.perfclipse;
/**
* @author kuba
*
*/
public class PerfClipseConstants {
public static final String PERFCAKE_BUNDLE = "org.perfcake";
public static final String PERFCAKE_SENDER_PACKAGE = "org.perfcake.message.sender";
public static final String PERFCAKE_GENERATOR_PACKAGE = "org.perfcake.message.generator";
public static final String PERFCAKE_REPORTER_PACKAGE = "org.perfcake.reporting.reporters";
public static final String PERFCAKE_DESTINATION_PACKAGE = "org.perfcake.reporting.destinations";
public static final String PERFCAKE_VALIDATOR_PACKAGE = "org.perfcake.validation";
}
|
Use explicit addEventListener instead of onclick
|
/* -------------------------------------------------------------------------- *\
JavaScript for animated navigation bar
--------------------------------------------------------------------------
This file is part of XML-to-bootstrap.
https://github.com/acch/XML-to-bootstrap
Copyright 2016 Achim Christ
Released under the MIT license
(https://github.com/acch/XML-to-bootstrap/blob/master/LICENSE)
\* -------------------------------------------------------------------------- */
(function() {
// construct Headroom
var headroom = new Headroom(document.querySelector(".js-nvbr"), {
"offset": Options.navbarOffset,
"tolerance": Options.navbarTolerance
});
// initialize Headroom
headroom.init();
// add click events to sidebar nav links
document.addEventListener("DOMContentLoaded", function() {
// choose elements to add click event to
var elements = document.getElementsByClassName("x2b-sdbr-entry");
// iterate over elements
for (var i = 0; elements[i]; ++i) {
// add click event
elements[i].addEventListener("click", function() {
// fudge scroll position to make Headroom pin
headroom.lastKnownScrollY = headroom.getScrollerHeight();
// make Headroom pin even if scroll position has not changed
window.requestAnimationFrame(function() { headroom.pin() });
});
}
});
})();
|
/* -------------------------------------------------------------------------- *\
JavaScript for animated navigation bar
--------------------------------------------------------------------------
This file is part of XML-to-bootstrap.
https://github.com/acch/XML-to-bootstrap
Copyright 2016 Achim Christ
Released under the MIT license
(https://github.com/acch/XML-to-bootstrap/blob/master/LICENSE)
\* -------------------------------------------------------------------------- */
(function() {
// construct Headroom
var headroom = new Headroom(document.querySelector(".js-nvbr"), {
"offset": Options.navbarOffset,
"tolerance": Options.navbarTolerance
});
// initialize Headroom
headroom.init();
// add click events to sidebar nav links
document.addEventListener("DOMContentLoaded", function() {
// choose elements to add click event to
var elements = document.getElementsByClassName("x2b-sdbr-entry");
// iterate over elements
for (var i = 0; elements[i]; ++i) {
// add click event
elements[i].onclick = function() {
// fudge scroll position to make Headroom pin
headroom.lastKnownScrollY = headroom.getScrollerHeight();
// make Headroom pin even if scroll position has not changed
window.requestAnimationFrame(function() { headroom.pin() });
}
}
});
})();
|
Fix error message in CLI mode
|
<?php
/**
* Hendle every http errors.
*
* @author Iskandar Soesman <k4ndar@yahoo.com>
* @link http://panadaframework.com/
* @license http://www.opensource.org/licenses/bsd-license.php
* @since version 1.0.0
* @package Resources
*/
namespace Resources;
class HttpException extends \Exception
{
public function __construct($message = null, $code = 0, Exception $previous = null)
{
set_exception_handler( array($this, 'main') );
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function main($exception)
{
self::outputError($exception->getMessage());
}
public static function outputError($message = null)
{
if(PHP_SAPI == 'cli')
exit($message."\n");
// Write the error to log file
@error_log('Error 404 Page Not Found: '.$_SERVER['REQUEST_URI']);
header('HTTP/1.1 404 Not Found', true, 500);
\Resources\Controller::outputError('errors/404', array('message' => $message) );
}
}
|
<?php
/**
* Hendle every http errors.
*
* @author Iskandar Soesman <k4ndar@yahoo.com>
* @link http://panadaframework.com/
* @license http://www.opensource.org/licenses/bsd-license.php
* @since version 1.0.0
* @package Resources
*/
namespace Resources;
class HttpException extends \Exception
{
public function __construct($message = null, $code = 0, Exception $previous = null)
{
set_exception_handler( array($this, 'main') );
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function main($exception)
{
self::outputError($exception->getMessage());
}
public static function outputError($message = null)
{
// Write the error to log file
@error_log('Error 404 Page Not Found: '.$_SERVER['REQUEST_URI']);
header('HTTP/1.1 404 Not Found', true, 500);
\Resources\Controller::outputError('errors/404', array('message' => $message) );
}
}
|
Fix bug when "Show New Instances" action is enabled, but tracker is not ready
|
package org.jetbrains.debugger.memory.action;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.xdebugger.XDebugSession;
import com.sun.jdi.ReferenceType;
import org.jetbrains.debugger.memory.utils.InstancesProvider;
import org.jetbrains.debugger.memory.view.ClassesTable;
import org.jetbrains.debugger.memory.view.InstancesWindow;
public class ShowNewInstancesAction extends ClassesActionBase {
@Override
protected boolean isEnabled(AnActionEvent e) {
XDebugSession session = getDebugSession(e);
ReferenceType selectedClass = getSelectedClass(e);
InstancesProvider provider = e.getData(ClassesTable.NEW_INSTANCES_PROVIDER_KEY);
return super.isEnabled(e) && session != null && selectedClass != null && provider != null;
}
@Override
protected void perform(AnActionEvent e) {
XDebugSession session = getDebugSession(e);
ReferenceType selectedClass = getSelectedClass(e);
InstancesProvider provider = e.getData(ClassesTable.NEW_INSTANCES_PROVIDER_KEY);
if(selectedClass != null && provider != null && session != null) {
new InstancesWindow(session, provider, selectedClass.name()).show();
}
}
}
|
package org.jetbrains.debugger.memory.action;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.xdebugger.XDebugSession;
import com.sun.jdi.ReferenceType;
import org.jetbrains.debugger.memory.component.InstancesTracker;
import org.jetbrains.debugger.memory.utils.InstancesProvider;
import org.jetbrains.debugger.memory.view.ClassesTable;
import org.jetbrains.debugger.memory.view.InstancesWindow;
public class ShowNewInstancesAction extends ClassesActionBase {
@Override
protected boolean isEnabled(AnActionEvent e) {
Project project = e.getProject();
ReferenceType selectedClass = getSelectedClass(e);
return super.isEnabled(e) && selectedClass != null &&
project != null && InstancesTracker.getInstance(project).isTracked(selectedClass.name());
}
@Override
protected void perform(AnActionEvent e) {
XDebugSession session = getDebugSession(e);
ReferenceType selectedClass = getSelectedClass(e);
InstancesProvider provider = e.getData(ClassesTable.NEW_INSTANCES_PROVIDER_KEY);
if(selectedClass != null && provider != null && session != null) {
new InstancesWindow(session, provider, selectedClass.name()).show();
}
}
}
|
Extend browser no activity timeout to 3 minutes.
|
// This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var webpackConfig = require('../../build/webpack.test.conf')
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
browserNoActivityTimeout: 180000, // 3 mins
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}
|
// This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var webpackConfig = require('../../build/webpack.test.conf')
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}
|
Add y to the check true function
This is an obvious omision.
|
from fabric.api import hide, settings
from fabric.colors import blue
from contextlib import contextmanager
def header(txt):
"""Decorate a string to make it stand out as a header. """
wrapper = "------------------------------------------------------"
return blue(wrapper + "\n" + txt + "\n" + wrapper, bold=True)
@contextmanager
def mute():
"""Run a fabric command without reporting any responses to the user. """
with settings(warn_only='true'):
with hide('running', 'stdout', 'stderr', 'warnings'):
yield
def check_true(string):
""" Check if an English string seems to contain truth.
Return a boolean
Default to returning a False value unless truth is found.
"""
string = string.lower()
if string in ['true', 'yes', 'y', '1', 'yep', 'yeah']:
return True
else:
return False
|
from fabric.api import hide, settings
from fabric.colors import blue
from contextlib import contextmanager
def header(txt):
"""Decorate a string to make it stand out as a header. """
wrapper = "------------------------------------------------------"
return blue(wrapper + "\n" + txt + "\n" + wrapper, bold=True)
@contextmanager
def mute():
"""Run a fabric command without reporting any responses to the user. """
with settings(warn_only='true'):
with hide('running', 'stdout', 'stderr', 'warnings'):
yield
def check_true(string):
""" Check if an English string seems to contain truth.
Return a boolean
Default to returning a False value unless truth is found.
"""
string = string.lower()
if string in ['true', 'yes', '1', 'yep', 'yeah']:
return True
else:
return False
|
Make the chart bigger and add hook for colours
|
<!-- resources/views/dashboard/survey_graph.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Survey Count Graphs</h2>
{{--
{!! Charts::assets(['google']) !!}
<div class="panel panel-default">
<div class="panel-body">
<p>{!! $allYears->render() !!}</p>
</div>
</div>
@foreach ($yearCharts as $yearChart)
<div class="panel panel-default">
<div class="panel-body">
<p>{!! $yearChart->render() !!}</p>
</div>
</div>
--}}
<!-- Chart's container -->
<div id="chart" style="height: 600px;"></div>
<!-- Charting library -->
<script src="https://unpkg.com/chart.js@2.9.3/dist/Chart.min.js"></script>
<!-- Chartisan -->
<script src="https://unpkg.com/@chartisan/chartjs@^2.1.0/dist/chartisan_chartjs.umd.js"></script>
<!-- Your application script -->
<script>
const chart = new Chartisan({
el: '#chart',
url: "@chart('survey_graph')",
hooks: new ChartisanHooks()
.colors(),
});
</script>
@endsection
|
<!-- resources/views/dashboard/survey_graph.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Survey Count Graphs</h2>
{{--
{!! Charts::assets(['google']) !!}
<div class="panel panel-default">
<div class="panel-body">
<p>{!! $allYears->render() !!}</p>
</div>
</div>
@foreach ($yearCharts as $yearChart)
<div class="panel panel-default">
<div class="panel-body">
<p>{!! $yearChart->render() !!}</p>
</div>
</div>
--}}
<!-- Chart's container -->
<div id="chart" style="height: 300px;"></div>
<!-- Charting library -->
<script src="https://unpkg.com/chart.js@2.9.3/dist/Chart.min.js"></script>
<!-- Chartisan -->
<script src="https://unpkg.com/@chartisan/chartjs@^2.1.0/dist/chartisan_chartjs.umd.js"></script>
<!-- Your application script -->
<script>
const chart = new Chartisan({
el: '#chart',
url: "@chart('survey_graph')",
});
</script>
@endsection
|
Edit form now pulls live data
|
'use strict';
angular
.module('app.controllers')
.controller('EditCtrl', function($scope, $rootScope, $stateParams, $sce, $interval, Restangular, apiDescription, formElementProvider) {
var resourceName = $stateParams.resourceName,
resourceId = //$stateParams.id;
'53f54dd98d1e62ff12539dbb'; // test id
$scope.rdesc = apiDescription.resource(resourceName);
$scope.fep = formElementProvider;
$scope.model = Restangular.one(resourceName, resourceId).get().$object;
$interval(function() { console.log($scope.model); }, 500);
// var resource = Restangular.one(resourceName, resourceId);
// resource.get()
// .then(function(live) {
// // // transform schools to String
// // presenter.schools = presenter.schools.join(',');
// // // format date for input[type=date]
// // if (presenter.graduationDate) {
// // presenter.graduationDate = presenter.graduationDate.formatForInputTypeDate(); // see js/lib/extentions.js
// // }
// // $scope.presenter = Restangular.stripRestangular(presenter);
// $scope.model =
// });
// FAKE, but more or less like this...
// $scope.updateResource = function() {
// console.log($scope.presenter);
// // resource.put($scope.presenter); ClayReedA gets 403 Forbidden
// };
});
|
'use strict';
angular
.module('app.controllers')
.controller('EditCtrl', function($scope, $rootScope, $stateParams, $sce, $interval, Restangular, apiDescription, formElementProvider) {
var resourceName = $stateParams.resourceName,
resourceId = //$stateParams.id;
'53f54dd98d1e62ff12539dbb'; // test id
$scope.rdesc = apiDescription.resource(resourceName);
$scope.fep = formElementProvider;
$scope.model = {};
console.log($scope.rdesc);
$interval(function() { console.log($scope.model); }, 500);
var resource = Restangular.one(resourceName, resourceId);
resource.get()
.then(function(presenter) {
// // transform schools to String
// presenter.schools = presenter.schools.join(',');
// // format date for input[type=date]
// if (presenter.graduationDate) {
// presenter.graduationDate = presenter.graduationDate.formatForInputTypeDate(); // see js/lib/extentions.js
// }
// $scope.presenter = Restangular.stripRestangular(presenter);
});
// FAKE, but more or less like this...
$scope.updateResource = function() {
console.log($scope.presenter);
// resource.put($scope.presenter); ClayReedA gets 403 Forbidden
};
});
|
Allow empty calendar to be drawn
|
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
"allow_empty": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
|
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
|
Make pylint happy as per graphite-web example
|
import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk # noqa # pylint: disable=unused-import
except ImportError:
from scandir import scandir, walk # noqa # pylint: disable=unused-import
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
metric_regex = re.compile(".*\.%s$" % metric_suffix)
storage_dir = storage_dir.rstrip(os.sep)
for root, _, filenames in walk(storage_dir, followlinks=follow_sym_links):
for filename in filenames:
if metric_regex.match(filename):
root_path = root[len(storage_dir) + 1:]
m_path = os.path.join(root_path, filename)
m_name, m_ext = os.path.splitext(m_path)
m_name = m_name.replace('/', '.')
yield m_name
|
import os
import re
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
def listMetrics(storage_dir, follow_sym_links=False, metric_suffix='wsp'):
metric_regex = re.compile(".*\.%s$" % metric_suffix)
storage_dir = storage_dir.rstrip(os.sep)
for root, dirnames, filenames in walk(storage_dir,
followlinks=follow_sym_links):
for filename in filenames:
if metric_regex.match(filename):
root_path = root[len(storage_dir) + 1:]
m_path = os.path.join(root_path, filename)
m_name, m_ext = os.path.splitext(m_path)
m_name = m_name.replace('/', '.')
yield m_name
|
Add utils tests into testing module.
|
__author__ = 'To\xc3\xb1o G. Quintela (tgq.spm@gmail.com)'
__version__ = '0.0.0'
#from pyCausality.TimeSeries.TS import *
#from pyCausality.TimeSeries.automatic_thresholding import *
#from pyCausality.TimeSeries.distances import *
#from pyCausality.TimeSeries.measures import *
#from pyCausality.TimeSeries.smoothing import *
#from pyCausality.TimeSeries.transformations import *
from tests import test_artificial_data
from tests import test_utils
from tests import test_measures
from tests import test_transformations
from tests import test_burstdetection
from tests import test_tsstatistics
from tests import test_regimedetection
from tests import test_feature_extraction
from tests import test_similarities
## Administrative information
import release
import version
## Not inform about warnings
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
warnings.simplefilter("ignore")
def test():
## Tests of modules
test_artificial_data.test()
test_utils.test()
# test_measures.test()
test_transformations.test()
test_burstdetection.test()
# test_tsstatistics.test()
test_regimedetection.test()
test_feature_extraction.test()
test_similarities.test()
|
__author__ = 'To\xc3\xb1o G. Quintela (tgq.spm@gmail.com)'
__version__ = '0.0.0'
#from pyCausality.TimeSeries.TS import *
#from pyCausality.TimeSeries.automatic_thresholding import *
#from pyCausality.TimeSeries.distances import *
#from pyCausality.TimeSeries.measures import *
#from pyCausality.TimeSeries.smoothing import *
#from pyCausality.TimeSeries.transformations import *
from tests import test_artificial_data
from tests import test_utils
from tests import test_measures
from tests import test_transformations
from tests import test_burstdetection
from tests import test_tsstatistics
from tests import test_regimedetection
from tests import test_feature_extraction
from tests import test_similarities
## Administrative information
import release
import version
## Not inform about warnings
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
warnings.simplefilter("ignore")
def test():
## Tests of modules
test_artificial_data.test()
# test_utils.test()
# test_measures.test()
test_transformations.test()
test_burstdetection.test()
# test_tsstatistics.test()
test_regimedetection.test()
test_feature_extraction.test()
test_similarities.test()
|
Fix user timeout setInterval interval value
|
if (Rooms.find().count() === 0) {
Meteor.call('createRoom');
}
Meteor.publish('rooms', function() {
return Rooms.find();
});
Rooms.allow({
insert: ()=> false,
update: ()=> false,
remove: ()=> false
});
Meteor.publish(null, function() {
return Connections.find();
});
// server code: heartbeat method
Meteor.methods({
keepalive: function (data) {
if (!data.name) return;
if (!Connections.findOne({user_id: data.id})) {
console.log("User "+data.name+" enters");
Connections.insert({user_id: data.id, name: data.name, color: data.color});
}
Connections.update({user_id: data.id}, {$set: {last_seen: (new Date()).getTime()}});
}
});
// server code: clean up dead clients after 10 seconds
Meteor.setInterval(function () {
var now = (new Date()).getTime();
Connections.find({last_seen: {$lt: (now - 10 * 1000)}}).forEach(function (user) {
console.log("User "+user.user_id+" has disconnected");
Connections.remove(user);
});
}, 1000);
|
if (Rooms.find().count() === 0) {
Meteor.call('createRoom');
}
Meteor.publish('rooms', function() {
return Rooms.find();
});
Rooms.allow({
insert: ()=> false,
update: ()=> false,
remove: ()=> false
});
Meteor.publish(null, function() {
return Connections.find();
});
// server code: heartbeat method
Meteor.methods({
keepalive: function (data) {
if (!data.name) return
if (!Connections.findOne({user_id: data.id})) {
console.log("User "+data.name+" enters");
Connections.insert({user_id: data.id, name: data.name, color: data.color});
}
Connections.update({user_id: data.id}, {$set: {last_seen: (new Date()).getTime()}});
}
});
// server code: clean up dead clients after 10 seconds
Meteor.setInterval(function () {
var now = (new Date()).getTime();
Connections.find({last_seen: {$lt: (now - 10 * 1000)}}).forEach(function (user) {
console.log("User "+user.user_id+" has disconnected");
Connections.remove(user);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.