text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix issue with trailing semicolon | 'use strict';
var helpers = require('../helpers');
var trailingZeroRegex = /^(\d+\.|\.)+(\d*?[1-9])0+$/;
module.exports = {
'name': 'no-trailing-zero',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('number', function (num) {
if (num.content.match(trailingZeroRegex)) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': num.start.line,
'column': num.start.column,
'message': 'Don\'t include trailing zeros on numbers',
'severity': parser.severity
});
}
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
var trailingZeroRegex = /^(\d+\.|\.)+(\d*?[1-9])0+$/;
module.exports = {
'name': 'no-trailing-zero',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('number', function (num) {
if (num.content.match(trailingZeroRegex)) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': num.start.line,
'column': num.start.column,
'message': 'Don\'t include trailing zeros on numbers',
'severity': parser.severity
});
}
});
return result;
}
}
|
Allow content editors to edit banners. | <?php
class BannerImage extends DataObject{
private static $db = array(
'Title' => 'Varchar(255)',
'SubTitle' => 'Varchar(255)',
'Link' => 'LinkField',
'Sort' => 'Int'
);
private static $has_one = array(
'Image' => 'Image',
'Parent' => 'Page'
);
private static $summary_fields = array(
'Image.CMSThumbnail' => 'Image',
'CMSTitle' => 'Title',
'Link' => 'Link'
);
private static $default_sort = "\"Sort\" ASC, \"ID\" ASC";
public function getCMSFields(){
$fields = parent::getCMSFields();
$image = $fields->fieldByName('Root.Main.Image');
$fields->removeByName('Image');
$fields->insertBefore($image,'Title');
$fields->removeByName('ParentID');
$fields->removeByName('Sort');
return $fields;
}
function getCMSTitle(){
if($this->Title){
return $this->Title;
}
if($this->Image()){
return $this->Image()->Title;
}
}
public function canCreate($member = null) {
return Permission::check("CMS_ACCESS_CMSMain");
}
public function canEdit($member = null) {
return Permission::check("CMS_ACCESS_CMSMain");
}
public function canDelete($member = null) {
return Permission::check("CMS_ACCESS_CMSMain");
}
public function canView($member = null) {
return Permission::check("CMS_ACCESS_CMSMain");
}
} | <?php
class BannerImage extends DataObject{
private static $db = array(
'Title' => 'Varchar(255)',
'SubTitle' => 'Varchar(255)',
'Link' => 'LinkField',
'Sort' => 'Int'
);
private static $has_one = array(
'Image' => 'Image',
'Parent' => 'Page'
);
private static $summary_fields = array(
'Image.CMSThumbnail' => 'Image',
'CMSTitle' => 'Title',
'Link' => 'Link'
);
private static $default_sort = "\"Sort\" ASC, \"ID\" ASC";
public function getCMSFields(){
$fields = parent::getCMSFields();
$image = $fields->fieldByName('Root.Main.Image');
$fields->removeByName('Image');
$fields->insertBefore($image,'Title');
$fields->removeByName('ParentID');
$fields->removeByName('Sort');
return $fields;
}
function getCMSTitle(){
if($this->Title){
return $this->Title;
}
if($this->Image()){
return $this->Image()->Title;
}
}
} |
Add CLI instructions for using multiple packages. | #!/usr/bin/env node
'use strict';
var gulp = require('gulp')
require('../gulpfile');
require('coa').Cmd() // main (top level) command declaration
.name(process.argv[1]) // set top level command name from program name
.title('Vaadin GWT Metamorphosis GWT API Client Forge') // title for use in text messages
.helpful() // make command "helpful", i.e. options -h --help with usage message
.act(function() {
console.log(this.usage());
})
.opt() // add some option
.name('version') // name for use in API
.title('Version') // title for use in text messages
.short('v') // short key: -v
.long('version') // long key: --version
.flag() // for options without value
.act(function(opts) { // add action for option
//return message as result of action
return JSON.parse(require('fs').readFileSync(__dirname + '/../package.json'))
.version;
})
.end()
.cmd()
.name('polymer')
.title('Generate GWT API from Polymer API')
.helpful()
.opt()
.name('package')
.req()
.title('Bower package(s) to use. Multiple packages can be defined with: package="foo bar" or package=foo,bar')
.long('package')
.act(function() {
gulp.start('default');
})
.end()
.end()
.run(process.argv.slice(2)); | #!/usr/bin/env node
'use strict';
var gulp = require('gulp')
require('../gulpfile');
require('coa').Cmd() // main (top level) command declaration
.name(process.argv[1]) // set top level command name from program name
.title('Vaadin GWT Metamorphosis GWT API Client Forge') // title for use in text messages
.helpful() // make command "helpful", i.e. options -h --help with usage message
.act(function() {
console.log(this.usage());
})
.opt() // add some option
.name('version') // name for use in API
.title('Version') // title for use in text messages
.short('v') // short key: -v
.long('version') // long key: --version
.flag() // for options without value
.act(function(opts) { // add action for option
//return message as result of action
return JSON.parse(require('fs').readFileSync(__dirname + '/../package.json'))
.version;
})
.end()
.cmd()
.name('polymer')
.title('Generate GWT API from Polymer API')
.helpful()
.opt()
.name('package')
.req()
.title('Bower package to use')
.long('package')
.act(function() {
gulp.start('default');
})
.end()
.end()
.run(process.argv.slice(2)); |
Make sure we ask callers for the "type" field | # -*- encoding: utf-8
from flask_restplus import fields, Model
class TypedModel(Model):
"""
A thin wrapper around ``Model`` that adds a ``type`` field.
"""
def __init__(self, name, model_fields, *args, **kwargs):
# When you use a model in ``@api.response``, it triggers an internal
# cloning operation, which passes the ``model_fields`` parameter as
# a list of 2-tuples.
#
# In that case, we should already have a ``type`` field, so we
# can skip adding it.
#
if isinstance(model_fields, dict) and "type" not in model_fields:
model_fields["type"] = fields.String(
description="Type of the object",
enum=[name],
default=name,
required=True
)
super().__init__(name, model_fields, *args, **kwargs)
| # -*- encoding: utf-8
from flask_restplus import fields, Model
class TypedModel(Model):
"""
A thin wrapper around ``Model`` that adds a ``type`` field.
"""
def __init__(self, name, model_fields, *args, **kwargs):
# When you use a model in ``@api.response``, it triggers an internal
# cloning operation, which passes the ``model_fields`` parameter as
# a list of 2-tuples.
#
# In that case, we should already have a ``type`` field, so we
# can skip adding it.
#
if isinstance(model_fields, dict) and "type" not in model_fields:
model_fields["type"] = fields.String(
description="Type of the object",
enum=[name],
default=name
)
super().__init__(name, model_fields, *args, **kwargs)
|
Set setEnv defaults to undefined | const {webpack} = require('@webpack-blocks/webpack2');
/**
* Sets environment variables with all possible ways.
*/
module.exports = (options = {}) => {
const {
nodeEnv,
babelEnv,
} = options;
process.env.NODE_ENV = nodeEnv;
process.env.BABEL_ENV = babelEnv;
return () => ({
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
BABEL_ENV: JSON.stringify(babelEnv),
},
}),
new webpack.EnvironmentPlugin(['NODE_ENV', 'BABEL_ENV']),
],
});
};
| const {webpack} = require('@webpack-blocks/webpack2');
/**
* Sets environment variables with all possible ways.
*/
module.exports = (options = {}) => {
const {
nodeEnv = 'development',
babelEnv = 'development',
} = options;
process.env.NODE_ENV = nodeEnv;
process.env.BABEL_ENV = babelEnv;
return () => ({
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
BABEL_ENV: JSON.stringify(babelEnv),
},
}),
new webpack.EnvironmentPlugin(['NODE_ENV', 'BABEL_ENV']),
],
});
};
|
Fix the regex so that it catches all characters to the right of the equals-sign. | #! /usr/bin/env python
import jinja2
import sys
import re
import os
KEY_REGEX = re.compile('([A-Z]+)=(.+)')
def main():
args = sys.argv[1:]
if len(args) < 1:
raise Exception('args too short {}'.format(args))
template_file = args[0]
keyword_args = args[1:]
if not os.path.exists(template_file):
raise Exception('File "{}" does not exist'.format(template_file))
context = {}
for arg in keyword_args:
match = KEY_REGEX.match(arg)
if match:
(key, val) = match.groups()
context[key] = val
with open(template_file, 'r') as file_reader:
text = file_reader.read()
print jinja2.Template(text).render(context)
if __name__ == '__main__':
main()
| #! /usr/bin/env python
import jinja2
import sys
import re
import os
KEY_REGEX = re.compile('([A-Z]+)=(\w+)')
def main():
args = sys.argv[1:]
if len(args) < 1:
raise Exception('args too short {}'.format(args))
template_file = args[0]
keyword_args = args[1:]
if not os.path.exists(template_file):
raise Exception('File "{}" does not exist'.format(template_file))
context = {}
for arg in keyword_args:
match = KEY_REGEX.match(arg)
if match:
(key, val) = match.groups()
context[key] = val
with open(template_file, 'r') as file_reader:
text = file_reader.read()
print jinja2.Template(text).render(context)
if __name__ == '__main__':
main()
|
Improve url patterns structure, enable debugging common error pages while debugging | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.generic import TemplateView
from django.conf.urls.static import static
from django.views import defaults as default_views
urlpatterns = [
url(settings.ADMIN_URL, include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name='index.html'), name="home"),
url(r'^users/', include('users.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception("Bad Request!")}),
url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception("Permissin Denied")}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception("Page not Found")}),
url(r'^500/$', default_views.server_error),
]
| """{{project_name}} URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.generic import TemplateView
urlpatterns = [
url(settings.ADMIN_URL, include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name='index.html'), name="home"),
url(r'^users/', include('users.urls')),
]
|
Improve error message when computing a rulekey fails
Summary: This adds the field name in the context message.
Test Plan: CI
Reviewed By: elsteveogrande
fbshipit-source-id: c373b6c | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules.keys;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.util.exceptions.BuckUncheckedExecutionException;
class DefaultAlterRuleKey implements AlterRuleKey {
private final ValueExtractor valueExtractor;
DefaultAlterRuleKey(ValueExtractor valueExtractor) {
this.valueExtractor = valueExtractor;
}
@Override
public void amendKey(RuleKeyObjectSink builder, Object addsToRuleKey) {
try {
builder.setReflectively(valueExtractor.getName(), valueExtractor.getValue(addsToRuleKey));
} catch (Exception e) {
throw new BuckUncheckedExecutionException(e, "When amending %s.", valueExtractor.getName());
}
}
}
| /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules.keys;
import com.facebook.buck.rules.RuleKeyObjectSink;
class DefaultAlterRuleKey implements AlterRuleKey {
private final ValueExtractor valueExtractor;
DefaultAlterRuleKey(ValueExtractor valueExtractor) {
this.valueExtractor = valueExtractor;
}
@Override
public void amendKey(RuleKeyObjectSink builder, Object addsToRuleKey) {
builder.setReflectively(valueExtractor.getName(), valueExtractor.getValue(addsToRuleKey));
}
}
|
Use get_feed_link for RSS URL | <!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php wp_title('|', true, 'right'); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
<link href='//ajax.googleapis.com' rel='dns-prefetch' />
<% if (includeHumans) { %>
<link href='<?php echo get_stylesheet_directory_uri(); ?>/humans.txt' rel='author' type='text/plain' />
<% } %>
<% if (includeLogo) { %>
<link href='<?php echo get_stylesheet_directory_uri(); ?>/assets/img/logo.svg' rel='logo' type='image/svg' />
<% } %>
<link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo esc_url(get_feed_link()); ?>">
<meta content='false' http-equiv='imagetoolbar' />
<meta content='éGz - http://egztudio.com/' name='author' />
</head>
| <!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php wp_title('|', true, 'right'); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
<link href='//ajax.googleapis.com' rel='dns-prefetch' />
<% if (includeHumans) { %>
<link href='<?php echo get_stylesheet_directory_uri(); ?>/humans.txt' rel='author' type='text/plain' />
<% } %>
<% if (includeLogo) { %>
<link href='<?php echo get_stylesheet_directory_uri(); ?>/assets/img/logo.svg' rel='logo' type='image/svg' />
<% } %>
<link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/">
<meta content='false' http-equiv='imagetoolbar' />
<meta content='éGz - http://egztudio.com/' name='author' />
</head>
|
Clean Up the Contributing Documentation and Process: Part VII.XXXIII
* Fix the css/custom.css issues. | module.exports = function(grunt) {
require("time-grunt")(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
eslint: {
options: {
configFile: ".eslintrc.json"
},
target: ["js/*.js", "modules/default/*.js", "serveronly/*.js", "*.js"]
},
stylelint: {
simple: {
options: {
configFile: ".stylelintrc"
},
src: ["css/main.css", "modules/default/calendar/calendar.css", "modules/default/clock/clock_styles.css", "modules/default/currentweather/currentweather.css", "modules/default/weatherforcast/weatherforcast.css"]
}
}
});
grunt.loadNpmTasks("grunt-eslint");
grunt.loadNpmTasks("grunt-stylelint");
grunt.registerTask("default", ["eslint", "stylelint"]);
};
| module.exports = function(grunt) {
require("time-grunt")(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
eslint: {
options: {
configFile: ".eslintrc.json"
},
target: ["js/*.js", "modules/default/*.js", "serveronly/*.js", "*.js"]
},
stylelint: {
simple: {
options: {
configFile: ".stylelintrc"
},
src: ["css/custom.css", "css/main.css", "modules/default/calendar/calendar.css", "modules/default/clock/clock_styles.css", "modules/default/currentweather/currentweather.css", "modules/default/weatherforcast/weatherforcast.css"]
}
}
});
grunt.loadNpmTasks("grunt-eslint");
grunt.loadNpmTasks("grunt-stylelint");
grunt.registerTask("default", ["eslint", "stylelint"]);
};
|
Remove outdated (React) prop shape property; we no longer aggregate idea w/ user | //
// Reusable, domain-specific prop types
//
import PropTypes from "prop-types"
import STAGES from "../js/configs/stages"
import { CATEGORIES as startingCategories } from "../js/configs/retro_configs"
const { LOBBY, PRIME_DIRECTIVE, IDEA_GENERATION, VOTING, ACTION_ITEMS, CLOSED } = STAGES
export const alert = PropTypes.object
export const category = PropTypes.oneOf([
...startingCategories,
"action-item",
])
export const presence = PropTypes.shape({
given_name: PropTypes.string,
online_at: PropTypes.number,
is_facilitator: PropTypes.boolean,
})
export const presences = PropTypes.arrayOf(presence)
export const retroChannel = PropTypes.shape({
on: PropTypes.func,
push: PropTypes.func,
})
export const idea = PropTypes.shape({
id: PropTypes.number,
body: PropTypes.string,
category,
})
export const stage = PropTypes.oneOf([
LOBBY,
PRIME_DIRECTIVE,
IDEA_GENERATION,
VOTING,
ACTION_ITEMS,
CLOSED,
])
export const categories = PropTypes.arrayOf(PropTypes.string)
export const votes = PropTypes.arrayOf(PropTypes.object)
export const ideas = PropTypes.arrayOf(idea)
| //
// Reusable, domain-specific prop types
//
import PropTypes from "prop-types"
import STAGES from "../js/configs/stages"
import { CATEGORIES as startingCategories } from "../js/configs/retro_configs"
const { LOBBY, PRIME_DIRECTIVE, IDEA_GENERATION, VOTING, ACTION_ITEMS, CLOSED } = STAGES
export const alert = PropTypes.object
export const category = PropTypes.oneOf([
...startingCategories,
"action-item",
])
export const presence = PropTypes.shape({
given_name: PropTypes.string,
online_at: PropTypes.number,
is_facilitator: PropTypes.boolean,
})
export const presences = PropTypes.arrayOf(presence)
export const retroChannel = PropTypes.shape({
on: PropTypes.func,
push: PropTypes.func,
})
export const idea = PropTypes.shape({
id: PropTypes.number,
user: PropTypes.object,
body: PropTypes.string,
category,
})
export const stage = PropTypes.oneOf([
LOBBY,
PRIME_DIRECTIVE,
IDEA_GENERATION,
VOTING,
ACTION_ITEMS,
CLOSED,
])
export const categories = PropTypes.arrayOf(PropTypes.string)
export const votes = PropTypes.arrayOf(PropTypes.object)
export const ideas = PropTypes.arrayOf(idea)
|
Delete the exercise bases, not the translations | # Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_exercises(apps, schema_editor):
"""
Delete all pending exercises
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Exercise = apps.get_model("exercises", "ExerciseBase")
Exercise.objects.filter(status='1').delete()
class Migration(migrations.Migration):
dependencies = [
('core', '0014_merge_20210818_1735'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('exercises', '0017_muscle_name_en'),
]
operations = [
migrations.RunPython(delete_pending_exercises)
]
| # Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_exercises(apps, schema_editor):
"""
Delete all pending exercises
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Exercise = apps.get_model("exercises", "Exercise")
Exercise.objects.filter(status='1').delete()
class Migration(migrations.Migration):
dependencies = [
('core', '0014_merge_20210818_1735'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('exercises', '0017_muscle_name_en'),
]
operations = [
migrations.RunPython(delete_pending_exercises)
]
|
Fix repository import test for Python < 3.6
Check for broader range of exceptions. | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017, Fabian Greif
# All Rights Reserved.
#
# The file is part of the lbuild project and is released under the
# 2-clause BSD license. See the file `LICENSE.txt` for the full license
# governing this code.
import os
import sys
import unittest
# Hack to support the usage of `coverage`
sys.path.append(os.path.abspath("."))
import lbuild
class RepositoryTest(unittest.TestCase):
def _get_path(self, filename):
return os.path.join(os.path.dirname(os.path.realpath(__file__)),
"resources", "repository", filename)
def setUp(self):
self.parser = lbuild.parser.Parser()
def test_should_generate_exception_on_import_error(self):
with self.assertRaises(lbuild.exception.BlobForwardException) as cm:
self.parser.parse_repository(self._get_path("invalid_import.lb"))
self.assertTrue(issubclass(cm.exception.exception.__class__, ImportError))
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017, Fabian Greif
# All Rights Reserved.
#
# The file is part of the lbuild project and is released under the
# 2-clause BSD license. See the file `LICENSE.txt` for the full license
# governing this code.
import os
import io
import sys
import unittest
# Hack to support the usage of `coverage`
sys.path.append(os.path.abspath("."))
import lbuild
class RepositoryTest(unittest.TestCase):
def _get_path(self, filename):
return os.path.join(os.path.dirname(os.path.realpath(__file__)),
"resources", "repository", filename)
def setUp(self):
self.parser = lbuild.parser.Parser()
def test_should_generate_exception_on_import_error(self):
with self.assertRaises(lbuild.exception.BlobForwardException) as cm:
self.parser.parse_repository(self._get_path("invalid_import.lb"))
self.assertEqual(ModuleNotFoundError, cm.exception.exception.__class__)
if __name__ == '__main__':
unittest.main()
|
Add new version to PyPi | """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.4",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.3",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
|
Load stream + net modules before loading app code
See #628 and #634 |
global.process.removeAllListeners();
global.process.on( "uncaughtException", function( err ) {
// do nothing if window was fully initialized
if ( window && window.initialized ) { return; }
// show the app window and dev tools while being in debug mode
if ( DEBUG ) {
try {
let nwWindow = require( "nw.gui" ).Window.get();
nwWindow.show();
nwWindow.showDevTools();
return;
} catch ( e ) {}
}
// write to stderr and kill the process with error code 1
global.process.stderr.write([
"Could not initialize application window",
require( "util" ).inspect( err ),
""
].join( "\n" ) );
global.process.exit( 1 );
});
// "pre-load" certain native node modules
// prevents a bug on Windows which causes all methods of stream.Writable.prototype to be missing
// on stream.Duplex.prototype, more specifically stream.Duplex.prototype.cork. Also related to
// all classes which extend stream.Duplex, like net.Socket.
// See https://github.com/streamlink/streamlink-twitch-gui/issues/628#issuecomment-481510654
require( "stream" );
require( "net" );
require( "shim" );
require( "jquery" );
require( "ember" );
require( "./logger" );
require( "./app" );
|
global.process.removeAllListeners();
global.process.on( "uncaughtException", function( err ) {
// do nothing if window was fully initialized
if ( window && window.initialized ) { return; }
// show the app window and dev tools while being in debug mode
if ( DEBUG ) {
try {
let nwWindow = require( "nw.gui" ).Window.get();
nwWindow.show();
nwWindow.showDevTools();
return;
} catch ( e ) {}
}
// write to stderr and kill the process with error code 1
global.process.stderr.write([
"Could not initialize application window",
require( "util" ).inspect( err ),
""
].join( "\n" ) );
global.process.exit( 1 );
});
require( "shim" );
require( "jquery" );
require( "ember" );
require( "./logger" );
require( "./app" );
|
Add test for opal test py -t | """
Unittests fror opal.core.test_runner
"""
import ffs
from mock import MagicMock, patch
from opal.core.test import OpalTestCase
from opal.core import test_runner
class RunPyTestsTestCase(OpalTestCase):
@patch('subprocess.check_call')
def test_run_tests(self, check_call):
mock_args = MagicMock(name="args")
mock_args.userland_here = ffs.Path('.')
mock_args.coverage = False
mock_args.test = None
test_runner._run_py_tests(mock_args)
check_call.assert_called_once_with(['python', 'runtests.py'])
@patch('subprocess.check_call')
def test_run_tests_with_test_arg(self, check_call):
mock_args = MagicMock(name="args")
mock_args.userland_here = ffs.Path('.')
mock_args.coverage = False
mock_args.test = 'opal.tests.foo'
test_runner._run_py_tests(mock_args)
check_call.assert_called_once_with(['python', 'runtests.py', 'opal.tests.foo'])
class RunJSTestsTestCase(OpalTestCase):
pass
class RunTestsTestCase(OpalTestCase):
pass
| """
Unittests fror opal.core.test_runner
"""
import ffs
from mock import MagicMock, patch
from opal.core.test import OpalTestCase
from opal.core import test_runner
class RunPyTestsTestCase(OpalTestCase):
@patch('subprocess.check_call')
def test_run_tests(self, check_call):
mock_args = MagicMock(name="args")
mock_args.userland_here = ffs.Path('.')
mock_args.coverage = False
mock_args.test = None
test_runner._run_py_tests(mock_args)
check_call.assert_called_once_with(['python', 'runtests.py'])
class RunJSTestsTestCase(OpalTestCase):
pass
class RunTestsTestCase(OpalTestCase):
pass
|
Fix password character escaping issue | package com.migibert.kheo.core;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.migibert.kheo.client.SshClient;
public abstract class AbstractSshCommand<T> implements SshCommand<T> {
private Logger logger;
private String command;
protected AbstractSshCommand(String command) {
this.command = command;
this.logger = LoggerFactory.getLogger(this.getClass());
}
public T executeAndParse(Server target) throws IOException {
logger.info("Executing {} on {}", command, target.host);
String result = execute(target, command);
logger.info("Result is {}", result);
return parse(result);
}
@Override
public String execute(Server target, String command) throws IOException {
if (target.sudo) {
logger.info("Executing remote command with sudo flag");
command = "echo '" + target.password + "' | sudo -kS " + command;
}
return SshClient.execute(target, command);
}
}
| package com.migibert.kheo.core;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.migibert.kheo.client.SshClient;
public abstract class AbstractSshCommand<T> implements SshCommand<T> {
private Logger logger;
private String command;
protected AbstractSshCommand(String command) {
this.command = command;
this.logger = LoggerFactory.getLogger(this.getClass());
}
public T executeAndParse(Server target) throws IOException {
logger.info("Executing {} on {}", command, target.host);
String result = execute(target, command);
logger.info("Result is {}", result);
return parse(result);
}
@Override
public String execute(Server target, String command) throws IOException {
if (target.sudo) {
logger.info("Executing remote command with sudo flag");
command = "echo " + target.password + " | sudo -kS " + command;
}
return SshClient.execute(target, command);
}
}
|
Use <br> for soft breaks. | <?php
/*
* This file is part of Laravel Markdown.
*
* (c) Graham Campbell <graham@mineuk.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| Enable View Integration
|--------------------------------------------------------------------------
|
| This option specifies if the view integration is enabled so you can write
| markdown views and have them rendered as html. The following extensions
| are currently supported: ".md", ".md.php", and ".md.blade.php". You may
| disable this integration if it is conflicting with another package.
|
| Default: true
|
*/
'views' => true,
'allow_unsafe_links' => false,
'max_nesting_level' => 20,
'renderer' => [
'soft_break' => '<br />',
],
'extensions' => [
Webuni\CommonMark\TableExtension\TableExtension::class,
],
];
| <?php
/*
* This file is part of Laravel Markdown.
*
* (c) Graham Campbell <graham@mineuk.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| Enable View Integration
|--------------------------------------------------------------------------
|
| This option specifies if the view integration is enabled so you can write
| markdown views and have them rendered as html. The following extensions
| are currently supported: ".md", ".md.php", and ".md.blade.php". You may
| disable this integration if it is conflicting with another package.
|
| Default: true
|
*/
'views' => true,
'allow_unsafe_links' => false,
'max_nesting_level' => 20,
'extensions' => [
Webuni\CommonMark\TableExtension\TableExtension::class,
],
];
|
Remove unused imports in GUI class | package interactivelearner.gui;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class NaiveBayesGUI extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/gui/TrainGUI.fxml"));
Parent train = loader.load();
TrainController controller = loader.getController();
controller.getStage(primaryStage);
primaryStage.setTitle("Naive bayesian classifier");
Scene trainScene = new Scene(train, 600, 400);
primaryStage.setScene(trainScene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| package interactivelearner.gui;
import interactivelearner.classifier.NaiveBayesianClassifier;
import interactivelearner.data.Corpus;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import java.io.File;
public class NaiveBayesGUI extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/gui/TrainGUI.fxml"));
Parent train = loader.load();
TrainController controller = loader.getController();
controller.getStage(primaryStage);
primaryStage.setTitle("Naive bayesian classifier");
Scene trainScene = new Scene(train, 600, 400);
primaryStage.setScene(trainScene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
Add a slight delay to bring up drag handle | "use strict";
angular.module('arethusa.core').directive('arethusaGridHandle', [
'$timeout',
function($timeout) {
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs, ctrl, transclude) {
var enter;
function mouseEnter() {
enter = $timeout(function() { scope.visible = true; }, 100);
}
function mouseLeave() {
$timeout.cancel(enter);
}
function dragLeave() {
scope.$apply(function() { scope.visible = false; });
}
var trigger = element.find('.drag-handle-trigger');
var handle = element.find('.drag-handle');
trigger.bind('mouseenter', mouseEnter);
trigger.bind('mouseleave', mouseLeave);
handle.bind('mouseleave', dragLeave);
},
templateUrl: 'templates/arethusa.core/arethusa_grid_handle.html'
};
}
]);
| "use strict";
angular.module('arethusa.core').directive('arethusaGridHandle', [
function() {
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs, ctrl, transclude) {
function mouseEnter() {
scope.$apply(function() { scope.visible = true; });
}
function mouseLeave(event) {
scope.$apply(function() { scope.visible = false; });
}
var trigger = element.find('.drag-handle-trigger');
var handle = element.find('.drag-handle');
trigger.bind('mouseenter', mouseEnter);
handle.bind('mouseleave', mouseLeave);
},
templateUrl: 'templates/arethusa.core/arethusa_grid_handle.html'
};
}
]);
|
Convert numerical values to number type
For example,
`index.js --a=1 b=2.12`
should give
```js
{
"a": 1,
"b": 2.12
}
```
instead of string types:
```js
{
"a": "1",
"b": "2.12"
}
```
Thanks! | "use strict";
/*
Straight-forward node.js arguments parser
Author: eveningkid
License: Apache-2.0
*/
function Parse (argv) {
// Removing node/bin and called script name
argv = argv.slice(2);
// Returned object
var args = {};
var argName, argValue;
// For each argument
argv.forEach(function (arg, index) {
// Seperate argument, for a key/value return
arg = arg.split('=');
// Retrieve the argument name
argName = arg[0];
// Remove "--" or "-"
if (argName.indexOf('-') === 0) {
argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1);
}
// Associate defined value or initialize it to "true" state
argValue = (arg.length === 2)
? parseFloat(arg[1]).toString() === arg[1] // check if argument is valid number
? +arg[1]
: arg[1]
: true;
// Finally add the argument to the args set
args[argName] = argValue;
});
return args;
}
module.exports = Parse;
| "use strict";
/*
Straight-forward node.js arguments parser
Author: eveningkid
License: Apache-2.0
*/
function Parse (argv) {
// Removing node/bin and called script name
argv = argv.slice(2);
// Returned object
var args = {};
var argName, argValue;
// For each argument
argv.forEach(function (arg, index) {
// Seperate argument, for a key/value return
arg = arg.split('=');
// Retrieve the argument name
argName = arg[0];
// Remove "--" or "-"
if (argName.indexOf('-') === 0) {
argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1);
}
// Associate defined value or initialize it to "true" state
argValue = (arg.length === 2) ? arg[1] : true;
// Finally add the argument to the args set
args[argName] = argValue;
});
return args;
}
module.exports = Parse; |
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values | class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_object)
@classmethod
def str_to_bool(xcls, str_object):
if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable":
return True
elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable":
return False
else:
raise TypeError
@classmethod
def bool_to_str(xcls, bool_object):
if bool_object:
return "yes"
else:
return "no"
| class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_object)
@classmethod
def str_to_bool(xcls, str_object):
if str_object == "yes" or str_object == "on" or str_object == "true":
return True
elif str_object == "no" or str_object == "off" or str_object == "false":
return False
else:
raise TypeError
@classmethod
def bool_to_str(xcls, bool_object):
if bool_object:
return "yes"
else:
return "no"
|
Use standard jdk functional interface in rest utility method performIfNotNull | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.rest.utils;
public class Utility {
/**
* Perform the given action if the object is not null
*
* @param obj The object to check for null
* @param action The action to perform if object is not null
*/
public static void performIfNotNull(Object obj, Runnable action) {
if(obj != null) {
action.run();
}
}
}
| /**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.rest.utils;
public class Utility {
@FunctionalInterface
public interface Action {
void doIt();
}
/**
* Perform the given action if the object is not null
*
* @param obj The object to check for null
* @param action The action to perform if object is not null
*/
public static void performIfNotNull(Object obj, Action action) {
if(obj != null) {
action.doIt();
}
}
}
|
Remove hardcoded default filename. Raise an error if no app config file was specified, or it is unreadable, or it doesn't contain the section we need. | import ConfigParser
from common.application import Application
from keystonemiddleware.auth_token import filter_factory as auth_filter_factory
class KeystoneApplication(Application):
"""
An Application which uses Keystone for authorisation using RBAC
"""
INI_SECTION = 'keystone_authtoken'
def __init__(self, configuration):
super(KeystoneApplication, self).__init__(configuration)
self.required_role = self.config.get('authorisation', 'required_role')
if self.required_role is None:
raise ValueError("No required role supplied")
def _check_auth(self, req):
if 'HTTP_X_ROLES' in req.environ:
user_roles = req.environ['HTTP_X_ROLES'].split(',')
return self.required_role in user_roles
return False
def keystone_auth_filter_factory(global_config, **local_config):
global_config.update(local_config)
config_file_name = global_config.get('config_file')
if not config_file_name:
raise ValueError('No config_file directive')
config_file = ConfigParser.SafeConfigParser()
if not config_file.read(config_file_name):
raise ValueError("Cannot read config file '%s'" % config_file_name)
global_config.update(config_file.items(KeystoneApplication.INI_SECTION))
return auth_filter_factory(global_config)
| import ConfigParser
from common.application import Application
from keystonemiddleware.auth_token import filter_factory as auth_filter_factory
class KeystoneApplication(Application):
"""
An Application which uses Keystone for authorisation using RBAC
"""
def __init__(self, configuration):
super(KeystoneApplication, self).__init__(configuration)
self.required_role = self.config.get('authorisation', 'required_role')
if self.required_role is None:
raise ValueError("No required role supplied")
def _check_auth(self, req):
if 'HTTP_X_ROLES' in req.environ:
user_roles = req.environ['HTTP_X_ROLES'].split(',')
return self.required_role in user_roles
return False
def keystone_auth_filter_factory(global_config, **local_config):
global_config.update(local_config)
config_file_name = global_config.get('config_file', 'apiv1app.ini')
config_file = ConfigParser.SafeConfigParser()
config_file.read(config_file_name)
global_config.update(config_file.items('keystone_authtoken'))
return auth_filter_factory(global_config)
|
Fix broken tag-tree links in changelog | # Obtain shared config values
import sys
import os
from os.path import abspath, join, dirname
sys.path.append(abspath(join(dirname(__file__), '..')))
from shared_conf import *
# Local blog extension
sys.path.append(abspath('.'))
extensions.append('blog')
rss_link = 'http://paramiko.org'
rss_description = 'Paramiko project news'
# Releases changelog extension
extensions.append('releases')
# Paramiko 1.x tags start with 'v'. Meh.
releases_release_uri = "https://github.com/paramiko/paramiko/tree/v%s"
releases_issue_uri = "https://github.com/paramiko/paramiko/issues/%s"
# Intersphinx for referencing API/usage docs
extensions.append('sphinx.ext.intersphinx')
# Default is 'local' building, but reference the public docs site when building
# under RTD.
target = join(dirname(__file__), '..', 'docs', '_build')
if os.environ.get('READTHEDOCS') == 'True':
# TODO: switch to docs.paramiko.org post go-live of sphinx API docs
target = 'http://docs.paramiko.org/en/latest/'
intersphinx_mapping = {
'docs': (target, None),
}
# Sister-site links to API docs
html_theme_options['extra_nav_links'] = {
"API Docs": 'http://docs.paramiko.org',
}
| # Obtain shared config values
import sys
import os
from os.path import abspath, join, dirname
sys.path.append(abspath(join(dirname(__file__), '..')))
from shared_conf import *
# Local blog extension
sys.path.append(abspath('.'))
extensions.append('blog')
rss_link = 'http://paramiko.org'
rss_description = 'Paramiko project news'
# Releases changelog extension
extensions.append('releases')
releases_release_uri = "https://github.com/paramiko/paramiko/tree/%s"
releases_issue_uri = "https://github.com/paramiko/paramiko/issues/%s"
# Intersphinx for referencing API/usage docs
extensions.append('sphinx.ext.intersphinx')
# Default is 'local' building, but reference the public docs site when building
# under RTD.
target = join(dirname(__file__), '..', 'docs', '_build')
if os.environ.get('READTHEDOCS') == 'True':
# TODO: switch to docs.paramiko.org post go-live of sphinx API docs
target = 'http://docs.paramiko.org/en/latest/'
intersphinx_mapping = {
'docs': (target, None),
}
# Sister-site links to API docs
html_theme_options['extra_nav_links'] = {
"API Docs": 'http://docs.paramiko.org',
}
|
Add exception handling to batch copy | import ee
import os
import csv
import logging
def copy(source, destination):
with open(source, 'r') as f:
reader = csv.reader(f)
for line in reader:
name = line[0]
gme_id = line[1]
gme_path = 'GME/images/' + gme_id
ee_path = os.path.join(destination, name)
logging.info('Copying asset %s to %s', gme_path, ee_path)
try:
ee.data.copyAsset(gme_path, ee_path)
except ee.EEException as e:
with open('failed_batch_copy.csv', 'w') as fout:
fout.write('%s,%s,%s,%s', name, gme_id, ee_path,e)
if __name__ == '__main__':
ee.Initialize()
assets = '/home/tracek/Data/consbio2016/test.csv'
with open(assets, 'r') as f:
reader = csv.reader(f) | import ee
import os
import csv
import logging
def copy(source, destination):
with open(source, 'r') as f:
reader = csv.reader(f)
for line in reader:
name = line[0]
gme_id = line[1]
gme_path = 'GME/images/' + gme_id
ee_path = os.path.join(destination, name)
logging.info('Copying asset %s to %s', gme_path, ee_path)
ee.data.copyAsset(gme_path, ee_path)
if __name__ == '__main__':
ee.Initialize()
assets = '/home/tracek/Data/consbio2016/test.csv'
with open(assets, 'r') as f:
reader = csv.reader(f) |
Disable no-unresolved for locale-data line | import {addLocaleData} from 'react-intl';
import {updateIntl as superUpdateIntl} from 'react-intl-redux';
import languages from '../languages.json';
import messages from '../../locale/messages.json';
import {IntlProvider, intlReducer} from 'react-intl-redux';
Object.keys(languages).forEach(locale => {
// TODO: will need to handle locales not in the default intl - see www/custom-locales
// eslint-disable-line import/no-unresolved
import(`react-intl/locale-data/${locale}`).then(data => addLocaleData(data));
});
const intlInitialState = {
intl: {
defaultLocale: 'en',
locale: 'en',
messages: messages.en
}
};
const updateIntl = locale => superUpdateIntl({
locale: locale,
messages: messages[locale] || messages.en
});
export {
intlReducer as default,
IntlProvider,
intlInitialState,
updateIntl
};
| import {addLocaleData} from 'react-intl';
import {updateIntl as superUpdateIntl} from 'react-intl-redux';
import languages from '../languages.json';
import messages from '../../locale/messages.json';
import {IntlProvider, intlReducer} from 'react-intl-redux';
Object.keys(languages).forEach(locale => {
// TODO: will need to handle locales not in the default intl - see www/custom-locales
import(`react-intl/locale-data/${locale}`).then(data => addLocaleData(data));
});
const intlInitialState = {
intl: {
defaultLocale: 'en',
locale: 'en',
messages: messages.en
}
};
const updateIntl = locale => superUpdateIntl({
locale: locale,
messages: messages[locale] || messages.en
});
export {
intlReducer as default,
IntlProvider,
intlInitialState,
updateIntl
};
|
Set the process title to "obvious" | process.title = 'obvious';
const PERIOD = 500;
var term = require('term');
var repeatString = function (string, count) {
return new Array(count + 1).join(string);
};
var drawScreen = function (w, h, bg) {
var output =
term.color.bg(
repeatString(' ', w * (h - 1)),
bg
) +
term.cursor.home();
return output;
};
var currentState = false;
var loop = function () {
var alt = Date.now() % PERIOD < (PERIOD / 2);
if (alt !== currentState) {
var w = process.stdout.columns;
var h = process.stdout.rows;
var bg = alt ? term.color.WHITE : term.color.BLACK;
var output = drawScreen(w, h, bg);
currentState = alt;
process.stdout.write(output);
}
};
var init = function () {
var output = term.cursor.hide();
process.stdout.write(output);
};
var finish = function () {
var output = term.clear.all() + term.cursor.home();
process.stdout.write(output);
};
init();
(function inner () {
loop();
setImmediate(inner);
})();
process.on('SIGINT', function () {
finish();
process.exit();
}); | process.title = 'ATTENTION';
const PERIOD = 500;
var term = require('term');
var repeatString = function (string, count) {
return new Array(count + 1).join(string);
};
var drawScreen = function (w, h, bg) {
var output =
term.color.bg(
repeatString(' ', w * (h - 1)),
bg
) +
term.cursor.home();
return output;
};
var currentState = false;
var loop = function () {
var alt = Date.now() % PERIOD < (PERIOD / 2);
if (alt !== currentState) {
var w = process.stdout.columns;
var h = process.stdout.rows;
var bg = alt ? term.color.WHITE : term.color.BLACK;
var output = drawScreen(w, h, bg);
currentState = alt;
process.stdout.write(output);
}
};
var init = function () {
var output = term.cursor.hide();
process.stdout.write(output);
};
var finish = function () {
var output = term.clear.all() + term.cursor.home();
process.stdout.write(output);
};
init();
(function inner () {
loop();
setImmediate(inner);
})();
process.on('SIGINT', function () {
finish();
process.exit();
}); |
Fix URL for logging achievement to match RequestMapping | angular.module('worldOfWorkCraftApp')
.controller('LogAchievementCtrl', function($scope, $routeParams, $location, $http, UserData) {
$scope.challengeName = $routeParams.challengeName;
// TODO replace with real service endpoint
$http.get('http://localhost:8080/worldofworkcraft/learner/'+UserData.username+'/achievements')
.success(function(data) {
$scope.achievements = data;
})
.error(function(data, status) {
console.error('Failed to fetch achievement data');
});
// TODO replace with real service endpoint
$http.get('../achievement-options.json')
.success(function(data) {
$scope.achievementOptions = data;
})
.error(function(data, status) {
console.error('Failed to fetch achievement data');
});
$scope.logAchievement = function(achievement, pointValue) {
// TODO replace with real POST
console.log('Would have posted to achievements with achievement ' + achievement + ' and pointValue ' + pointValue);
$http.post('http://localhost:8080/worldofworkcraft/logger/log', {uniqname:UserData.username, achievementName:achievement, verb:'LEARN'});
$scope.achievements.push({name: achievement, points: pointValue});
};
$scope.goBack = function() {
$location.path('/leaderboard/' + $scope.challengeName);
}
});
| angular.module('worldOfWorkCraftApp')
.controller('LogAchievementCtrl', function($scope, $routeParams, $location, $http, UserData) {
$scope.challengeName = $routeParams.challengeName;
// TODO replace with real service endpoint
$http.get('http://localhost:8080/worldofworkcraft/learner/'+UserData.username+'/achievements')
.success(function(data) {
$scope.achievements = data;
})
.error(function(data, status) {
console.error('Failed to fetch achievement data');
});
// TODO replace with real service endpoint
$http.get('../achievement-options.json')
.success(function(data) {
$scope.achievementOptions = data;
})
.error(function(data, status) {
console.error('Failed to fetch achievement data');
});
$scope.logAchievement = function(achievement, pointValue) {
// TODO replace with real POST
console.log('Would have posted to achievements');
$http.post('http://localhost:8080/worldofworkcraft/logger', {uniqname:UserData.username, achievementName:achievement, verb:'LEARN'});
$scope.achievements.push({name: achievementName, points: pointValue});
};
$scope.goBack = function() {
$location.path('/leaderboard/' + $scope.challengeName);
}
});
|
Refactor test case for compound terms | import pytest
from katana.storage import Node, Pair, prepare
from katana.compound import sequence, group, repeat, option, maybe
from katana.term import term
Ta = term('a')
Tb = term('b')
Tc = term('c')
Na = Node('a', 'data')
Nb = Node('b', 'data')
Nc = Node('c', 'data')
def test_sequence():
s = sequence(Ta, Tb)
given = prepare([Na, Nb])
after = Pair([Na, Nb], [])
assert s(given) == after
def test_group():
g = group(Ta)
given = prepare([Na])
after = Pair([Node(g, [Na])], [])
assert g(given) == after
def test_repeat():
r = repeat(Ta)
given = prepare([Na]*10)
after = Pair([Na]*10, [])
assert r(given) == after
def test_option():
opt = option(Ta, Tb, Tc)
for node in [Na, Nb]:
assert opt(prepare([node])) == Pair([node], [])
def test_option_empty():
with pytest.raises(ValueError):
assert option(Ta, Tb)(prepare([Nc]))
def test_maybe():
m = maybe(Ta)
assert m(prepare([Nb])) == Pair([], [Nb])
assert m(prepare([Na])) == Pair([Na], [])
| import pytest
from katana.storage import Node, Pair, prepare
from katana.compound import sequence, group, repeat, option, maybe
from katana.term import term
A = term('a')
B = term('b')
C = term('c')
node = lambda x: Node(x, 'data')
def test_sequence():
na = node('a')
nb = node('b')
s = sequence(A, B)
given = prepare([na, nb])
after = Pair([na, nb], [])
assert s(given) == after
def test_group():
n = node('a')
g = group(A)
given = prepare([n])
after = Pair([Node(g, [n])], [])
assert g(given) == after
def test_repeat():
n = node('a')
r = repeat(A)
given = prepare([n]*10)
after = Pair([n]*10, [])
assert r(given) == after
def test_option():
a = node('a')
b = node('b')
c = node('c')
opt = option(A, B, C)
for item in [a, b]:
assert opt(prepare([item])) == Pair([item], [])
def test_option_empty():
c = node('c')
with pytest.raises(ValueError):
assert option(A, B)(prepare([c]))
def test_maybe():
m = maybe(A)
a = node('a')
b = node('b')
assert m(prepare([b])) == Pair([], [b])
assert m(prepare([a])) == Pair([a], [])
|
Fix promise test using a worker/semaphore hack
(looks like we need support for async tests) | var assert = require("assert");
var {defer, promises} = require("ringo/promise");
var {Worker} = require("ringo/worker");
var semaphore = new java.util.concurrent.Semaphore(0);
exports.testPromiseList = function() {
var d1 = defer(), d2 = defer(), d3 = defer(), done = defer();
var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
var result;
l.then(function(value) {
done.resolve(value);
}, function(error) {
done.resolve("promises called error callback", true);
});
done.promise.then(function(value) {
result = value;
semaphore.release();
});
// Resolve promise in worker so async promise callbacks get called
var worker = new Worker({
onmessage: function() {
d2.resolve(1);
d3.resolve("error", true);
d1.resolve("ok");
}
}).postMessage();
// wait for last promise to resolve
semaphore.acquire();
// make sure promises have resolved via chained callback
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
};
// start the test runner if we're called directly from command line
if (require.main == module.id) {
system.exit(require('test').run(exports));
}
| var assert = require("assert");
var {defer, promises} = require("ringo/promise");
exports.testPromiseList = function() {
var d1 = defer(), d2 = defer(), d3 = defer(), done = defer();
var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
l.then(function(result) {
done.resolve(result);
}, function(error) {
done.resolve("promises called error callback", true);
});
d2.resolve(1);
d3.resolve("error", true);
d1.resolve("ok");
// make sure promises resolve via wait()
var result = l.wait();
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
// make sure promises resolve via callback
result = done.promise.wait();
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
};
// start the test runner if we're called directly from command line
if (require.main == module.id) {
system.exit(require('test').run(exports));
}
|
Mark the getZonedDateTime method with @XmlTransient. The JAXB parsers are seeing the getX and setX methods and assume there's a state property of type ZonedDateTime. The old JAXB implementations (java 8) don't handle the java.time stuff at all. This fixes the JAXB problem for a client (AZ). | package com.smartlogic.ses.client;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.XmlTransient;
public abstract class AbstractSimpleNodeDate extends AbstractSimpleNode {
private static final long serialVersionUID = -7383419011106091654L;
public AbstractSimpleNodeDate() {}
public AbstractSimpleNodeDate(String value) {
super(value);
}
public AbstractSimpleNodeDate(Element element) {
super(element);
}
private final static DateTimeFormatter defaultDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
@XmlTransient
public ZonedDateTime getZonedDateTime() {
if ((getValue() == null) || (getValue().length() == 0)) return null;
return ZonedDateTime.parse(getValue(), defaultDateTimeFormatter);
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
setValue(defaultDateTimeFormatter.format(zonedDateTime));
}
public ZonedDateTime getZonedDateTime(DateTimeFormatter dateTimeFormatter) {
if ((getValue() == null) || (getValue().length() == 0)) return null;
return ZonedDateTime.parse(getValue(), dateTimeFormatter);
}
}
| package com.smartlogic.ses.client;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.w3c.dom.Element;
public abstract class AbstractSimpleNodeDate extends AbstractSimpleNode {
private static final long serialVersionUID = -7383419011106091654L;
public AbstractSimpleNodeDate() {}
public AbstractSimpleNodeDate(String value) {
super(value);
}
public AbstractSimpleNodeDate(Element element) {
super(element);
}
private final static DateTimeFormatter defaultDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
public ZonedDateTime getZonedDateTime() {
if ((getValue() == null) || (getValue().length() == 0)) return null;
return ZonedDateTime.parse(getValue(), defaultDateTimeFormatter);
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
setValue(defaultDateTimeFormatter.format(zonedDateTime));
}
public ZonedDateTime getZonedDateTime(DateTimeFormatter dateTimeFormatter) {
if ((getValue() == null) || (getValue().length() == 0)) return null;
return ZonedDateTime.parse(getValue(), dateTimeFormatter);
}
}
|
54: Use route names instead of paths. | Template.HostCreate.events({
'submit form' : function (event, template) {
event.preventDefault();
// Define form field variables.
var hostname = event.target.hostname.value,
type = event.target.type.value,
version = event.target.version.value;
// Need more validation here.
if (hostname.length) {
// Create sort field sequence value.
var total = Hosts.find().count();
if (total == 0) {
var seq = total;
} else {
var seq = total++;
}
// Insert data into document.
Hosts.insert({
hostname: hostname,
type: type,
version: version,
hostCreated: new Date,
sort: seq
});
// Reset form.
template.find('form').reset();
Router.go('home');
}
}
});
| Template.HostCreate.events({
'submit form' : function (event, template) {
event.preventDefault();
// Define form field variables.
var hostname = event.target.hostname.value,
type = event.target.type.value,
version = event.target.version.value;
// Need more validation here.
if (hostname.length) {
// Create sort field sequence value.
var total = Hosts.find().count();
if (total == 0) {
var seq = total;
} else {
var seq = total++;
}
// Insert data into document.
Hosts.insert({
hostname: hostname,
type: type,
version: version,
hostCreated: new Date,
sort: seq
});
// Reset form.
template.find('form').reset();
Router.go('/');
}
}
});
|
Use interface instead of class in generic | package ru.yandex.qatools.allure.storages;
import ru.yandex.qatools.allure.model.Step;
import java.util.Deque;
import java.util.LinkedList;
/**
* @author Dmitry Baev charlie@yandex-team.ru
* Date: 13.12.13
*/
public class StepStorage extends ThreadLocal<Deque<Step>> {
@Override
protected Deque<Step> initialValue() {
Deque<Step> queue = new LinkedList<>();
queue.add(new Step());
return queue;
}
public Step getLast() {
return get().getLast();
}
public void put(Step step) {
get().add(step);
}
public Step pollLast() {
return get().pollLast();
}
}
| package ru.yandex.qatools.allure.storages;
import ru.yandex.qatools.allure.model.Step;
import java.util.LinkedList;
/**
* @author Dmitry Baev charlie@yandex-team.ru
* Date: 13.12.13
*/
public class StepStorage extends ThreadLocal<LinkedList<Step>> {
@Override
protected LinkedList<Step> initialValue() {
LinkedList<Step> queue = new LinkedList<>();
queue.add(new Step());
return queue;
}
public Step getLast() {
return get().getLast();
}
public void put(Step step) {
get().add(step);
}
public Step pollLast() {
return get().pollLast();
}
}
|
Fix translations path for storybook | import { configure, addDecorator } from '@storybook/react';
import { setOptions } from '@storybook/addon-options';
import '../lib/global.css';
/**
* React intl support
*/
// Load the locale data for all your defined locales
import { setIntlConfig, withIntl } from 'storybook-addon-intl';
import enTranslations from '../translations/stripes-components/en.json';
import { addLocaleData } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
addLocaleData(enLocaleData);
// Define messages
const messages = {
en: enTranslations,
};
// Set intl configuration
setIntlConfig({
locales: ['en'],
defaultLocale: 'en',
getMessages: (locale) => messages[locale]
});
addDecorator(withIntl);
/**
* Set options
*/
setOptions({
name: 'FOLIO Stripes',
});
const req = require.context('../lib', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach((filename) => req(filename));
}
configure(loadStories, module);
| import { configure, addDecorator } from '@storybook/react';
import { setOptions } from '@storybook/addon-options';
import '../lib/global.css';
/**
* React intl support
*/
// Load the locale data for all your defined locales
import { setIntlConfig, withIntl } from 'storybook-addon-intl';
import enTranslations from '../translations/en.json';
import { addLocaleData } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
addLocaleData(enLocaleData);
// Define messages
const messages = {
en: enTranslations,
};
// Set intl configuration
setIntlConfig({
locales: ['en'],
defaultLocale: 'en',
getMessages: (locale) => messages[locale]
});
addDecorator(withIntl);
/**
* Set options
*/
setOptions({
name: 'FOLIO Stripes',
});
const req = require.context('../lib', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach((filename) => req(filename));
}
configure(loadStories, module);
|
Update "Programming Language" Tag to Indicate Python3 Support | from setuptools import setup, find_packages
import plaid
url = 'https://github.com/plaid/plaid-python'
setup(
name='plaid-python',
version=plaid.__version__,
description='Simple Python API client for Plaid',
long_description='',
keywords='api, client, plaid',
author='Chris Forrette',
author_email='chris@chrisforrette.com',
url=url,
download_url='{}/tarball/v{}'.format(url, plaid.__version__),
license='MIT',
packages=find_packages(exclude='tests'),
package_data={'README': ['README.md']},
install_requires=['requests==2.2.1'],
zip_safe=False,
include_package_data=True,
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries :: Python Modules",
"Environment :: Web Environment",
]
)
| from setuptools import setup, find_packages
import plaid
url = 'https://github.com/plaid/plaid-python'
setup(
name='plaid-python',
version=plaid.__version__,
description='Simple Python API client for Plaid',
long_description='',
keywords='api, client, plaid',
author='Chris Forrette',
author_email='chris@chrisforrette.com',
url=url,
download_url='{}/tarball/v{}'.format(url, plaid.__version__),
license='MIT',
packages=find_packages(exclude='tests'),
package_data={'README': ['README.md']},
install_requires=['requests==2.2.1'],
zip_safe=False,
include_package_data=True,
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Environment :: Web Environment",
]
)
|
Fix packager script breakage when running `npm start` | /**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
'use strict';
var spawn = require('child_process').spawn;
var path = require('path');
var install = require('./install.js');
function printUsage() {
console.log([
'Usage: react-native <command>',
'',
'Commands:',
' start: starts the webserver',
' install: installs npm react components'
].join('\n'));
process.exit(1);
}
function run() {
var args = process.argv.slice(2);
if (args.length === 0) {
printUsage();
}
switch (args[0]) {
case 'start':
spawn('sh', [
path.resolve(__dirname, '../packager', 'packager.sh'),
'--projectRoots',
process.cwd(),
], {stdio: 'inherit'});
break;
case 'install':
install.init();
break;
default:
console.error('Command `%s` unrecognized', args[0]);
printUsage();
}
// Here goes any cli commands we need to
}
function init(root, projectName) {
spawn(path.resolve(__dirname, '../init.sh'), [projectName], {stdio:'inherit'});
}
if (require.main === module) {
run();
}
module.exports = {
run: run,
init: init,
};
| /**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
'use strict';
var spawn = require('child_process').spawn;
var path = require('path');
var install = require('./install.js');
function printUsage() {
console.log([
'Usage: react-native <command>',
'',
'Commands:',
' start: starts the webserver',
' install: installs npm react components'
].join('\n'));
process.exit(1);
}
function run() {
var args = process.argv.slice(2);
if (args.length === 0) {
printUsage();
}
switch (args[0]) {
case 'start':
spawn('sh', [
path.resolve(__dirname, 'packager', 'packager.sh'),
'--projectRoots',
process.cwd(),
], {stdio: 'inherit'});
break;
case 'install':
install.init();
break;
default:
console.error('Command `%s` unrecognized', args[0]);
printUsage();
}
// Here goes any cli commands we need to
}
function init(root, projectName) {
spawn(path.resolve(__dirname, '../init.sh'), [projectName], {stdio:'inherit'});
}
if (require.main === module) {
run();
}
module.exports = {
run: run,
init: init,
};
|
Change EPA API Data Structure | 'use strict';
let Schema = require('mongoose').Schema;
let schema = new Schema(
{
tim: {type: Number},
data:{
"SiteName":{type: String},
"SiteKey":{type: String},
"AreaKey":{type: String},
"PSI":{type: String},
"PSIStyle":{type: String},
"MainPollutant":{type: String},
"MainPollutantKey":{type: String},
"PM10":{type: String},
"PM25":{type: String},
"O3":{type: String},
"SO2":{type: String},
"CO":{type: String},
"NO2":{type: String},
"X":{type: String},
"Y":{type: String},
"FPMI":{type: String},
"PM10_AVG":{type: String},
"PM25_AVG":{type: String}
}
}
);
module.exports = schema; | 'use strict';
let Schema = require('mongoose').Schema;
let schema = new Schema(
{
tim: {type: Number},
data:{
"CO": {type: String},
"County": {type: String},
"FPMI": {type: String},
"MajorPollutant": {type: String},
"NO": {type: String},
"NO2": {type: String},
"NOx": {type: String},
"O3": {type: String},
"PM10": {type: String},
"PM25": {type: String},
"PSI": {type: String},
"PublishTime": {type: String},
"SiteName": {type: String},
"SO2": {type: String},
"Status": {type: String},
"WindDirec": {type: String},
"WindSpeed": {type: String}
}
}
);
module.exports = schema; |
Allow serialization to an io.Writer
If w is also an http.ResponseWriter, write the headers too | package serialize
import (
"encoding/json"
"encoding/xml"
"io"
"net/http"
"strconv"
)
type SerializationFormat int
const (
Json SerializationFormat = iota
Xml
)
func Write(w io.Writer, value interface{}, f SerializationFormat) (int, error) {
var contentType string
var data []byte
var err error
switch f {
case Json:
data, err = json.Marshal(value)
contentType = "application/json"
case Xml:
data, err = xml.Marshal(value)
contentType = "application/xml"
default:
panic("Invalid serialization format")
}
if err != nil {
return 0, err
}
total := len(data)
if rw, ok := w.(http.ResponseWriter); ok {
header := rw.Header()
header.Set("Content-Type", contentType)
header.Set("Content-Length", strconv.Itoa(total))
}
for c := 0; c < total; {
n, err := w.Write(data)
c += n
if err != nil {
return c, err
}
}
return total, nil
}
func WriteJson(w io.Writer, value interface{}) (int, error) {
return Write(w, value, Json)
}
func WriteXml(w io.Writer, value interface{}) (int, error) {
return Write(w, value, Xml)
}
| package serialize
import (
"encoding/json"
"encoding/xml"
"net/http"
"strconv"
)
type Serializer int
const (
Json Serializer = iota
Xml
)
func Write(w http.ResponseWriter, value interface{}, s Serializer) (int, error) {
var contentType string
var data []byte
var err error
if s == Json {
data, err = json.Marshal(value)
contentType = "application/json"
} else if s == Xml {
data, err = xml.Marshal(value)
contentType = "application/xml"
}
if err != nil {
return 0, err
}
total := len(data)
header := w.Header()
header.Set("Content-Type", contentType)
header.Set("Content-Length", strconv.Itoa(total))
for c := 0; c < total; {
n, err := w.Write(data)
c += n
if err != nil {
return c, err
}
}
return total, nil
}
|
Fix payout currencies in Trading page | /*
* Handles currency display
*
* It process 'socket.send({payout_currencies:1})` response
* and display them
*/
function displayCurrencies(selected) {
'use strict';
var target = document.getElementById('currency'),
fragment = document.createDocumentFragment(),
currencies = JSON.parse(sessionStorage.getItem('currencies'))['payout_currencies'];
if (!target) {
return;
}
while (target && target.firstChild) {
target.removeChild(target.firstChild);
}
var client_currencies;
if(page.client.is_logged_in) {
client_currencies = Settings.get('client.currencies');
}
currencies.forEach(function (currency) {
if(client_currencies && client_currencies.length > 0 && client_currencies.indexOf(currency) < 0) {
return;
}
var option = document.createElement('option'),
content = document.createTextNode(currency);
option.setAttribute('value', currency);
if (selected && selected == key) {
option.setAttribute('selected', 'selected');
}
option.appendChild(content);
fragment.appendChild(option);
});
target.appendChild(fragment);
}
| /*
* Handles currency display
*
* It process 'socket.send({payout_currencies:1})` response
* and display them
*/
function displayCurrencies(selected) {
'use strict';
var target = document.getElementById('currency'),
fragment = document.createDocumentFragment(),
currencies = JSON.parse(sessionStorage.getItem('currencies'))['payout_currencies'];
if (!target) {
return;
}
while (target && target.firstChild) {
target.removeChild(target.firstChild);
}
currencies.forEach(function (currency) {
var option = document.createElement('option'),
content = document.createTextNode(currency);
option.setAttribute('value', currency);
if (selected && selected == key) {
option.setAttribute('selected', 'selected');
}
option.appendChild(content);
fragment.appendChild(option);
});
target.appendChild(fragment);
}
|
Make the skeleton survey script use the new melange.template namespace. | /* Copyright 2011 the Melange 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.
*/
/**
* @author <a href="mailto:fadinlight@gmail.com">Mario Ferraro</a>
*/
(function() {
var template_name = "survey";
melange.template[template_name] = function(_self, context) {
};
melange.template[template_name].prototype = new melange.templates._baseTemplate();
melange.template[template_name].prototype.constructor = melange.template[template_name];
melange.template[template_name].apply(
melange.template[template_name],
[melange.template[template_name], melange.template[template_name].prototype.context]
);
}());
| /* Copyright 2011 the Melange 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.
*/
/**
* @author <a href="mailto:fadinlight@gmail.com">Mario Ferraro</a>
*/
(function() {
var template_name = "survey_template";
melange[template_name] = function(_self, context) {
};
melange[template_name].prototype = new melange.templates._baseTemplate();
melange[template_name].prototype.constructor = melange[template_name];
melange[template_name].apply(
melange[template_name],
[melange[template_name],melange[template_name].prototype.context]
);
}());
|
Use host + port from config | var Express = require('express');
var webpack = require('webpack');
var config = require('../src/config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = config.host || 'localhost';
var port = (config.port + 1) || 3001;
var serverOptions = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: webpackConfig.output.publicPath,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true}
};
var app = new Express();
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err);
} else {
console.info('==> 🚧 Webpack development server listening on port %s', port);
}
});
| var Express = require('express');
var webpack = require('webpack');
var config = require('../src/config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = process.env.HOST || 'localhost';
var port = parseInt(config.port, 10) + 1 || 3001;
var serverOptions = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: webpackConfig.output.publicPath,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true}
};
var app = new Express();
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err);
} else {
console.info('==> 🚧 Webpack development server listening on port %s', port);
}
});
|
Update ApiClient host env var to CODECLIMATE_API_HOST
This commit also strips trailing slashes from the host. | import json
import os
import requests
class ApiClient:
def __init__(self, host=None, timeout=5):
self.host = host or self.__default_host().rstrip("/")
self.timeout = timeout
def post(self, payload):
print("Submitting payload to %s" % self.host)
headers = {"Content-Type": "application/json"}
response = requests.post(
"%s/test_reports" % self.host,
data=json.dumps(payload),
headers=headers,
timeout=self.timeout
)
return response
def __default_host(self):
return os.environ.get("CODECLIMATE_API_HOST", "https://codeclimate.com")
| import json
import os
import requests
class ApiClient:
def __init__(self, host=None, timeout=5):
self.host = host or self.__default_host()
self.timeout = timeout
def post(self, payload):
print("Submitting payload to %s" % self.host)
headers = {"Content-Type": "application/json"}
response = requests.post(
"%s/test_reports" % self.host,
data=json.dumps(payload),
headers=headers,
timeout=self.timeout
)
return response
def __default_host(self):
return os.environ.get("CODECLIMATE_HOST", "https://codeclimate.com")
|
Add favicon and static folder | module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `@gatsbyjs`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/beaker_favicon.png`, // This path is relative to the root of the site.
},
},
`gatsby-plugin-typescript`,
`gatsby-plugin-tslint`,
`gatsby-plugin-styled-components`,
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
| module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `@gatsbyjs`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
`gatsby-plugin-typescript`,
`gatsby-plugin-tslint`,
`gatsby-plugin-styled-components`,
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
Update scheduler tasks day of week
After testing it comes that day 0 = Sunday, 1 = Monday, ..., 6 = Saturday | <?php
namespace Myjob\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\Myjob\Console\Commands\Inspire::class,
\Myjob\Console\Commands\SendNotificationMails::class,
\Myjob\Console\Commands\SyncLDAPStudents::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule) {
// Synchronise student list with the LDAP
$schedule->command('syncstudents')
->weeklyOn(6, '4:00'); // 6 = Saturday
// Send notification mails
$schedule->command('sendnotificationmails --subscribed=instantly')
->everyThirtyMinutes();
$schedule->command('sendnotificationmails --subscribed=daily')
->dailyAt('4:00');
$schedule->command('sendnotificationmails --subscribed=weekly')
->weeklyOn(0, '4:00'); // 0 = Sunday
}
}
| <?php
namespace Myjob\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\Myjob\Console\Commands\Inspire::class,
\Myjob\Console\Commands\SendNotificationMails::class,
\Myjob\Console\Commands\SyncLDAPStudents::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule) {
// Synchronise student list with the LDAP
$schedule->command('syncstudents')
->weeklyOn(5, '4:00');
// Send notification mails
$schedule->command('sendnotificationmails --subscribed=instantly')
->everyThirtyMinutes();
$schedule->command('sendnotificationmails --subscribed=daily')
->dailyAt('4:00');
$schedule->command('sendnotificationmails --subscribed=weekly')
->weeklyOn(6, '4:00');
}
}
|
Drop unused and dangerous entrypoint `open_fileindex` | #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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.
__version__ = "0.9.9.2.dev0"
# cfgrib core API depends on the ECMWF ecCodes C-library only
from .cfmessage import CfMessage
from .dataset import Dataset, DatasetBuildError, open_container, open_file, open_from_index
from .messages import FileStream, Message
# NOTE: xarray is not a hard dependency, but let's provide helpers if it is available.
try:
from .xarray_store import open_dataset, open_datasets
except ImportError:
pass
| #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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.
__version__ = "0.9.9.2.dev0"
# cfgrib core API depends on the ECMWF ecCodes C-library only
from .cfmessage import CfMessage
from .dataset import (
Dataset,
DatasetBuildError,
open_container,
open_file,
open_fileindex,
open_from_index,
)
from .messages import FileStream, Message
# NOTE: xarray is not a hard dependency, but let's provide helpers if it is available.
try:
from .xarray_store import open_dataset, open_datasets
except ImportError:
pass
|
Fix themes getting nuked by purgecss | const IN_PRODUCTION = process.env.NODE_ENV === 'production'
class TailwindVueExtractor {
static extract(content) {
const contentWithoutStyleBlocks = content.replace(/<style[^]+?<\/style>/gi, '')
return contentWithoutStyleBlocks.match(/[A-Za-z0-9-_:/]+/g) || []
}
}
const extensionsUsingCSS = ['vue', 'html']
const extensionsOfCSS = ['css', 'less', 'pcss', 'postcss', 'sass', 'scss', 'styl']
module.exports = {
plugins: [
require('postcss-preset-env')({stage: 1}),
require('tailwindcss')('./tailwind.config.js'),
IN_PRODUCTION && require('@fullhuman/postcss-purgecss')({
content: [`./@(public|src)/**/*.@(${extensionsUsingCSS.join('|')})`],
css: [`./src/**/*.@(${extensionsOfCSS.join('|')})`],
extractors: [
{
extractor: TailwindVueExtractor,
extensions: extensionsUsingCSS
}
],
whitelist: [],
whitelistPatterns: [
/-(leave|enter|appear)(|-(to|from|active))$/,
/^(?!(|.*?:)cursor-move).+-move$/,
/^router-link(|-exact)-active$/,
/^theme-.+$/
]
}),
require('autoprefixer')(),
require('postcss-flexbugs-fixes')
]
}
| const IN_PRODUCTION = process.env.NODE_ENV === 'production'
class TailwindVueExtractor {
static extract(content) {
const contentWithoutStyleBlocks = content.replace(/<style[^]+?<\/style>/gi, '')
return contentWithoutStyleBlocks.match(/[A-Za-z0-9-_:/]+/g) || []
}
}
const extensionsUsingCSS = ['vue', 'html']
const extensionsOfCSS = ['css', 'less', 'pcss', 'postcss', 'sass', 'scss', 'styl']
module.exports = {
plugins: [
require('postcss-preset-env')({stage: 1}),
require('tailwindcss')('./tailwind.config.js'),
IN_PRODUCTION && require('@fullhuman/postcss-purgecss')({
content: [`./@(public|src)/**/*.@(${extensionsUsingCSS.join('|')})`],
css: [`./src/**/*.@(${extensionsOfCSS.join('|')})`],
extractors: [
{
extractor: TailwindVueExtractor,
extensions: extensionsUsingCSS
}
],
whitelist: [],
whitelistPatterns: [/-(leave|enter|appear)(|-(to|from|active))$/, /^(?!(|.*?:)cursor-move).+-move$/, /^router-link(|-exact)-active$/]
}),
require('autoprefixer')(),
require('postcss-flexbugs-fixes')
]
}
|
Update test server name for local development | <?php
// Any of these settings can be overridden by creating a "config.user.php" file in
// this directory which returns a subset of or replacement for the following array.
return [
'testWith' => [
'mysql' => true,
'sqlsrv' => false, // don't test by default since it isn't configured on CI
],
'db' => [
'mysql' => [
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'database' => 'PeachySQL',
],
'sqlsrv' => [
'serverName' => '(local)\SQLEXPRESS',
'connectionInfo' => [
'Database' => 'PeachySQL',
'ReturnDatesAsStrings' => true,
],
],
],
];
| <?php
// Any of these settings can be overridden by creating a "config.user.php" file in
// this directory which returns a subset of or replacement for the following array.
return [
'testWith' => [
'mysql' => true,
'sqlsrv' => false, // don't test by default since it isn't configured on CI
],
'db' => [
'mysql' => [
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'database' => 'PeachySQL',
],
'sqlsrv' => [
'serverName' => 'Computer-Name\SQLEXPRESS',
'connectionInfo' => [
'Database' => 'PeachySQL',
'ReturnDatesAsStrings' => true,
],
],
],
];
|
Make package private methods public | package de.flux.playground.deckcompare;
import java.io.File;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@SpringBootApplication
public class Deckcompare {
public static String ROOT = "upload-dir";
@RequestMapping("/")
@ResponseBody
public String home() {
return "Hello World!";
}
@Bean
public CommandLineRunner init() {
return (String[] args) -> {
new File(ROOT).mkdir();
};
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Deckcompare.class, args);
}
}
| package de.flux.playground.deckcompare;
import java.io.File;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@SpringBootApplication
public class Deckcompare {
public static String ROOT = "upload-dir";
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
@Bean
CommandLineRunner init() {
return (String[] args) -> {
new File(ROOT).mkdir();
};
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Deckcompare.class, args);
}
}
|
Update the kmip package to allow importing enums globally
This change updates the root-level kmip package, allowing users
to now import enums directly from the kmip package:
from kmip import enums
Enumerations are used throughout the codebase and user applications
and this will simplify usage and help obfuscate internal package
details that may change in the future. | # Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import re
from kmip.core import enums
# Dynamically set __version__
version_path = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'version.py')
with open(version_path, 'r') as version_file:
mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE)
__version__ = mo.group(1)
__all__ = [
'core',
'demos',
'enums',
'services'
]
| # Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import re
# Dynamically set __version__
version_path = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'version.py')
with open(version_path, 'r') as version_file:
mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE)
__version__ = mo.group(1)
__all__ = ['core', 'demos', 'services']
|
Correct timeout to 3 seconds
Avoid repeated print attempts within 3 seconds of the original (this
was the original intent, but the time period was set to 1 second) | // Extension to monitor attempts to print pages.
(function () {
"use strict";
GOVUK.analyticsPlugins = GOVUK.analyticsPlugins || {};
GOVUK.analyticsPlugins.printIntent = function () {
var printAttempt = (function () {
GOVUK.analytics.trackEvent('Print Intent', document.location.pathname);
GOVUK.analytics.trackPageview('/print' + document.location.pathname);
});
// Most browsers
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print'),
mqlListenerCount = 0;
mediaQueryList.addListener(function (mql) {
if (!mql.matches && mqlListenerCount === 0) {
printAttempt();
mqlListenerCount++;
// If we try and print again within 3 seconds, don't log it
window.setTimeout(function () {
mqlListenerCount = 0;
// printing will be tracked again now
}, 3000);
}
});
}
// IE < 10
if (window.onafterprint) {
window.onafterprint = printAttempt;
}
};
}());
| // Extension to monitor attempts to print pages.
(function () {
"use strict";
GOVUK.analyticsPlugins = GOVUK.analyticsPlugins || {};
GOVUK.analyticsPlugins.printIntent = function () {
var printAttempt = (function () {
GOVUK.analytics.trackEvent('Print Intent', document.location.pathname);
GOVUK.analytics.trackPageview('/print' + document.location.pathname);
});
// Most browsers
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print'),
mqlListenerCount = 0;
mediaQueryList.addListener(function (mql) {
if (!mql.matches && mqlListenerCount === 0) {
printAttempt();
mqlListenerCount++;
// If we try and print again in 3 seconds, don't log it
window.setTimeout(function () {
mqlListenerCount = 0;
// printing will be tracked again now
}, 1000);
}
});
}
// IE < 10
if (window.onafterprint) {
window.onafterprint = printAttempt;
}
};
}());
|
Revert "Moving to localhost for testing"
This reverts commit 19e27ec078033c5ffe7b982ddc46e9426b48209c. | // Load in modules
var fs = require('fs');
global.fs = fs;
global.assert = require('assert');
global.request = require('request');
// Load in DOM specific modules
global.jsdom = require('jsdom');
var jqueryPath = __dirname + '/test_files/jquery.js';
global.jqueryPath = jqueryPath;
global.jquerySrc = fs.readFileSync(jqueryPath, 'utf8');
// Set up config
var config = {
host: 'http://twolfson.com',
url: function getUrl (path) {
return this.host + path;
},
navigateToRaw: function (options, cb) {
// Collect arguments
var args = [].slice.call(arguments);
// If the options are a string
if (typeof options === 'string') {
options = config.url(options);
} else {
options.url = config.url(options.url);
}
// Call request
var that = this;
request(options, function getPage (err, res, body) {
// Save response
that.err = err;
that.res = res;
that.body = body;
// Callback
cb(err);
});
},
navigateTo: function (options) {
return function navFn (cb) {
return config.navigateToRaw.call(this, options, cb);
};
}
};
global.config = config; | // Load in modules
var fs = require('fs');
global.fs = fs;
global.assert = require('assert');
global.request = require('request');
// Load in DOM specific modules
global.jsdom = require('jsdom');
var jqueryPath = __dirname + '/test_files/jquery.js';
global.jqueryPath = jqueryPath;
global.jquerySrc = fs.readFileSync(jqueryPath, 'utf8');
// Set up config
var config = {
host: 'http://localhost:8080',
url: function getUrl (path) {
return this.host + path;
},
navigateToRaw: function (options, cb) {
// Collect arguments
var args = [].slice.call(arguments);
// If the options are a string
if (typeof options === 'string') {
options = config.url(options);
} else {
options.url = config.url(options.url);
}
// Call request
var that = this;
request(options, function getPage (err, res, body) {
// Save response
that.err = err;
that.res = res;
that.body = body;
// Callback
cb(err);
});
},
navigateTo: function (options) {
return function navFn (cb) {
return config.navigateToRaw.call(this, options, cb);
};
}
};
global.config = config; |
Update post view sorting (so latest comes first) | # -*- coding: utf-8 -*-
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
class PostView(ModelView):
column_default_sort = ('date', True)
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
admin.add_view(PostView(models.Post, db.session, category="Post"))
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
| # -*- coding: utf-8 -*-
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
admin.add_view(ModelView(models.Post, db.session, category="Post"))
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
|
Fix error in Questionable Content crawler when feed entry does not contain date | from comics.crawler.crawlers import BaseComicCrawler
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.feed_url = 'http://www.questionablecontent.net/QCRSS.xml'
self.parse_feed()
for entry in self.feed.entries:
if ('updated_parsed' in entry and
self.timestamp_to_date(entry.updated_parsed) == self.pub_date):
self.title = entry.title
pieces = entry.summary.split('"')
for i, piece in enumerate(pieces):
if piece.count('src='):
self.url = pieces[i + 1]
return
| from comics.crawler.crawlers import BaseComicCrawler
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.feed_url = 'http://www.questionablecontent.net/QCRSS.xml'
self.parse_feed()
for entry in self.feed['entries']:
if self.timestamp_to_date(entry['updated_parsed']) == self.pub_date:
self.title = entry['title']
pieces = entry['summary'].split('"')
for i, piece in enumerate(pieces):
if piece.count('src='):
self.url = pieces[i + 1]
return
|
Add mixin to make the case-insensitive email auth backend more flexible | from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveEmailBackendMixin(object):
def authenticate(self, username=None, password=None, **kwargs):
if username is not None:
username = username.lower()
return super(CaseInsensitiveEmailBackendMixin, self).authenticate(
username=username,
password=password,
**kwargs
)
class CaseInsensitiveEmailBackend(ModelBackend):
"""
This authentication backend assumes that usernames are email addresses and simply lowercases
a username before an attempt is made to authenticate said username using Django's ModelBackend.
Example usage:
# In settings.py
AUTHENTICATION_BACKENDS = ('authtools.backends.CaseInsensitiveEmailBackend',)
NOTE:
A word of caution. Use of this backend presupposes a way to ensure that users cannot create
usernames that differ only in case (e.g., joe@test.org and JOE@test.org). Using this backend
in such a system is a huge security risk.
"""
def authenticate(self, username=None, password=None, **kwargs):
if username is not None:
username = username.lower()
return super(CaseInsensitiveEmailBackend, self).authenticate(
username=username,
password=password,
**kwargs
)
| from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveEmailBackend(ModelBackend):
"""
This authentication backend assumes that usernames are email addresses and simply lowercases
a username before an attempt is made to authenticate said username using Django's ModelBackend.
Example usage:
# In settings.py
AUTHENTICATION_BACKENDS = ('authtools.backends.CaseInsensitiveEmailBackend',)
NOTE:
A word of caution. Use of this backend presupposes a way to ensure that users cannot create
usernames that differ only in case (e.g., joe@test.org and JOE@test.org). Using this backend
in such a system is a huge security risk.
"""
def authenticate(self, username=None, password=None, **kwargs):
if username is not None:
username = username.lower()
return super(CaseInsensitiveEmailBackend, self).authenticate(
username=username,
password=password,
**kwargs
)
|
Stop using PHP 5.4 short array syntax. Package only requires 5.3.7 | <?php
use Psr\Log\LogLevel;
return array(
'delete' => array(
'error' => 'There was an error while deleting the log.',
'success' => 'Log deleted successfully!',
'text' => 'Delete Current Log',
),
'empty_file' => ':sapi log for :date appears to be empty. Did you manually delete the contents?',
'levels' => array(
'all' => 'all',
'emergency' => LogLevel::EMERGENCY,
'alert' => LogLevel::ALERT,
'critical' => LogLevel::CRITICAL,
'error' => LogLevel::ERROR,
'warning' => LogLevel::WARNING,
'notice' => LogLevel::NOTICE,
'info' => LogLevel::INFO,
'debug' => LogLevel::DEBUG,
),
'no_log' => 'No :sapi log available for :date.',
// @TODO Find out what sapi nginx, IIS, etc. show up as.
'sapi' => array(
'apache' => 'Apache',
'cgi-fcgi' => 'Fast CGI',
'cli' => 'CLI',
),
); | <?php
use Psr\Log\LogLevel;
return [
'delete' => array(
'error' => 'There was an error while deleting the log.',
'success' => 'Log deleted successfully!',
'text' => 'Delete Current Log',
),
'empty_file' => ':sapi log for :date appears to be empty. Did you manually delete the contents?',
'levels' => [
'all' => 'all',
'emergency' => LogLevel::EMERGENCY,
'alert' => LogLevel::ALERT,
'critical' => LogLevel::CRITICAL,
'error' => LogLevel::ERROR,
'warning' => LogLevel::WARNING,
'notice' => LogLevel::NOTICE,
'info' => LogLevel::INFO,
'debug' => LogLevel::DEBUG,
],
'no_log' => 'No :sapi log available for :date.',
'sapi' => [
'apache' => 'Apache',
'cli' => 'CLI'
],
]; |
Fix missing function reference in Make command | "use strict";
const {exec} = require("child_process");
const commands = {
/* Run GNU Make from project directory */
"user:make" (){
const projectPath = atom.project.getPaths();
exec(`cd '${projectPath[0]}' && make`);
},
/* Toggle bracket-matcher highlights */
"body user:toggle-bracket-matcher" (){
let el = getRootEditorElement();
el && el.classList.toggle("show-bracket-matcher");
},
/* Reset editor's size to my preferred default, not Atom's */
"user:reset-font-size" (){
atom.config.set("editor.fontSize", 11);
},
/* File-Icons: Debugging commands */
"file-icons:toggle-changed-only":_=> atom.config.set("file-icons.onChanges", !(atom.config.get("file-icons.onChanges"))),
"file-icons:toggle-tab-icons":_=> atom.config.set("file-icons.tabPaneIcon", !(atom.config.get("file-icons.tabPaneIcon"))),
"file-icons:open-settings":_=> atom.workspace.open("atom://config/packages/file-icons"),
};
for(let name in commands){
let cmd = name.split(/\s+/);
if(cmd.length < 2) cmd.unshift("");
atom.commands.add(cmd[0] || "atom-workspace", cmd[1], commands[name]);
}
| "use strict";
const commands = {
/* Run GNU Make from project directory */
"user:make" (){
const projectPath = atom.project.getPaths();
exec(`cd '${projectPath[0]}' && make`);
},
/* Toggle bracket-matcher highlights */
"body user:toggle-bracket-matcher" (){
let el = getRootEditorElement();
el && el.classList.toggle("show-bracket-matcher");
},
/* Reset editor's size to my preferred default, not Atom's */
"user:reset-font-size" (){
atom.config.set("editor.fontSize", 11);
},
/* File-Icons: Debugging commands */
"file-icons:toggle-changed-only":_=> atom.config.set("file-icons.onChanges", !(atom.config.get("file-icons.onChanges"))),
"file-icons:toggle-tab-icons":_=> atom.config.set("file-icons.tabPaneIcon", !(atom.config.get("file-icons.tabPaneIcon"))),
"file-icons:open-settings":_=> atom.workspace.open("atom://config/packages/file-icons"),
};
for(let name in commands){
let cmd = name.split(/\s+/);
if(cmd.length < 2) cmd.unshift("");
atom.commands.add(cmd[0] || "atom-workspace", cmd[1], commands[name]);
}
|
Add output option to use response.content stream | # flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
elif output == 'stream':
content = await response.content.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
| # flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
|
Make number of vertices configurable | <?php
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Loader\CompleteGraph;
class CompleteGraphTest extends TestCase
{
public function testOne(){
$loader = new CompleteGraph(1);
$graph = $loader->createGraph();
$expected = new Graph();
$expected->createVertex();
$this->assertGraphEquals($expected,$graph);
}
public function testUndirected(){
$n = 9;
$loader = new CompleteGraph($n);
$graph = $loader->createGraph();
$this->assertEquals($n,$graph->getNumberOfVertices());
$this->assertEquals($n*($n-1)/2,$graph->getNumberOfEdges());
}
public function testDirected(){
$n = 8;
$loader = new CompleteGraph($n);
$loader->setEnableDirectedEdges(true);
$graph = $loader->createGraph();
$this->assertEquals($n,$graph->getNumberOfVertices());
$this->assertEquals($n*($n-1),$graph->getNumberOfEdges()); // n*(n-1) for directed graphs
$this->assertTrue($graph->isDirected());
$this->assertTrue($graph->isComplete());
}
}
| <?php
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Loader\CompleteGraph;
class CompleteGraphTest extends TestCase
{
public function testOne(){
$loader = new CompleteGraph(1);
$graph = $loader->createGraph();
$expected = new Graph();
$expected->createVertex();
$this->assertGraphEquals($expected,$graph);
}
public function testTen(){
$loader = new CompleteGraph(10);
$graph = $loader->createGraph();
$this->assertEquals(10,$graph->getNumberOfVertices()); // $n
$this->assertEquals(45,$graph->getNumberOfEdges()); // n*(n-1)/2
}
public function testDirected(){
$loader = new CompleteGraph(5);
$loader->setEnableDirectedEdges(true);
$graph = $loader->createGraph();
$this->assertEquals(5,$graph->getNumberOfVertices());
$this->assertEquals(20,$graph->getNumberOfEdges()); // n*(n-1) for directed graphs
$this->assertTrue($graph->isDirected());
$this->assertTrue($graph->isComplete());
}
}
|
Update dots lineplot example to use relplot | """
Line plots on multiple facets
=============================
_thumb: .45, .42
"""
import seaborn as sns
sns.set(style="ticks")
dots = sns.load_dataset("dots")
# Define a palette to ensure that colors will be
# shared across the facets
palette = dict(zip(dots.coherence.unique(),
sns.color_palette("rocket_r", 6)))
# Plot the lines on two facets
sns.relplot(x="time", y="firing_rate",
hue="coherence", size="choice", col="align",
size_order=["T1", "T2"], palette=palette,
height=5, aspect=.75, facet_kws=dict(sharex=False),
kind="line", legend="full", data=dots)
| """
Line plots on multiple facets
=============================
_thumb: .45, .42
"""
import seaborn as sns
sns.set(style="ticks")
dots = sns.load_dataset("dots")
# Define a palette to ensure that colors will be
# shared across the facets
palette = dict(zip(dots.coherence.unique(),
sns.color_palette("rocket_r", 6)))
# Set up the FacetGrid with independent x axes
g = sns.FacetGrid(dots, col="align",
sharex=False, size=5, aspect=.75)
# Draw the lineplot on each facet
g.map_dataframe(sns.lineplot, "time", "firing_rate",
hue="coherence", size="choice",
size_order=["T1", "T2"],
palette=palette)
g.add_legend()
|
Add function to Virtual Queue Repository interface | /*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.gpay.virtualqueue.backendservice.repository;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.model.Token;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;
public interface VirtualQueueRepository {
public UUID createShop(CreateShopRequest createShopRequest);
public Map<UUID, Shop> getAllShops();
public List<Token> getTokensByShopId(UUID shopId);
}
| /*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.gpay.virtualqueue.backendservice.repository;
import java.util.Map;
import java.util.UUID;
import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;
public interface VirtualQueueRepository {
public UUID createShop(CreateShopRequest createShopRequest);
public Map<UUID, Shop> getAllShops();
}
|
Change incorrect comment for error handler | var config = require("./config.js");
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.set('log level', 1);
// all environments
app.set('port', process.env.PORT || 80);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: config.security.sessionKey }));
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// route registration
require('./routes')(app, config.db);
// socket.io server logic
require('./lib/poem-editing')(io, config.db);
// error handler
app.use(function(err, req, res, next) {
console.error('***UNHANDLED ERROR: ', err.stack);
res.send(500, 'Internal server error');
});
// start the http server
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
| var config = require("./config.js");
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.set('log level', 1);
// all environments
app.set('port', process.env.PORT || 80);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: config.security.sessionKey }));
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// route registration
require('./routes')(app, config.db);
// socket.io server logic
require('./lib/poem-editing')(io, config.db);
// development only
app.use(function(err, req, res, next) {
console.error('***UNHANDLED ERROR: ', err.stack);
res.send(500, 'Internal server error');
});
// start the http server
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
Set default logging to info | from functools import lru_cache
import boto3
from pydantic import BaseSettings, Field, root_validator
@lru_cache
def get_secrets_client():
return boto3.client("secretsmanager")
@lru_cache
def get_secret(secret_id):
client = get_secrets_client()
secret_value = client.get_secret_value(SecretId=secret_id)
return secret_value["SecretString"]
class Config(BaseSettings):
environment: str
evm_full_node_url: str
reward_root_submitter_address: str
reward_root_submitter_private_key: str
reward_root_submitter_sentry_dsn: str
log_level: str = Field("INFO")
@root_validator(pre=True)
def load_secrets(cls, values):
env = values["environment"]
for field_name, field in cls.__fields__.items():
# Check it isn't already set *and* there is no default
if field_name not in values and field.default is None:
values[field_name] = get_secret(f"{env}_{field_name}")
return values
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
| from functools import lru_cache
import boto3
from pydantic import BaseSettings, Field, root_validator
@lru_cache
def get_secrets_client():
return boto3.client("secretsmanager")
@lru_cache
def get_secret(secret_id):
client = get_secrets_client()
secret_value = client.get_secret_value(SecretId=secret_id)
return secret_value["SecretString"]
class Config(BaseSettings):
environment: str
evm_full_node_url: str
reward_root_submitter_address: str
reward_root_submitter_private_key: str
reward_root_submitter_sentry_dsn: str
log_level: str = Field("WARNING")
@root_validator(pre=True)
def load_secrets(cls, values):
env = values["environment"]
for field_name, field in cls.__fields__.items():
# Check it isn't already set *and* there is no default
if field_name not in values and field.default is None:
values[field_name] = get_secret(f"{env}_{field_name}")
return values
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
|
Fix spacing on import in ReadmePage. | /*
* ReadmePage
*
* This is the page users see when they click the "Setup" button on the HomePage
*/
import React, { Component } from 'react';
import { Link } from 'react-router';
export default class AboutPage extends Component {
render() {
return (
<div>
<h2>Further Setup</h2>
<p>Assuming you have already cloned the repo and ran all the commands from the README (otherwise you would not be here), these are the further steps:</p>
<ol>
<li>Replace my name and the package name in the package.json file</li>
<li>Replace the two components with your first component</li>
<li>Replace the default actions with your first action</li>
<li>Delete css/components/_home.css and add the styling for your component</li>
<li>And finally, update the unit tests</li>
</ol>
<Link className="btn" to="/">Home</Link>
</div>
);
}
}
| /*
* ReadmePage
*
* This is the page users see when they click the "Setup" button on the HomePage
*/
import React, { Component} from 'react';
import { Link } from 'react-router';
export default class AboutPage extends Component {
render() {
return (
<div>
<h2>Further Setup</h2>
<p>Assuming you have already cloned the repo and ran all the commands from the README (otherwise you would not be here), these are the further steps:</p>
<ol>
<li>Replace my name and the package name in the package.json file</li>
<li>Replace the two components with your first component</li>
<li>Replace the default actions with your first action</li>
<li>Delete css/components/_home.css and add the styling for your component</li>
<li>And finally, update the unit tests</li>
</ol>
<Link className="btn" to="/">Home</Link>
</div>
);
}
}
|
Disable JS test for a while since the CP hack breaks things | /*
* Copyright 2016 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.vertx.ext.web.templ;
import io.vertx.lang.js.ClasspathFileResolver;
import io.vertx.test.lang.js.JSTestBase;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author Thomas Segismont
*/
public class FreeMarkerJavascriptTemplateTest extends JSTestBase {
// static {
// ClasspathFileResolver.init();
// }
@Override
protected String getTestFile() {
return "freemarker_javascript_template_test.js";
}
@Test
@Ignore
public void testTemplate() throws Exception {
runTest();
}
}
| /*
* Copyright 2016 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.vertx.ext.web.templ;
import io.vertx.lang.js.ClasspathFileResolver;
import io.vertx.test.lang.js.JSTestBase;
import org.junit.Test;
/**
* @author Thomas Segismont
*/
public class FreeMarkerJavascriptTemplateTest extends JSTestBase {
static {
ClasspathFileResolver.init();
}
@Override
protected String getTestFile() {
return "freemarker_javascript_template_test.js";
}
@Test
public void testTemplate() throws Exception {
runTest();
}
}
|
Change url to base url in mobile app delete | const CoreView = require('backbone/core-view');
const template = require('./delete-mobile-app.tpl');
const checkAndBuildOpts = require('builder/helpers/required-opts');
const REQUIRED_OPTS = [
'modalModel',
'configModel',
'authenticityToken',
'needsPasswordConfirmation'
];
module.exports = CoreView.extend({
events: {
'submit .js-form': '_close',
'click .js-cancel': '_close'
},
initialize: function (options) {
checkAndBuildOpts(options, REQUIRED_OPTS, this);
},
render: function () {
const mobileAppId = this.options.mobileApp.id;
this.$el.html(
template({
formAction: `${this._configModel.get('base_url')}/your_apps/mobile/${mobileAppId}`,
authenticityToken: this._authenticityToken,
passwordNeeded: this._needsPasswordConfirmation
})
);
},
_close: function () {
this._modalModel.destroy();
}
});
| const CoreView = require('backbone/core-view');
const template = require('./delete-mobile-app.tpl');
const checkAndBuildOpts = require('builder/helpers/required-opts');
const REQUIRED_OPTS = [
'modalModel',
'configModel',
'authenticityToken',
'needsPasswordConfirmation'
];
module.exports = CoreView.extend({
events: {
'submit .js-form': '_close',
'click .js-cancel': '_close'
},
initialize: function (options) {
checkAndBuildOpts(options, REQUIRED_OPTS, this);
},
render: function () {
const mobileAppId = this.options.mobileApp.id;
this.$el.html(
template({
formAction: `${this._configModel.prefixUrl()}/your_apps/mobile/${mobileAppId}`,
authenticityToken: this._authenticityToken,
passwordNeeded: this._needsPasswordConfirmation
})
);
},
_close: function () {
this._modalModel.destroy();
}
});
|
Fix error when auth not present
Change-Id: I8222b18587954fa00c5887aaf0e67db958509c7e | 'use strict'
var ComposrError = require('composr-core').ComposrError
var logger = require('../../utils/composrLogger')
var tokenVerifier = require('corbel-token-verifier')
/**
* Token Object Middleware
*/
module.exports = function () {
return function tokenObjectHook (req, res, next) {
var authHeader = req.header('Authorization') || ''
if(!authHeader){
return next()
}
var tokenObject = tokenVerifier(authHeader)
if (authHeader && !tokenObject) {
logger.debug('[CorbelAuthHook]', 'Malformed user token')
return next(new ComposrError('error:malformed:token', 'Your token is malformed', 400))
} else if (!tokenObject) {
logger.debug('[CorbelAuthHook]', 'Request without token')
} else {
logger.debug('[CorbelAuthHook]', 'Request with token')
req.tokenObject = tokenObject
}
return next()
}
}
| 'use strict'
var ComposrError = require('composr-core').ComposrError
var logger = require('../../utils/composrLogger')
var tokenVerifier = require('corbel-token-verifier')
/**
* Token Object Middleware
*/
module.exports = function () {
return function tokenObjectHook (req, res, next) {
var authHeader = req.header('Authorization') || ''
var tokenObject = tokenVerifier(authHeader)
if (authHeader && !tokenObject) {
logger.debug('[CorbelAuthHook]', 'Malformed user token')
return next(new ComposrError('error:malformed:token', 'Your token is malformed', 400))
} else if (!tokenObject) {
logger.debug('[CorbelAuthHook]', 'Request without token')
} else {
logger.debug('[CorbelAuthHook]', 'Request with token')
req.tokenObject = tokenObject
}
return next()
}
}
|
Use route names to get URIs for testing | <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class AdminTest extends TestCase
{
/**
* Test to see that the admin pages can be loaded
* @dataProvider adminPages
*
* @return void
*/
public function testAdminPagesLoadProperly($routeName, $value)
{
$this->withoutMiddleware()->get(route($routeName))->assertSee($value);
}
public function adminPages()
{
return [
['locations.index', 'Locations'],
['manufacturers.index', 'Manufacturers'],
['modalities.index', 'Modalities'],
['testers.index', 'Testers'],
['testtypes.index', 'Test Types'],
];
}
}
| <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AdminTest extends TestCase
{
/**
* Test to see that the admin pages can be loaded
* @dataProvider adminPages
*
* @return void
*/
public function testAdminPages($uri, $value)
{
$this->withoutMiddleware()->get($uri)->assertSee($value);
}
public function adminPages()
{
return [
['/admin/locations', 'Locations'],
['/admin/manufacturers', 'Manufacturers'],
['/admin/modalities', 'Modalities'],
['/admin/testers', 'Testers'],
['/admin/testtypes', 'Test Types'],
];
}
}
|
Allow admins to access Horizon | <?php
namespace App\Providers;
use App\Models\Reply;
use App\Models\Thread;
use App\User;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\ServiceProvider;
use Laravel\Horizon\Horizon;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
$this->bootEloquentMorphs();
$this->bootMacros();
$this->bootHorizon();
}
private function bootEloquentMorphs()
{
Relation::morphMap([
Thread::TABLE => Thread::class,
Reply::TABLE => Reply::class,
User::TABLE => User::class,
]);
}
public function bootMacros()
{
require base_path('resources/macros/blade.php');
}
public function bootHorizon()
{
Horizon::routeMailNotificationsTo($horizonEmail = config('lio.horizon.email'));
Horizon::routeSlackNotificationsTo(config('lio.horizon.webhook'));
Horizon::auth(function ($request) {
return auth()->check() && auth()->user()->isAdmin();
});
}
}
| <?php
namespace App\Providers;
use App\Models\Reply;
use App\Models\Thread;
use App\User;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\ServiceProvider;
use Laravel\Horizon\Horizon;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
$this->bootEloquentMorphs();
$this->bootMacros();
$this->bootHorizon();
}
private function bootEloquentMorphs()
{
Relation::morphMap([
Thread::TABLE => Thread::class,
Reply::TABLE => Reply::class,
User::TABLE => User::class,
]);
}
public function bootMacros()
{
require base_path('resources/macros/blade.php');
}
public function bootHorizon()
{
Horizon::routeMailNotificationsTo($horizonEmail = config('lio.horizon.email'));
Horizon::routeSlackNotificationsTo(config('lio.horizon.webhook'));
Horizon::auth(function ($request) use ($horizonEmail) {
return auth()->check() && auth()->user()->emailAddress() === $horizonEmail;
});
}
}
|
Add targetname option in unit test. | "use strict";
var fs = require('fs');
var should = require('chai').should();
var pdf2img = require('../index.js');
var input = __dirname + '/test.pdf';
pdf2img.setOptions({
outputdir: __dirname + '/output',
targetname: 'test'
});
describe('Split and covert pdf into images', function() {
it ('Create png files', function(done) {
this.timeout(100000);
console.log(input);
pdf2img.convert(input, function(err, info) {
var n = 1;
console.log(info);
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.png');
if (n === 3) done();
n++;
});
});
});
it ('Create jpg files', function(done) {
this.timeout(60000);
console.log(input);
pdf2img.setOptions({ type: 'jpg' });
pdf2img.convert(input, function(err, info) {
var n = 1;
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.jpg');
if (n === 3) done();
n++;
});
});
});
});
| "use strict";
var fs = require('fs');
var should = require('chai').should();
var pdf2img = require('../index.js');
var input = __dirname + '/test.pdf';
pdf2img.setOptions({ outputdir: __dirname + '/output' });
describe('Split and covert pdf into images', function() {
it ('Create png files', function(done) {
this.timeout(100000);
console.log(input);
pdf2img.convert(input, function(err, info) {
var n = 1;
console.log(info);
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.png');
if (n === 3) done();
n++;
});
});
});
it ('Create jpg files', function(done) {
this.timeout(60000);
console.log(input);
pdf2img.setOptions({ type: 'jpg' });
pdf2img.convert(input, function(err, info) {
var n = 1;
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.jpg');
if (n === 3) done();
n++;
});
});
});
});
|
Use os.Exit() in order to make this tool more usable for scripts, than panic() does. | // Copyright 2014 The Dename 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 main
import (
"crypto/rand"
"github.com/agl/ed25519"
. "github.com/andres-erbsen/dename/protocol"
"fmt"
"os"
)
func main() {
pk, sk, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
fmt.Fprintf(os.Stderr, "unable to create ed25519 keys")
os.Exit(1)
}
if _, err := os.Stderr.Write(sk[:]); err != nil {
fmt.Fprintf(os.Stderr, "unable to write secret key")
os.Exit(1)
}
if _, err := os.Stdout.Write(PBEncode(&Profile_PublicKey{Ed25519: pk[:]})); err != nil {
fmt.Fprintf(os.Stderr, "unable to write public key")
os.Exit(1)
}
}
| // Copyright 2014 The Dename 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 main
import (
"crypto/rand"
"github.com/agl/ed25519"
. "github.com/andres-erbsen/dename/protocol"
"os"
)
func main() {
pk, sk, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
if _, err := os.Stderr.Write(sk[:]); err != nil {
panic(err)
}
if _, err := os.Stdout.Write(PBEncode(&Profile_PublicKey{Ed25519: pk[:]})); err != nil {
panic(err)
}
}
|
Improve test coverage and deprecate some methods. | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.bytes.util;
import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/*
* Created by Peter Lawrey on 17/09/15.
*/
public class StringInternerBytesTest {
@Test
public void testIntern() {
@NotNull StringInternerBytes si = new StringInternerBytes(128);
for (int i = 0; i < 100; i++) {
Bytes b = Bytes.from("key" + i);
si.intern(b, (int) b.readRemaining());
}
assertEquals(86, si.valueCount());
}
} | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.bytes.util;
import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/*
* Created by Peter Lawrey on 17/09/15.
*/
public class StringInternerBytesTest {
@Test
public void testIntern() {
@NotNull StringInternerBytes si = new StringInternerBytes(128);
for (int i = 0; i < 100; i++) {
Bytes b = Bytes.from("key" + i);
si.intern(b, (int) b.readRemaining());
}
assertEquals(82, si.valueCount());
}
} |
Use new imageunpacker/client.AddDevice() function in unpacker-tool. | package main
import (
"fmt"
uclient "github.com/Symantec/Dominator/imageunpacker/client"
"github.com/Symantec/Dominator/lib/srpc"
"io"
"os"
"os/exec"
)
func addDeviceSubcommand(client *srpc.Client, args []string) {
if err := addDevice(client, args[0], args[1], args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error adding device: %s\n", err)
os.Exit(1)
}
os.Exit(0)
}
func addDevice(client *srpc.Client, deviceId, command string,
args []string) error {
return uclient.AddDevice(client, deviceId,
func() error { return adder(command, args) })
}
func adder(command string, args []string) error {
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
if err != io.EOF {
return err
}
}
return nil
}
| package main
import (
"errors"
"fmt"
"github.com/Symantec/Dominator/lib/srpc"
"io"
"os"
"os/exec"
)
func addDeviceSubcommand(client *srpc.Client, args []string) {
if err := addDevice(client, args[0], args[1], args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error adding device: %s\n", err)
os.Exit(1)
}
os.Exit(0)
}
func addDevice(client *srpc.Client, deviceId, command string,
args []string) error {
conn, err := client.Call("ImageUnpacker.AddDevice")
if err != nil {
return err
}
response, err := conn.ReadString('\n')
if err != nil {
return err
}
response = response[:len(response)-1]
if response != "" {
return errors.New(response)
}
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
if err != io.EOF {
return err
}
}
if _, err := conn.WriteString(deviceId + "\n"); err != nil {
return err
}
if err := conn.Flush(); err != nil {
return err
}
response, err = conn.ReadString('\n')
if err != nil {
return err
}
response = response[:len(response)-1]
if response != "" {
return errors.New(response)
}
return nil
}
|
Add linting task before test task | const path = require('path');
const gulp = require('gulp');
const babel = require('gulp-babel');
const eslint = require('gulp-eslint');
const Server = require('karma').Server;
const src = 'src/*.js';
gulp.task('lint', () => (
gulp.src(src)
.pipe(eslint())
.pipe(eslint.format())
));
gulp.task('test', ['lint'], done => {
new Server({
configFile: path.join(__dirname, '/karma.conf.js'),
singleRun: true,
autoWatch: false,
}, done).start();
});
gulp.task('tdd', done => {
new Server({
configFile: path.join(__dirname, '/karma.conf.js'),
}, done).start();
});
gulp.task('build', ['test'], () => (
gulp.src(src)
.pipe(babel())
.pipe(gulp.dest('lib'))
));
gulp.task('default', ['build']);
| const path = require('path');
const gulp = require('gulp');
const babel = require('gulp-babel');
const eslint = require('gulp-eslint');
const Server = require('karma').Server;
const src = 'src/*.js';
gulp.task('lint', () => (
gulp.src(src)
.pipe(eslint())
.pipe(eslint.format())
));
gulp.task('test', done => {
new Server({
configFile: path.join(__dirname, '/karma.conf.js'),
singleRun: true,
autoWatch: false,
}, done).start();
});
gulp.task('tdd', done => {
new Server({
configFile: path.join(__dirname, '/karma.conf.js'),
}, done).start();
});
gulp.task('build', ['test'], () => (
gulp.src(src)
.pipe(babel())
.pipe(gulp.dest('lib'))
));
gulp.task('default', ['build']);
|
Fix story parsing regexp to ignore ZWSP and ZWNBSP characters between newlines | package net.bloople.stories;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;
/**
* Created by i on 27/05/2016.
*/
public class StoryParser {
private Scanner scanner;
public StoryParser(Reader reader) {
scanner = new Scanner(reader);
scanner.useDelimiter("(?:\r?\n[\u200B\uFEFF]*){2,}+");
}
public boolean hasNext() throws IOException {
return scanner.hasNext();
}
public Node next() throws IOException {
String content = scanner.next();
if(content.startsWith("#")) {
return NodeFactory.heading(content);
}
else {
return NodeFactory.paragraph(content);
}
}
}
| package net.bloople.stories;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;
/**
* Created by i on 27/05/2016.
*/
public class StoryParser {
private Scanner scanner;
public StoryParser(Reader reader) {
scanner = new Scanner(reader);
scanner.useDelimiter("(?:\r?\n){2,}+");
}
public boolean hasNext() throws IOException {
return scanner.hasNext();
}
public Node next() throws IOException {
String content = scanner.next();
if(content.startsWith("#")) {
return NodeFactory.heading(content);
}
else {
return NodeFactory.paragraph(content);
}
}
}
|
Check if browser accepts Webp instead of .png | package imgwizard
import (
"bytes"
"image"
"image/png"
"net/http"
"github.com/foobaz/lossypng/lossypng"
"github.com/shifr/vips"
)
func Transform(img_buff *[]byte, ctx *Context) {
var err error
buf := new(bytes.Buffer)
debug("Detecting image type...")
iType := http.DetectContentType(*img_buff)
if !stringExists(iType, ResizableImageTypes) {
warning("Wizard resize doesn't support image type, returning original image")
return
}
*img_buff, err = vips.Resize(*img_buff, ctx.Options)
if err != nil {
warning("Can't resize img, reason - %s", err)
return
}
if iType == PNG && !ctx.Options.Webp {
decoded, _, err := image.Decode(bytes.NewReader(*img_buff))
if err != nil {
warning("Can't decode PNG image, reason - %s", err)
}
out := lossypng.Compress(decoded, lossypng.NoConversion, 100-ctx.Options.Quality)
err = png.Encode(buf, out)
if err != nil {
warning("Can't encode PNG image, reason - %s", err)
}
*img_buff = buf.Bytes()
}
}
| package imgwizard
import (
"bytes"
"image"
"image/png"
"net/http"
"github.com/foobaz/lossypng/lossypng"
"github.com/shifr/vips"
)
func Transform(img_buff *[]byte, ctx *Context) {
var err error
buf := new(bytes.Buffer)
debug("Detecting image type...")
iType := http.DetectContentType(*img_buff)
if !stringExists(iType, ResizableImageTypes) {
warning("Wizard resize doesn't support image type, returning original image")
return
}
*img_buff, err = vips.Resize(*img_buff, ctx.Options)
if err != nil {
warning("Can't resize img, reason - %s", err)
return
}
if iType == PNG {
decoded, _, err := image.Decode(bytes.NewReader(*img_buff))
if err != nil {
warning("Can't decode PNG image, reason - %s", err)
}
out := lossypng.Compress(decoded, lossypng.NoConversion, 100-ctx.Options.Quality)
err = png.Encode(buf, out)
if err != nil {
warning("Can't encode PNG image, reason - %s", err)
}
*img_buff = buf.Bytes()
}
}
|
Rename selector variable to type | #!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')(process.argv.slice(2));
var printHelp = function() {
console.log('oust');
console.log(pkg.description);
console.log('');
console.log('Usage:');
console.log(' $ oust <filename> <selector>');
};
if(argv.h || argv.help) {
printHelp();
return;
}
if(argv.v || argv.version) {
console.log(pkg.version);
return;
}
var file = argv._[0];
var type = argv._[1];
fs.readFile(file, function(err, data) {
if(err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
var res = oust(data, type);
console.log(res.join("\n"));
});
| #!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')(process.argv.slice(2));
var printHelp = function() {
console.log('oust');
console.log(pkg.description);
console.log('');
console.log('Usage:');
console.log(' $ oust <filename> <selector>');
};
if(argv.h || argv.help) {
printHelp();
return;
}
if(argv.v || argv.version) {
console.log(pkg.version);
return;
}
var file = argv._[0];
var selector = argv._[1];
fs.readFile(file, function(err, data) {
if(err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
var res = oust(data, selector);
console.log(res.join("\n"));
});
|
Set the status code through $context->response. | <?php
/**
* @version $Id: default.php 3314 2012-02-10 02:14:52Z johanjanssens $
* @package Nooku_Server
* @subpackage Settings
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Setting Controller Class
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @package Nooku_Server
* @subpackage Settings
*/
class ComExtensionsControllerSetting extends ComDefaultControllerDefault
{
protected function _initialize(KConfig $config)
{
$config->append(array(
'request' => array('view' => 'settings')
));
parent::_initialize($config);
}
protected function _actionRead(KCommandContext $context)
{
$name = ucfirst($this->getView()->getName());
if(!$this->getModel()->getState()->isUnique()) {
$context->response->setStatus(KHttpResponse::NOT_FOUND, $name.' Not Found');
}
return parent::_actionRead($context);
}
} | <?php
/**
* @version $Id: default.php 3314 2012-02-10 02:14:52Z johanjanssens $
* @package Nooku_Server
* @subpackage Settings
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Setting Controller Class
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @package Nooku_Server
* @subpackage Settings
*/
class ComExtensionsControllerSetting extends ComDefaultControllerDefault
{
protected function _initialize(KConfig $config)
{
$config->append(array(
'request' => array('view' => 'settings')
));
parent::_initialize($config);
}
protected function _actionRead(KCommandContext $context)
{
$name = ucfirst($this->getView()->getName());
if(!$this->getModel()->getState()->isUnique()) {
$context->setError(new KControllerException($name.' Not Found', KHttpResponse::NOT_FOUND));
}
return parent::_actionRead($context);
}
} |
Disable passwordless sms mode for now | import ContainerManager from './container_manager';
import { LockModes } from '../control/constants';
import renderCrashed from '../crashed/render';
import renderPasswordlessEmail from '../passwordless-email/render';
import renderPasswordlessSMS from '../passwordless-sms/render';
import React from 'react';
import * as l from './index';
export default class Renderer {
constructor() {
this.containerManager = new ContainerManager();
}
render(locks) {
locks.filter(l.render).forEach(lock => {
const container = this.containerManager.ensure(l.ui.containerID(lock), l.ui.appendContainer(lock));
if (lock.get("show")) {
React.render(this.element(lock), container);
} else if (container) {
React.unmountComponentAtNode(container);
}
});
}
element(lock) {
// TODO: mode specific renderer specs should be passed to the constructor
const mode = lock.get("mode");
switch(mode) {
case LockModes.CRASHED:
return renderCrashed(lock);
case LockModes.PASSWORDLESS_EMAIL:
return renderPasswordlessEmail(lock);
// case LockModes.PASSWORDLESS_SMS:
// return renderPasswordlessSMS(lock);
default:
throw new Error(`unknown lock mode ${mode}`);
}
}
}
| import ContainerManager from './container_manager';
import { LockModes } from '../control/constants';
import renderCrashed from '../crashed/render';
import renderPasswordlessEmail from '../passwordless-email/render';
import renderPasswordlessSMS from '../passwordless-sms/render';
import React from 'react';
import * as l from './index';
export default class Renderer {
constructor() {
this.containerManager = new ContainerManager();
}
render(locks) {
locks.filter(l.render).forEach(lock => {
const container = this.containerManager.ensure(l.ui.containerID(lock), l.ui.appendContainer(lock));
if (lock.get("show")) {
React.render(this.element(lock), container);
} else if (container) {
React.unmountComponentAtNode(container);
}
});
}
element(lock) {
// TODO: mode specific renderer specs should be passed to the constructor
const mode = lock.get("mode");
switch(mode) {
case LockModes.CRASHED:
return renderCrashed(lock);
case LockModes.PASSWORDLESS_EMAIL:
return renderPasswordlessEmail(lock);
case LockModes.PASSWORDLESS_SMS:
return renderPasswordlessSMS(lock);
default:
throw new Error(`unknown lock mode ${mode}`);
}
}
}
|
Print server response when introspection query result does not contain data | // Based on https://facebook.github.io/relay/docs/guides-babel-plugin.html#using-other-graphql-implementations
import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
import {
buildClientSchema,
introspectionQuery,
printSchema,
} from 'graphql/utilities';
import { ApolloError } from './errors'
export default async function downloadSchema(url, outputPath) {
let result;
try {
const response = await fetch(`${url}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'query': introspectionQuery }),
});
result = await response.json();
} catch (error) {
throw new ApolloError(`Error while fetching introspection query result: ${error.message}`);
}
if (result.errors) {
throw new ApolloError(`Errors in introspection query result: ${result.errors}`);
}
const schemaData = result.data;
if (!schemaData) {
throw new ApolloError(`No introspection query result data found, server responded with: ${JSON.stringify(result)}`);
}
fs.writeFileSync(outputPath, JSON.stringify(schemaData, null, 2));
}
| // Based on https://facebook.github.io/relay/docs/guides-babel-plugin.html#using-other-graphql-implementations
import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
import {
buildClientSchema,
introspectionQuery,
printSchema,
} from 'graphql/utilities';
import { ApolloError } from './errors'
export default async function downloadSchema(url, outputPath) {
let result;
try {
const response = await fetch(`${url}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'query': introspectionQuery }),
});
result = await response.json();
} catch (error) {
throw new ApolloError(`Error while fetching introspection query result: ${error.message}`);
}
if (result.errors) {
throw new ApolloError(`Errors in introspection query result: ${result.errors}`);
}
const schemaData = result.data;
if (!schemaData) {
throw new ApolloError('No instrospection query result data');
}
fs.writeFileSync(outputPath, JSON.stringify(schemaData, null, 2));
}
|
Correct HackCWRU spelling to hackCWRU | import React from 'react';
import styles from 'components/Summary/Summary.scss';
export default class Summary extends React.Component {
render() {
return (
<div className={styles.summary}>
<div className={styles.date}>{'February 16th - 18th, 2018'}</div>
<div className={styles.description}>
hackCWRU brings together the brightest and most creative students to
promote unrestricted technological innovation.
<div className={styles.spacer}></div>
Hosted at Case Western Reserve University, over 350 students will
spend 36 hours bringing their imagination into the real world.
Attendees will work with peers and mentors to create projects in
one of four project tracks.
<div className={styles.spacer}></div>
Don't be intimidated, however. You don't have to know what you're
doing to attend. If you are new to hackathons, we look forward to
introducing you to a world of creation.
Lastly, at hackCWRU we abide by and enforce <a href="http://static.mlh.io/docs/mlh-code-of-conduct.pdf">MLH's Code of Conduct</a>.
</div>
</div>
)
}
}
| import React from 'react';
import styles from 'components/Summary/Summary.scss';
export default class Summary extends React.Component {
render() {
return (
<div className={styles.summary}>
<div className={styles.date}>{'February 16th - 18th, 2018'}</div>
<div className={styles.description}>
HackCWRU brings together the brightest and most creative students to
promote unrestricted technological innovation.
<div className={styles.spacer}></div>
Hosted at Case Western Reserve University, over 350 students will
spend 36 hours bringing their imagination into the real world.
Attendees will work with peers and mentors to create projects in
one of four project tracks.
<div className={styles.spacer}></div>
Don't be intimidated, however. You don't have to know what you're
doing to attend. If you are new to hackathons, we look forward to
introducing you to a world of creation.
Lastly, at HackCWRU we abide by and enforce <a href="http://static.mlh.io/docs/mlh-code-of-conduct.pdf">MLH's Code of Conduct</a>.
</div>
</div>
)
}
}
|
Fix indentation and parse error | /* Set up the environment before loading the rest of the files into Zotero */
var $rdf = {
Util: {
ArrayIndexOf: function (arr, item, i) {
//supported in all browsers except IE<9
return arr.indexOf(item, i);
},
RDFArrayRemove: function (a, x) { //removes all statements equal to x from a
for (var i = 0; i < a.length; i++) {
//TODO: This used to be the following, which didnt always work..why
//if(a[i] == x)
if (a[i].subject.sameTerm(x.subject) && a[i].predicate.sameTerm(x.predicate) && a[i].object.sameTerm(x.object) && a[i].why.sameTerm(x.why)) {
a.splice(i, 1);
return;
}
}
throw "RDFArrayRemove: Array did not contain " + x;
}
},
log: {
debug: Zotero.debug,
warn: Zotero.debug
}
};
if(Zotero.RDF) {
Zotero.RDF.AJAW = $rdf;
} else {
Zotero.RDF = {AJAW:$rdf};
}
var tabulator = {log: $rdf.log};
var alert = $rdf.log.warn;
| /* Set up the environment before loading the rest of the files into Zotero */
var $rdf = {
Util: {
ArrayIndexOf: function (arr, item, i) {
//supported in all browsers except IE<9
return arr.indexOf(item, i);
},
RDFArrayRemove: function (a, x) { //removes all statements equal to x from a
for (var i = 0; i < a.length; i++) {
//TODO: This used to be the following, which didnt always work..why
//if(a[i] == x)
if (a[i].subject.sameTerm(x.subject) && a[i].predicate.sameTerm(x.predicate) && a[i].object.sameTerm(x.object) && a[i].why.sameTerm(x.why)) {
a.splice(i, 1);
return;
}
}
throw "RDFArrayRemove: Array did not contain " + x;
}
},
log: {
debug: Zotero.debug,
warn: Zotero.debug
}
};
if(Zotero.RDF) {
Zotero.RDF.AJAW = $rdf;
} else {
Zotero.RDF = {AJAW:$rdf};
}
var tabulator = {log: $rdf.log};
var alert = $rdf.log.warn; |
[tfdbg] Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs
- Skip a set of TPU compilation-specific ops from tfdbg's op callbacks.
PiperOrigin-RevId: 281836861
Change-Id: Ic7ff59a32eba26d5bb3ee2ac4f5f9166c78928c8 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"LoopCond",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
# TPU-specific ops begin.
b"TPUReplicatedInput",
b"TPUReplicateMetadata",
b"TPUCompilationResult",
b"TPUReplicatedOutput",
b"ConfigureDistributedTPU",
)
| # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
)
|
Customize admin site title and header | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
admin.site.site_header = 'Release Notes Administration'
admin.site.site_title = 'Release Notes Administration'
urlpatterns = [
url(r'', include('nucleus.base.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-token-auth/',
'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^rna/', include('rna.urls')),
url(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % ('Allow' if settings.ENGAGE_ROBOTS else 'Disallow'),
content_type="text/plain")),
url(r'^healthz/$', watchman_views.ping, name="watchman.ping"),
url(r'^readiness/$', watchman_views.status, name="watchman.status"),
]
if settings.OIDC_ENABLE:
urlpatterns.append(url(r'^oidc/', include('mozilla_django_oidc.urls')))
| from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
urlpatterns = [
url(r'', include('nucleus.base.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-token-auth/',
'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^rna/', include('rna.urls')),
url(r'^robots\.txt$', lambda r: HttpResponse(
"User-agent: *\n%s: /" % ('Allow' if settings.ENGAGE_ROBOTS else 'Disallow'),
content_type="text/plain")),
url(r'^healthz/$', watchman_views.ping, name="watchman.ping"),
url(r'^readiness/$', watchman_views.status, name="watchman.status"),
]
if settings.OIDC_ENABLE:
urlpatterns.append(url(r'^oidc/', include('mozilla_django_oidc.urls')))
|
Add test for bijection init from list of pairs | """Test bijection class."""
import pytest
from collections_extended.bijection import bijection
def test_bijection():
"""General tests for bijection."""
b = bijection()
assert len(b) == 0
b['a'] = 1
assert len(b) == 1
assert b['a'] == 1
assert b.inverse[1] == 'a'
assert 'a' in b
assert 1 not in b
assert 1 in b.inverse
with pytest.raises(KeyError):
del b['f']
assert b == bijection(a=1)
assert b.inverse.inverse is b
assert b == b.copy()
del b['a']
assert b == bijection()
assert bijection(a=1, b=2, c=3) == bijection({'a': 1, 'b': 2, 'c': 3})
b['a'] = 1
b.inverse[1] = 'b'
assert 'b' in b
assert b['b'] == 1
assert 'a' not in b
def test_init_from_pairs():
assert bijection({'a': 1, 'b': 2}) == bijection((('a', 1), ('b', 2)))
| """Test bijection class."""
import pytest
from collections_extended.bijection import bijection
def test_bijection():
"""General tests for bijection."""
b = bijection()
assert len(b) == 0
b['a'] = 1
assert len(b) == 1
assert b['a'] == 1
assert b.inverse[1] == 'a'
assert 'a' in b
assert 1 not in b
assert 1 in b.inverse
with pytest.raises(KeyError):
del b['f']
assert b == bijection(a=1)
assert b.inverse.inverse is b
assert b == b.copy()
del b['a']
assert b == bijection()
assert bijection(a=1, b=2, c=3) == bijection({'a': 1, 'b': 2, 'c': 3})
b['a'] = 1
b.inverse[1] = 'b'
assert 'b' in b
assert b['b'] == 1
assert 'a' not in b
|
Determine if an action has been called
Use hasAction() to determine if the given action has been reserved by
a method already. | <?php
class Hook {
private $actions;
private $methods;
private $objects;
private $arguments;
public function __construct() {
$this->actions = array();
$this->methods = array();
$this->objects = array();
$this->arguments = array();
}
public function doAction($action) {
if (in_array($action, $this->actions)) {
$array_position = array_search($action, $this->actions);
$method = $this->methods[$array_position];
$object = $this->objects[$array_position];
$argument = $this->arguments[$array_position];
if (method_exists($object, $method)) {
return call_user_func(array($object, $method), $argument);
}
}
}
public function addAction($action, $object, $method, $argument = null) {
if (!in_array($action, $this->actions)) {
array_push($this->actions, $action);
array_push($this->methods, $method);
array_push($this->objects, $object);
array_push($this->arguments, $argument);
}
}
public function hasAction($action) {
if (in_array($action, $this->actions)) {
return true;
}
return false;
}
public function removeAction($action) {
if (in_array($action, $this->actions)) {
$array_position = array_search($action, $this->actions);
unset($this->actions[$array_position]);
}
}
}
?>
| <?php
class Hook {
private $actions;
private $methods;
private $objects;
private $arguments;
public function __construct() {
$this->actions = array();
$this->methods = array();
$this->objects = array();
$this->arguments = array();
}
public function doAction($action) {
if (in_array($action, $this->actions)) {
$array_position = array_search($action, $this->actions);
$method = $this->methods[$array_position];
$object = $this->objects[$array_position];
$argument = $this->arguments[$array_position];
if (method_exists($object, $method)) {
return call_user_func(array($object, $method), $argument);
}
}
}
public function addAction($action, $object, $method, $argument = null) {
if (!in_array($action, $this->actions)) {
array_push($this->actions, $action);
array_push($this->methods, $method);
array_push($this->objects, $object);
array_push($this->arguments, $argument);
}
}
public function removeAction($action) {
if (in_array($action, $this->actions)) {
$array_position = array_search($action, $this->actions);
unset($this->actions[$array_position]);
}
}
}
?>
|
Call enabled scope on the builder, not the collection | <ul class="list-group components">
@if($component_groups->count() > 0)
@foreach($component_groups as $componentGroup)
@if($componentGroup->components()->enabled()->count() > 0)
<li class="list-group-item group-name">
<i class="ion-ios-minus-outline group-toggle"></i>
<strong>{{ $componentGroup->name }}</strong>
</li>
<div class="group-items">
@foreach($componentGroup->components()->enabled()->orderBy('order')->get() as $component)
@include('partials.component', compact($component))
@endforeach
</div>
@endif
@endforeach
@if($ungrouped_components->count() > 0)
<li class="list-group-item break"></li>
@endif
@endif
@if($ungrouped_components->count() > 0)
@foreach($ungrouped_components as $component)
@include('partials.component', compact($component))
@endforeach
@endif
</ul>
| <ul class="list-group components">
@if($component_groups->count() > 0)
@foreach($component_groups as $componentGroup)
@if($componentGroup->components->enabled()->count() > 0)
<li class="list-group-item group-name">
<i class="ion-ios-minus-outline group-toggle"></i>
<strong>{{ $componentGroup->name }}</strong>
</li>
<div class="group-items">
@foreach($componentGroup->components->enabled()->sortBy('order') as $component)
@include('partials.component', compact($component))
@endforeach
</div>
@endif
@endforeach
@if($ungrouped_components->count() > 0)
<li class="list-group-item break"></li>
@endif
@endif
@if($ungrouped_components->count() > 0)
@foreach($ungrouped_components as $component)
@include('partials.component', compact($component))
@endforeach
@endif
</ul>
|
Change app-level error handler to use api_client.error exceptions | # coding=utf-8
from flask import render_template
from . import main
from ..api_client.error import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_page(404)
@main.app_errorhandler(500)
def internal_server_error(e):
return _render_error_page(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_page(503, e.response)
def _render_error_page(status_code, error_message=None):
templates = {
404: "errors/404.html",
500: "errors/500.html",
503: "errors/500.html",
}
if status_code not in templates:
status_code = 500
return render_template(
templates[status_code],
error_message=error_message
), status_code
| # coding=utf-8
from flask import render_template
from . import main
from dmapiclient import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_page(404)
@main.app_errorhandler(500)
def internal_server_error(e):
return _render_error_page(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_page(503, e.response)
def _render_error_page(status_code, error_message=None):
templates = {
404: "errors/404.html",
500: "errors/500.html",
503: "errors/500.html",
}
if status_code not in templates:
status_code = 500
return render_template(
templates[status_code],
error_message=error_message
), status_code
|
Allow for some missing silica bond parameters | import mbuild as mb
import parmed as pmd
import pytest
from foyer import Forcefield
from foyer.tests.utils import get_fn
@pytest.mark.timeout(1)
def test_fullerene():
fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True)
forcefield = Forcefield(get_fn('fullerene.xml'))
forcefield.apply(fullerene, assert_dihedral_params=False)
@pytest.mark.timeout(15)
def test_surface():
surface = mb.load(get_fn('silica.mol2'))
forcefield = Forcefield(get_fn('opls-silica.xml'))
forcefield.apply(surface, assert_bond_params=False)
@pytest.mark.timeout(45)
def test_polymer():
peg100 = mb.load(get_fn('peg100.mol2'))
forcefield = Forcefield(name='oplsaa')
forcefield.apply(peg100)
| import mbuild as mb
import parmed as pmd
import pytest
from foyer import Forcefield
from foyer.tests.utils import get_fn
@pytest.mark.timeout(1)
def test_fullerene():
fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True)
forcefield = Forcefield(get_fn('fullerene.xml'))
forcefield.apply(fullerene, assert_dihedral_params=False)
@pytest.mark.timeout(15)
def test_surface():
surface = mb.load(get_fn('silica.mol2'))
forcefield = Forcefield(get_fn('opls-silica.xml'))
forcefield.apply(surface)
@pytest.mark.timeout(45)
def test_polymer():
peg100 = mb.load(get_fn('peg100.mol2'))
forcefield = Forcefield(name='oplsaa')
forcefield.apply(peg100)
|
Add extra check to make sure there is a titlesArray | import React, {Component} from 'react';
export default class ReportAnalysisArea extends Component {
render() {
const {customFeatureTitle} = this.props.params;
// This will be useful later when we do have have multiple titles to display in the Analysis ReportAnalysisArea.
const titlesArray = customFeatureTitle.split(',');
return (
<div className="map-analysis-area-container">
<div id="map" className="map"></div>
<div id="analysis-area" className="analysis-area">
<span className="analysis-area-subtitle">AREA OF ANALYSIS</span>
<ul className="analysis-area-list">
{titlesArray && titlesArray.map((title, index) => <li key={`analysis-area-${index}`}className="analysis-area-list-item">{title}</li>)}
</ul>
</div>
</div>
);
}
}
| import React, {Component} from 'react';
export default class ReportAnalysisArea extends Component {
render() {
const {customFeatureTitle} = this.props.params;
// This will be useful later when we do have have multiple titles to display in the Analysis ReportAnalysisArea.
const titlesArray = customFeatureTitle.split(',');
return (
<div className="map-analysis-area-container">
<div id="map" className="map"></div>
<div id="analysis-area" className="analysis-area">
<span className="analysis-area-subtitle">AREA OF ANALYSIS</span>
<ul className="analysis-area-list">
{titlesArray.map((title, index) => <li key={`analysis-area-${index}`}className="analysis-area-list-item">{title}</li>)}
</ul>
</div>
</div>
);
}
}
|
Order paginated KV API results. | from rest_framework import viewsets
from wafer.kv.models import KeyValue
from wafer.kv.serializers import KeyValueSerializer
from wafer.kv.permissions import KeyValueGroupPermission
from wafer.utils import order_results_by
class KeyValueViewSet(viewsets.ModelViewSet):
"""API endpoint that allows key-value pairs to be viewed or edited."""
queryset = KeyValue.objects.none() # Needed for the REST Permissions
serializer_class = KeyValueSerializer
permission_classes = (KeyValueGroupPermission, )
@order_results_by('key', 'id')
def get_queryset(self):
# Restrict the list to only those that match the user's
# groups
if self.request.user.id is not None:
grp_ids = [x.id for x in self.request.user.groups.all()]
return KeyValue.objects.filter(group_id__in=grp_ids)
return KeyValue.objects.none()
| from rest_framework import viewsets
from wafer.kv.models import KeyValue
from wafer.kv.serializers import KeyValueSerializer
from wafer.kv.permissions import KeyValueGroupPermission
class KeyValueViewSet(viewsets.ModelViewSet):
"""API endpoint that allows key-value pairs to be viewed or edited."""
queryset = KeyValue.objects.none() # Needed for the REST Permissions
serializer_class = KeyValueSerializer
permission_classes = (KeyValueGroupPermission, )
def get_queryset(self):
# Restrict the list to only those that match the user's
# groups
if self.request.user.id is not None:
grp_ids = [x.id for x in self.request.user.groups.all()]
return KeyValue.objects.filter(group_id__in=grp_ids)
return KeyValue.objects.none()
|
Add locale to tree node event. | <?php
/*
* This file is part of the Tadcka package.
*
* (c) Tadas Gliaubicas <tadcka89@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tadcka\Component\Tree\Event;
use Symfony\Component\EventDispatcher\Event;
use Tadcka\Component\Tree\Model\NodeInterface;
/**
* @author Tadas Gliaubicas <tadcka89@gmail.com>
*
* @since 9/6/14 2:12 PM
*/
class TreeNodeEvent extends Event
{
/**
* @var NodeInterface
*/
private $node;
/**
* @var string
*/
private $locale;
/**
* Constructor.
*
* @param string $locale
* @param NodeInterface $node
*/
public function __construct($locale, NodeInterface $node)
{
$this->locale = $locale;
$this->node = $node;
}
/**
* Get locale.
*
* @return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* Get node.
*
* @return NodeInterface
*/
public function getNode()
{
return $this->node;
}
}
| <?php
/*
* This file is part of the Tadcka package.
*
* (c) Tadas Gliaubicas <tadcka89@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tadcka\Component\Tree\Event;
use Symfony\Component\EventDispatcher\Event;
use Tadcka\Component\Tree\Model\NodeInterface;
/**
* @author Tadas Gliaubicas <tadcka89@gmail.com>
*
* @since 9/6/14 2:12 PM
*/
class TreeNodeEvent extends Event
{
/**
* @var NodeInterface
*/
private $node;
/**
* Constructor.
*
* @param NodeInterface $node
*/
public function __construct(NodeInterface $node)
{
$this->node = $node;
}
/**
* Get node.
*
* @return NodeInterface
*/
public function getNode()
{
return $this->node;
}
}
|
Fix PyPI README.MD showing problem.
There is a problem in the project's PyPI page. To fix this I added the following line in the setup.py file:
```python
long_description_content_type='text/markdown'
``` | from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name = 'django-heroku-postgresify',
version = '0.4',
py_modules = ('postgresify',),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package dependencies:
install_requires = ['Django>=1.2', 'dj-database-url>=0.3.0'],
# Metadata for PyPI:
author = 'Randall Degges',
author_email = 'rdegges@gmail.com',
license = 'UNLICENSE',
url = 'https://github.com/rdegges/django-heroku-postgresify',
keywords = 'django heroku cloud postgresql postgres db database awesome epic',
description = 'Automatic Django database configuration on Heroku.',
long_description = open(normpath(join(dirname(abspath(__file__)),
'README.md'))).read(),
long_description_content_type='text/markdown'
)
| from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name = 'django-heroku-postgresify',
version = '0.4',
py_modules = ('postgresify',),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package dependencies:
install_requires = ['Django>=1.2', 'dj-database-url>=0.3.0'],
# Metadata for PyPI:
author = 'Randall Degges',
author_email = 'rdegges@gmail.com',
license = 'UNLICENSE',
url = 'https://github.com/rdegges/django-heroku-postgresify',
keywords = 'django heroku cloud postgresql postgres db database awesome epic',
description = 'Automatic Django database configuration on Heroku.',
long_description = open(normpath(join(dirname(abspath(__file__)),
'README.md'))).read()
)
|
Remove unused config file reference. | const
Hapi = require('hapi')
, Path = require('path')
, helper = require('./helper.js');
/* Configure the Hapi server */
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.views({
engines: {
html: require('handlebars')
},
path: Path.join(__dirname, 'templates')
});
server.route([
{
path: '/public/{path*}',
method: 'GET',
handler: {
directory: {
path: "./public",
listing: false,
index: false
}
}
},
{
method: 'GET',
path: '/',
handler: function(request, reply) {
reply.view('index', {
title: 'FetchrBot | Home'});
}
},
{
method: 'GET',
path: '/twilioCall',
handler: function(request, reply) {
/* Send the client the data being requested */
helper.parseRequestBody(request, function(err, parsedData) {
if (!err) {
helper.sendSMSToClient(request, parsedData);
};
});
}
}
]);
server.start(function() {
console.log("The magic happens on port " + server.info.port);
});
| const
Hapi = require('hapi')
, Path = require('path')
, helper = require('./helper.js')
, config = require('./config.js');
/* Configure the Hapi server */
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.views({
engines: {
html: require('handlebars')
},
path: Path.join(__dirname, 'templates')
});
server.route([
{
path: '/public/{path*}',
method: 'GET',
handler: {
directory: {
path: "./public",
listing: false,
index: false
}
}
},
{
method: 'GET',
path: '/',
handler: function(request, reply) {
reply.view('index', {
title: 'FetchrBot | Home'});
}
},
{
method: 'GET',
path: '/twilioCall',
handler: function(request, reply) {
/* Send the client the data being requested */
helper.parseRequestBody(request, function(err, parsedData) {
if (!err) {
helper.sendSMSToClient(request, parsedData);
};
});
}
}
]);
server.start(function() {
console.log("The magic happens on port " + server.info.port);
});
|
Add https status on error | /**
* Seed controller for fill your db of fake data
*/
import HTTPStatus from 'http-status';
import User from '../models/user.model';
import { userSeed, deleteUserSeed } from '../seeds/user.seed';
export async function seedUsers(req, res, next) {
try {
await userSeed(req.params.count);
return res
.status(HTTPStatus.OK)
.send(`User seed success! Created ${req.params.count} users!`);
} catch (e) {
e.status = HTTPStatus.BAD_REQUEST;
return next(e);
}
}
export async function clearSeedUsers(req, res, next) {
try {
await deleteUserSeed();
return res.status(HTTPStatus.OK).send('User collection empty');
} catch (e) {
e.status = HTTPStatus.BAD_REQUEST;
return next(e);
}
}
/**
* Take all your model and clear it
*
* @param {any} req
* @param {any} res
* @returns {String} All collections clear
*/
export async function clearAll(req, res, next) {
try {
await Promise.all([User.remove()]);
return res.status(HTTPStatus.OK).send('All collections clear');
} catch (e) {
e.status = HTTPStatus.BAD_REQUEST;
return next(e);
}
}
| /**
* Seed controller for fill your db of fake data
*/
import HTTPStatus from 'http-status';
import User from '../models/user.model';
import { userSeed, deleteUserSeed } from '../seeds/user.seed';
export async function seedUsers(req, res, next) {
try {
await userSeed(req.params.count);
return res
.status(HTTPStatus.OK)
.send(`User seed success! Created ${req.params.count} users!`);
} catch (e) {
return next(e);
}
}
export async function clearSeedUsers(req, res, next) {
try {
await deleteUserSeed();
return res.status(HTTPStatus.OK).send('User collection empty');
} catch (e) {
return next(e);
}
}
/**
* Take all your model and clear it
*
* @param {any} req
* @param {any} res
* @returns {String} All collections clear
*/
export async function clearAll(req, res, next) {
try {
await Promise.all([User.remove()]);
return res.status(HTTPStatus.OK).send('All collections clear');
} catch (e) {
return next(e);
}
}
|
Fix KernalAwareTest to use the correct kernel | <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Tests;
use SolidInvoice\Kernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
abstract class KernelAwareTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
* @var Kernel
*/
protected $kernel;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var Container
*/
protected $container;
public function setUp(): void
{
$this->kernel = new Kernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
parent::setUp();
}
public function tearDown(): void
{
$this->kernel->shutdown();
parent::tearDown();
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Tests;
use AppKernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
require_once __DIR__.'/../../../app/AppKernel.php';
abstract class KernelAwareTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
* @var AppKernel
*/
protected $kernel;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var Container
*/
protected $container;
public function setUp(): void
{
$this->kernel = new AppKernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
parent::setUp();
}
public function tearDown(): void
{
$this->kernel->shutdown();
parent::tearDown();
}
}
|
Adjust start up service: remove obsolete mail addresses
* Mail addresses for bosses and office are no longer
configured in a properties file, so no need to log
them anymore in start up service. |
package org.synyx.urlaubsverwaltung.core.startup;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
* This service is executed every time the application is started.
*
* @author Aljona Murygina - murygina@synyx.de
*/
@Service
public class StartupService {
private static final Logger LOG = Logger.getLogger(StartupService.class);
@Value("${db.username}")
private String dbUser;
@Value("${db.url}")
private String dbUrl;
@Value("${email.manager}")
private String emailManager;
@PostConstruct
public void logStartupInfo() {
LOG.info("Using database " + dbUrl + " with user " + dbUser);
LOG.info("Using following email address for technical notification: " + emailManager);
}
}
|
package org.synyx.urlaubsverwaltung.core.startup;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
* This service is executed every time the application is started.
*
* @author Aljona Murygina - murygina@synyx.de
*/
@Service
public class StartupService {
private static final Logger LOG = Logger.getLogger(StartupService.class);
@Value("${db.username}")
private String dbUser;
@Value("${db.url}")
private String dbUrl;
@Value("${email.boss}")
private String emailBoss;
@Value("${email.office}")
private String emailOffice;
@Value("${email.all}")
private String emailAll;
@Value("${email.manager}")
private String emailManager;
@PostConstruct
public void logStartupInfo() {
LOG.info("Using database " + dbUrl + " with user " + dbUser);
LOG.info("Using following email addresses for notification:");
LOG.info("Email boss: " + emailBoss);
LOG.info("Email office: " + emailOffice);
LOG.info("Email all: " + emailAll);
LOG.info("Email manager: " + emailManager);
}
}
|
Use assert_allclose for comparison of octree densities | import os
import h5py
import numpy as np
from numpy.testing import assert_allclose
from ..sph import construct_octree
DATA = os.path.join(os.path.dirname(__file__), 'data')
def test_construct_octree():
np.random.seed(0)
N = 5000
px = np.random.uniform(-10., 10., N)
py = np.random.uniform(-10., 10., N)
pz = np.random.uniform(-10., 10., N)
mass = np.random.uniform(0., 1., N)
sigma = np.random.uniform(0., 0.1, N)
o = construct_octree(0.1, 0.2, 0.3, 6., 5., 4.,
px, py, pz,
sigma, mass, n_levels=10)
# The following lines can be used to write out the reference file if the
# SPH gridding code is updated.
# f = h5py.File('reference_octree.hdf5', 'w')
# o.write(f)
# f.close()
from hyperion.grid import OctreeGrid
f = h5py.File(os.path.join(DATA, 'reference_octree.hdf5'), 'r')
o_ref = OctreeGrid()
o_ref.read(f)
f.close()
assert np.all(o_ref.refined == o.refined)
assert_allclose(o_ref['density'][0].array, o['density'][0].array)
| import os
import h5py
import numpy as np
from ..sph import construct_octree
DATA = os.path.join(os.path.dirname(__file__), 'data')
def test_construct_octree():
np.random.seed(0)
N = 5000
px = np.random.uniform(-10., 10., N)
py = np.random.uniform(-10., 10., N)
pz = np.random.uniform(-10., 10., N)
mass = np.random.uniform(0., 1., N)
sigma = np.random.uniform(0., 0.1, N)
o = construct_octree(0.1, 0.2, 0.3, 6., 5., 4.,
px, py, pz,
sigma, mass, n_levels=10)
# The following lines can be used to write out the reference file if the
# SPH gridding code is updated.
# f = h5py.File('reference_octree.hdf5', 'w')
# o.write(f)
# f.close()
from hyperion.grid import OctreeGrid
f = h5py.File(os.path.join(DATA, 'reference_octree.hdf5'), 'r')
o_ref = OctreeGrid()
o_ref.read(f)
f.close()
assert np.all(o_ref.refined == o.refined)
assert np.all(o_ref['density'][0].array == o['density'][0].array)
|
Update anchor tag in footer to react Link component | import React from 'react';
import { Link, Route, Switch } from 'react-router-dom';
import Landing from './Landing';
import Dashboard from './Dashboard';
import WishlistPublic from './WishlistPublic';
import WishlistPrivate from './WishlistPrivate';
import AboutUs from './AboutUs';
import Pairing from './Pairing';
import Messaging from './Messaging';
import SecureOrg from './SecureOrg';
const Main = (props) => {
return (
<div>
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/wishlist" component={WishlistPublic} />
<Route path="/aboutus" component={AboutUs} />
<Route path="/secure/wishlist" component={WishlistPrivate} /> {/* Secure */}
<Route path="/secure/pairing" component={Pairing} /> {/* Secure */}
<Route path="/secure/messaging" component={Messaging} /> {/* Secure */}
<Route path="/secure/org" component={SecureOrg} /> {/* Secure */}
</Switch>
<footer>
<Link to="/">
<button>
Home
</button>
</Link>
</footer>
</div>
);
};
export default Main;
| import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Landing from './Landing';
import Dashboard from './Dashboard';
import WishlistPublic from './WishlistPublic';
import WishlistPrivate from './WishlistPrivate';
import AboutUs from './AboutUs';
import Pairing from './Pairing';
import Messaging from './Messaging';
import SecureOrg from './SecureOrg';
const Main = (props) => {
return (
<div>
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/wishlist" component={WishlistPublic} />
<Route path="/aboutus" component={AboutUs} />
<Route path="/secure/wishlist" component={WishlistPrivate} /> {/* Secure */}
<Route path="/secure/pairing" component={Pairing} /> {/* Secure */}
<Route path="/secure/messaging" component={Messaging} /> {/* Secure */}
<Route path="/secure/org" component={SecureOrg} /> {/* Secure */}
</Switch>
<footer>
<a href="/">
<button>
Home
</button>
</a>
</footer>
</div>
);
};
export default Main; |
Use ng-bind instead of {{}} for header entry directive. | "use strict";
angular.module("hikeio").
directive("headerEntry", function() {
return {
scope: {
align: "@",
label: "@",
url: "@"
},
compile: function(tplElm, tplAttr) {
// Include link only if url is included (otherwise, on some browsers it implies /)
if (!tplAttr.url) {
var link = tplElm.children()[0];
tplElm.empty();
tplElm.append(link.children);
}
},
template: "<a href='{{url}}'>" +
"<div data-ng-style='{float:align}' >" +
"<div class='header-separator' data-ng-show='align == \"right\"'></div>" +
"<div class='header-entry' data-ng-transclude>" +
"<span class='label' data-ng-show='label' data-ng-bind='label'></span>" +
"</div>" +
"<div class='header-separator' data-ng-show='align == \"left\"'></div>" +
"</div>" +
"</a>",
transclude: true
};
}); | "use strict";
angular.module("hikeio").
directive("headerEntry", function() {
return {
scope: {
align: "@",
label: "@",
url: "@"
},
compile: function(tplElm, tplAttr) {
// Include link only if url is included (otherwise, on some browsers it implies /)
if (!tplAttr.url) {
var link = tplElm.children()[0];
tplElm.empty();
tplElm.append(link.children);
}
},
template: "<a href='{{url}}'>" +
"<div data-ng-style='{float:align}' >" +
"<div class='header-separator' data-ng-show='align == \"right\"'></div>" +
"<div class='header-entry' data-ng-transclude>" +
"<span class='label' data-ng-show='label'>{{label}}</span>" +
"</div>" +
"<div class='header-separator' data-ng-show='align == \"left\"'></div>" +
"</div>" +
"</a>",
transclude: true
};
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.