text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update UnknownCFTypeError to print the type name | package plist
// #include <CoreFoundation/CoreFoundation.h>
import "C"
import "reflect"
import "strconv"
// An UnsupportedTypeError is returned by Marshal when attempting to encode an
// unsupported value type.
type UnsupportedTypeError struct {
Type reflect.Type
}
func (e *UnsupportedTypeError) Error() string {
return "plist: unsupported type: " + e.Type.String()
}
type UnsupportedValueError struct {
Value reflect.Value
Str string
}
func (e *UnsupportedValueError) Error() string {
return "json: unsupported value: " + e.Str
}
type UnknownCFTypeError struct {
CFTypeID C.CFTypeID
}
func (e *UnknownCFTypeError) Error() string {
cfStr := C.CFCopyTypeIDDescription(e.CFTypeID)
str := convertCFStringToString(cfStr)
cfRelease(cfTypeRef(cfStr))
return "plist: unknown CFTypeID " + strconv.Itoa(int(e.CFTypeID)) + " (" + str + ")"
}
// UnsupportedKeyTypeError represents the case where a CFDictionary is being converted
// back into a map[string]interface{} but its key type is not a CFString.
//
// This should never occur in practice, because the only CFDictionaries that
// should be handled are coming from property lists, which require the keys to
// be strings.
type UnsupportedKeyTypeError struct {
CFTypeID int
}
func (e *UnsupportedKeyTypeError) Error() string {
return "plist: unexpected dictionary key CFTypeID " + strconv.Itoa(e.CFTypeID)
}
| package plist
// #include <CoreFoundation/CoreFoundation.h>
import "C"
import "reflect"
import "strconv"
// An UnsupportedTypeError is returned by Marshal when attempting to encode an
// unsupported value type.
type UnsupportedTypeError struct {
Type reflect.Type
}
func (e *UnsupportedTypeError) Error() string {
return "plist: unsupported type: " + e.Type.String()
}
type UnsupportedValueError struct {
Value reflect.Value
Str string
}
func (e *UnsupportedValueError) Error() string {
return "json: unsupported value: " + e.Str
}
type UnknownCFTypeError struct {
CFTypeID C.CFTypeID
}
func (e *UnknownCFTypeError) Error() string {
return "plist: unknown CFTypeID " + strconv.Itoa(int(e.CFTypeID))
}
// UnsupportedKeyTypeError represents the case where a CFDictionary is being converted
// back into a map[string]interface{} but its key type is not a CFString.
//
// This should never occur in practice, because the only CFDictionaries that
// should be handled are coming from property lists, which require the keys to
// be strings.
type UnsupportedKeyTypeError struct {
CFTypeID int
}
func (e *UnsupportedKeyTypeError) Error() string {
return "plist: unexpected dictionary key CFTypeID " + strconv.Itoa(e.CFTypeID)
}
|
Fix require path typo error. | var Browser = require('zombie'),
browser = new Browser(),
assert = require('assert'),
server = require('../server/server'),
router = require('../server/router'),
requestHandler = require('../server/requestHandler');
before(function() {
var handle = {};
handle["/"] = requestHandler.start;
handle["/start"] = requestHandler.start;
handle["/upload"] = requestHandler.upload;
handle["/show"] = requestHandler.show;
//server.start(router.route, handle);
});
suite('GET', function() {
before(function() {
this.browser = new Browser({ site: 'http://140.115.53.50:8888' });
});
suite('/', function() {
beforeEach(function(done) {
this.browser.visit('/', done);
});
test('should return request object', function() {
assert.notEqual(undefined, server);
});
});
});
| var Browser = require('zombie'),
browser = new Browser(),
assert = require('assert'),
server = require('../server/server'),
router = require('../server/router'),
requestHandler = require('./server/requestHandler');
before(function() {
var handle = {};
handle["/"] = requestHandler.start;
handle["/start"] = requestHandler.start;
handle["/upload"] = requestHandler.upload;
handle["/show"] = requestHandler.show;
//server.start(router.route, handle);
});
suite('GET', function() {
before(function() {
this.browser = new Browser({ site: 'http://140.115.53.50:8888' });
});
suite('/', function() {
beforeEach(function(done) {
this.browser.visit('/', done);
});
test('should return request object', function() {
assert.notEqual(undefined, server);
});
});
});
|
Support for wrapString in newer knex versions | const Formatter = require('knex/lib/formatter');
class FormatterSOQL extends Formatter {
wrap(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
const raw = this.unwrapRaw(value);
if (raw) return raw;
if (typeof value === 'number') return value;
// save compatibility with older knex.js versions
return (this.wrapString || this._wrapString).call(this, `${value}`);
}
outputQuery(compiled) {
let sql = compiled.sql || '';
if (sql) {
if (compiled.method === 'select') {
sql = `(${sql})`;
if (compiled.as) return this.alias(sql, this.wrap(compiled.as));
}
}
return sql;
}
}
module.exports = FormatterSOQL;
| const Formatter = require('knex/lib/formatter');
class FormatterSOQL extends Formatter {
wrap(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
const raw = this.unwrapRaw(value);
if (raw) return raw;
if (typeof value === 'number') return value;
return this._wrapString(`${value}`);
}
outputQuery(compiled) {
let sql = compiled.sql || '';
if (sql) {
if (compiled.method === 'select') {
sql = `(${sql})`;
if (compiled.as) return this.alias(sql, this.wrap(compiled.as));
}
}
return sql;
}
}
module.exports = FormatterSOQL;
|
Remove equivalentProfileItemExists method from interface. PL-11206. | package com.amee.domain;
import com.amee.base.domain.ResultsWrapper;
import com.amee.domain.data.DataCategory;
import com.amee.domain.item.BaseItemValue;
import com.amee.domain.item.profile.ProfileItem;
import com.amee.domain.item.profile.ProfileItemNumberValue;
import com.amee.domain.profile.Profile;
import com.amee.platform.science.StartEndDate;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public interface ProfileItemService extends ItemService {
@Override
ProfileItem getItemByUid(String uid);
boolean hasNonZeroPerTimeValues(ProfileItem profileItem);
boolean isNonZeroPerTimeValue(ProfileItemNumberValue value);
boolean isSingleFlight(ProfileItem profileItem);
int getProfileItemCount(Profile profile, DataCategory dataCategory);
ResultsWrapper<ProfileItem> getProfileItems(Profile profile, ProfileItemsFilter filter);
List<ProfileItem> getProfileItems(Profile profile, IDataCategoryReference dataCategory, Date profileDate);
List<ProfileItem> getProfileItems(Profile profile, IDataCategoryReference dataCategory, StartEndDate startDate, StartEndDate endDate);
boolean isUnique(ProfileItem pi);
Collection<Long> getProfileDataCategoryIds(Profile profile);
void persist(ProfileItem profileItem);
void remove(ProfileItem profileItem);
void persist(BaseItemValue itemValue);
void remove(BaseItemValue itemValue);
void updateProfileItemValues(ProfileItem profileItem);
}
| package com.amee.domain;
import com.amee.base.domain.ResultsWrapper;
import com.amee.domain.data.DataCategory;
import com.amee.domain.item.BaseItemValue;
import com.amee.domain.item.profile.ProfileItem;
import com.amee.domain.item.profile.ProfileItemNumberValue;
import com.amee.domain.profile.Profile;
import com.amee.platform.science.StartEndDate;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public interface ProfileItemService extends ItemService {
@Override
ProfileItem getItemByUid(String uid);
boolean hasNonZeroPerTimeValues(ProfileItem profileItem);
boolean isNonZeroPerTimeValue(ProfileItemNumberValue value);
boolean isSingleFlight(ProfileItem profileItem);
int getProfileItemCount(Profile profile, DataCategory dataCategory);
ResultsWrapper<ProfileItem> getProfileItems(Profile profile, ProfileItemsFilter filter);
List<ProfileItem> getProfileItems(Profile profile, IDataCategoryReference dataCategory, Date profileDate);
List<ProfileItem> getProfileItems(Profile profile, IDataCategoryReference dataCategory, StartEndDate startDate, StartEndDate endDate);
boolean isUnique(ProfileItem pi);
boolean equivalentProfileItemExists(ProfileItem profileItem);
Collection<Long> getProfileDataCategoryIds(Profile profile);
void persist(ProfileItem profileItem);
void remove(ProfileItem profileItem);
void persist(BaseItemValue itemValue);
void remove(BaseItemValue itemValue);
void updateProfileItemValues(ProfileItem profileItem);
}
|
Remove column from error output for now | 'use strict';
var configLoader = require('./config-loader');
var LessHint = require('./lesshint');
var meow = require('meow');
var Vow = require('vow');
module.exports = function () {
var lesshint = new LessHint();
var promises = [];
var config;
var args = meow({
pkg: '../package.json'
});
try {
config = configLoader(args.flags.c || args.flags.config);
} catch (e) {
console.error('Something\'s wrong with the config file.');
process.exit(1);
}
lesshint.configure(config);
promises = args.input.map(lesshint.checkPath, lesshint);
Vow.all(promises).then(function (errors) {
errors = [].concat.apply([], errors);
errors.forEach(function (error) {
console.log(
'%s %s:%d %s',
error.linter,
error.file,
error.line,
error.message
);
});
});
};
| 'use strict';
var configLoader = require('./config-loader');
var LessHint = require('./lesshint');
var meow = require('meow');
var Vow = require('vow');
module.exports = function () {
var lesshint = new LessHint();
var promises = [];
var config;
var args = meow({
pkg: '../package.json'
});
try {
config = configLoader(args.flags.c || args.flags.config);
} catch (e) {
console.error('Something\'s wrong with the config file.');
process.exit(1);
}
lesshint.configure(config);
promises = args.input.map(lesshint.checkPath, lesshint);
Vow.all(promises).then(function (errors) {
errors = [].concat.apply([], errors);
errors.forEach(function (error) {
console.log(
'%s %s:%d:%d %s',
error.linter,
error.file,
error.line,
error.column,
error.message
);
});
});
};
|
Remove Terser specifics from the shared configuration
It must only applies to TEST | const { environment } = require('@rails/webpacker')
// config
const alias = require('./config/alias')
const splitChunks = require("./config/splitChunks");
const output = require('./config/output')
environment.config.merge(alias)
environment.config.merge(splitChunks)
environment.config.merge(output)
// loaders
const vue = require('./loaders/vue')
const less = require('./loaders/less')
environment.loaders.append('less', less)
environment.loaders.append('vue', vue)
environment.loaders.delete('moduleCss')
environment.loaders.delete('moduleSass')
environment.loaders.delete('nodeModules')
// plugins
const webpack = require('webpack')
const { VueLoaderPlugin } = require('vue-loader')
const MomentLocalesPlugin = require('moment-locales-webpack-plugin')
environment.plugins.append('VueLoaderPlugin', new VueLoaderPlugin())
environment.plugins.append(
"Provide",
new webpack.ProvidePlugin({
$: "jquery",
"window.$": "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
_: "lodash"
})
)
// NOTE: Must be updated if add a new locale files - https://yarnpkg.com/es-ES/package/moment-locales-webpack-plugin
environment.plugins.append(
"MomentLocales",
new MomentLocalesPlugin({
localesToKeep: ["es", "ca"]
})
)
module.exports = environment
| const { environment } = require('@rails/webpacker')
// config
const alias = require('./config/alias')
const terser = require("./config/terser");
const splitChunks = require("./config/splitChunks");
const output = require('./config/output')
environment.config.merge(alias)
environment.config.merge(terser)
environment.config.merge(splitChunks)
environment.config.merge(output)
// loaders
const vue = require('./loaders/vue')
const less = require('./loaders/less')
environment.loaders.append('less', less)
environment.loaders.append('vue', vue)
environment.loaders.delete('moduleCss')
environment.loaders.delete('moduleSass')
environment.loaders.delete('nodeModules')
// plugins
const webpack = require('webpack')
const { VueLoaderPlugin } = require('vue-loader')
const MomentLocalesPlugin = require('moment-locales-webpack-plugin')
environment.plugins.append('VueLoaderPlugin', new VueLoaderPlugin())
environment.plugins.append(
"Provide",
new webpack.ProvidePlugin({
$: "jquery",
"window.$": "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
_: "lodash"
})
)
// NOTE: Must be updated if add a new locale files - https://yarnpkg.com/es-ES/package/moment-locales-webpack-plugin
environment.plugins.append(
"MomentLocales",
new MomentLocalesPlugin({
localesToKeep: ["es", "ca"]
})
)
module.exports = environment
|
Test case rename from checkstyle to jslint | 'use strict';
var should = require('should'),
fs = require('fs'),
xmlEmitter = require('../../lib/jslint_xml_emitter');
describe('jslint_xml', function () {
var mockXMLResults;
var xmlText;
before(function (done) {
fs.readFile('./test/jslint_xml/fixtures/mock.xml', function (err, data) {
if (err) return done(err);
mockXMLResults = data.toString('utf8');
done();
});
});
beforeEach(function () {
var errors = require('./fixtures/errors');
xmlText = xmlEmitter.getHeader();
xmlText = xmlText.concat(xmlEmitter.formatContent(errors));
xmlText = xmlText.concat(xmlEmitter.getFooter());
});
it('should transform JSHint results in jslint XML', function () {
xmlText.should.equal(mockXMLResults);
});
});
| 'use strict';
var should = require('should'),
fs = require('fs'),
xmlEmitter = require('../../lib/jslint_xml_emitter');
describe('jslint_xml', function () {
var mockXMLResults;
var xmlText;
before(function (done) {
fs.readFile('./test/jslint_xml/fixtures/mock.xml', function (err, data) {
if (err) return done(err);
mockXMLResults = data.toString('utf8');
done();
});
});
beforeEach(function () {
var errors = require('./fixtures/errors');
xmlText = xmlEmitter.getHeader();
xmlText = xmlText.concat(xmlEmitter.formatContent(errors));
xmlText = xmlText.concat(xmlEmitter.getFooter());
});
it('should transform JSHint results in checkstyle XML', function () {
xmlText.should.equal(mockXMLResults);
});
});
|
Write a \n at the end of the doc html files. |
/**
* Compiles a single file's dox output using the template.jade file.
*/
var fs = require('fs')
, basename = require('path').basename
, jade = require('jade')
, highlight = require('highlight').Highlight
, package = JSON.parse(fs.readFileSync(__dirname + '/../package.json'))
/**
* The output filename.
*/
var title = process.argv[2]
, template = __dirname + '/template.jade'
var input = ''
process.stdin.setEncoding('utf8')
process.stdin.on('data', function (b) {
input += b
})
process.stdin.on('end', function () {
input = JSON.parse(input)
render()
})
process.stdin.resume()
function render () {
var opts = {
title: title[0].toUpperCase() + title.substring(1)
, input: input
, package: package
}
, buf = fs.readFileSync(template)
, fn = jade.compile(buf, opts)
, html = fn(opts)
// Syntax highlighting
html = highlight(html, false, true)
// Output the result to stdout
process.stdout.write(html + '\n')
}
|
/**
* Compiles a single file's dox output using the template.jade file.
*/
var fs = require('fs')
, basename = require('path').basename
, jade = require('jade')
, highlight = require('highlight').Highlight
, package = JSON.parse(fs.readFileSync(__dirname + '/../package.json'))
/**
* The output filename.
*/
var title = process.argv[2]
, template = __dirname + '/template.jade'
var input = ''
process.stdin.setEncoding('utf8')
process.stdin.on('data', function (b) {
input += b
})
process.stdin.on('end', function () {
input = JSON.parse(input)
render()
})
process.stdin.resume()
function render () {
var opts = {
title: title[0].toUpperCase() + title.substring(1)
, input: input
, package: package
}
, buf = fs.readFileSync(template)
, fn = jade.compile(buf, opts)
, html = fn(opts)
// Syntax highlighting
html = highlight(html, false, true)
// Output the result to stdout
process.stdout.write(html)
}
|
Add one swing player to rule them all | package es.ucm.fdi.tp.control;
import java.util.List;
import es.ucm.fdi.tp.basecode.bgame.control.Player;
import es.ucm.fdi.tp.basecode.bgame.model.Board;
import es.ucm.fdi.tp.basecode.bgame.model.GameMove;
import es.ucm.fdi.tp.basecode.bgame.model.GameRules;
import es.ucm.fdi.tp.basecode.bgame.model.Piece;
public class SwingPlayer extends Player {
private static final long serialVersionUID = -257722318128195740L;
private GameMove move;
public SwingPlayer() {}
@Override
public GameMove requestMove(Piece p, Board board, List<Piece> pieces, GameRules rules) {
if(p.equals(move.getPiece()) {
return this.move;
}
return null;
}
public void setMove(GameMove newMove) {
this.move = move;
}
public GameMove getMove() {
return this.move;
}
}
| package es.ucm.fdi.tp.control;
import java.util.List;
import es.ucm.fdi.tp.basecode.bgame.control.Player;
import es.ucm.fdi.tp.basecode.bgame.model.Board;
import es.ucm.fdi.tp.basecode.bgame.model.GameMove;
import es.ucm.fdi.tp.basecode.bgame.model.GameRules;
import es.ucm.fdi.tp.basecode.bgame.model.Piece;
public class SwingPlayer extends Player{
/**
*
*/
private static final long serialVersionUID = -257722318128195740L;
@Override
public GameMove requestMove(Piece p, Board board, List<Piece> pieces, GameRules rules) {
// TODO Auto-generated method stub
return null;
}
private void setMove(){
}
}
|
Fix default config usage ejs | 'use strict';
/**
* Module dependencies
*/
// Native
const path = require('path');
// Externals
const co = require('co');
const render = require('koa-ejs');
/**
* EJS hook
*/
module.exports = function(strapi) {
const hook = {
/**
* Default options
*/
defaults: {
root: path.join(strapi.config.appPath, strapi.config.paths.views),
layout: 'layout',
viewExt: 'ejs',
cache: true,
debug: true,
},
/**
* Initialize the hook
*/
initialize () {
// Force cache mode in production
if (strapi.config.environment === 'production') {
strapi.config.hook.settings.ejs.cache = true;
}
render(strapi.app, Object.assign(this.defaults, strapi.config.hook.settings.ejs));
strapi.app.context.render = co.wrap(strapi.app.context.render);
},
};
return hook;
};
| 'use strict';
/**
* Module dependencies
*/
// Native
const path = require('path');
// Externals
const co = require('co');
const render = require('koa-ejs');
/**
* EJS hook
*/
module.exports = function(strapi) {
const hook = {
/**
* Default options
*/
defaults: {
root: path.join(strapi.config.appPath, strapi.config.paths.views),
layout: 'layout',
viewExt: 'ejs',
cache: true,
debug: true,
},
/**
* Initialize the hook
*/
initialize: () => {
// Force cache mode in production
if (strapi.config.environment === 'production') {
strapi.config.hook.settings.ejs.cache = true;
}
render(strapi.app, strapi.config.hook.settings.ejs);
strapi.app.context.render = co.wrap(strapi.app.context.render);
},
};
return hook;
};
|
Change option from extraKeys to addKeyMaps | import React from 'react'
import SimpleMDE from 'react-simplemde-editor'
const PoemEditor = (props) => {
const extraKeys = {
// 'Ctrl-Enter': () => { props.handleEditorSubmit() },
'Cmd-Enter': () => { props.handleEditorSubmit() },
}
return (
<div>
<SimpleMDE
onChange={props.handleEditorChange}
value={props.value}
options={{
autofocus: false,
spellChecker: false,
indentWithTabs: false,
status: false,
toolbar: false,
}}
addKeyMaps={extraKeys}
/>
<button onClick={props.handleEditorSubmit}>post</button>
</div>
)
}
export default PoemEditor
| import React from 'react'
import SimpleMDE from 'react-simplemde-editor'
const PoemEditor = (props) => {
const extraKeys = {
// 'Ctrl-Enter': () => { props.handleEditorSubmit() },
'Cmd-Enter': () => { props.handleEditorSubmit() },
}
return (
<div>
<SimpleMDE
onChange={props.handleEditorChange}
value={props.value}
extraKeys={extraKeys}
options={{
autofocus: false,
spellChecker: false,
indentWithTabs: false,
status: false,
toolbar: false,
}}
/>
<button onClick={props.handleEditorSubmit}>post</button>
</div>
)
}
export default PoemEditor
|
Add 'gym' prefix to URL in email app
The email app is supposed to be used in other parts of the application,
not only in the gym. | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from django.conf.urls import url, include
from wger.email.forms import EmailListForm
from wger.email.views import email_lists
# sub patterns for email lists
patterns_email = [
url(r'^overview/gym/(?P<gym_pk>\d+)$',
email_lists.EmailLogListView.as_view(),
name='overview'),
url(r'^add/gym/(?P<gym_pk>\d+)$',
email_lists.EmailListFormPreview(EmailListForm),
name='add'),
]
urlpatterns = [
url(r'^email/', include(patterns_email, namespace="email")),
]
| # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from django.conf.urls import url, include
from wger.email.forms import EmailListForm
from wger.email.views import email_lists
# sub patterns for email lists
patterns_email = [
url(r'^overview/(?P<gym_pk>\d+)$',
email_lists.EmailLogListView.as_view(),
name='overview'),
url(r'^add/(?P<gym_pk>\d+)$',
email_lists.EmailListFormPreview(EmailListForm),
name='add'),
]
urlpatterns = [
url(r'^email/', include(patterns_email, namespace="email")),
]
|
Clean rc from unit tests
Magnum have removed the k8s rc apis, but have not removed it from
policy.json. The patch (https://review.openstack.org/#/c/384064/)
remove rc from etc/magnum/policy.json.
And we should remove rc from tests/fake_policy.py.
Change-Id: Ia98e1637f2e3a5919be3784322a55005970d4da8 | # Copyright (c) 2012 OpenStack Foundation
#
# 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.
policy_data = """
{
"context_is_admin": "role:admin",
"admin_or_owner": "is_admin:True or project_id:%(project_id)s",
"default": "rule:admin_or_owner",
"admin_api": "rule:context_is_admin",
"bay:create": "",
"bay:delete": "",
"bay:detail": "",
"bay:get": "",
"bay:get_all": "",
"bay:update": "",
"baymodel:create": "",
"baymodel:delete": "",
"baymodel:detail": "",
"baymodel:get": "",
"baymodel:get_all": "",
"baymodel:update": ""
}
"""
| # Copyright (c) 2012 OpenStack Foundation
#
# 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.
policy_data = """
{
"context_is_admin": "role:admin",
"admin_or_owner": "is_admin:True or project_id:%(project_id)s",
"default": "rule:admin_or_owner",
"admin_api": "rule:context_is_admin",
"bay:create": "",
"bay:delete": "",
"bay:detail": "",
"bay:get": "",
"bay:get_all": "",
"bay:update": "",
"baymodel:create": "",
"baymodel:delete": "",
"baymodel:detail": "",
"baymodel:get": "",
"baymodel:get_all": "",
"baymodel:update": "",
"rc:create": "",
"rc:delete": "",
"rc:detail": "",
"rc:get": "",
"rc:get_all": "",
"rc:update": ""
}
"""
|
Add support for additional source options | <?php
namespace Bridge\HttpApi\Adapter;
use GuzzleHttp\Client;
use Transfer\Adapter\SourceAdapterInterface;
use Transfer\Adapter\Transaction\Request;
use Transfer\Adapter\Transaction\Response;
class HttpApiAdapter implements SourceAdapterInterface
{
/**
* {@inheritdoc}
*/
public function receive(Request $request)
{
$client = new Client();
$data = $request->getData();
$url = call_user_func_array('sprintf', array_merge(
array($data['source']['url']),
array_map(
function ($element) {
return urlencode($element);
},
$data['arguments']
)
));
$method = 'GET';
if (isset($data['source']['method'])) {
$method = $data['source']['method'];
}
$options = array();
if (isset($data['source']['options'])) {
$options = $data['source']['options'];
}
$response = $client->request($method, $url, $options);
return new Response((string) $response->getBody());
}
}
| <?php
namespace Bridge\HttpApi\Adapter;
use GuzzleHttp\Client;
use Transfer\Adapter\SourceAdapterInterface;
use Transfer\Adapter\Transaction\Request;
use Transfer\Adapter\Transaction\Response;
class HttpApiAdapter implements SourceAdapterInterface
{
/**
* {@inheritdoc}
*/
public function receive(Request $request)
{
$client = new Client();
$data = $request->getData();
$url = call_user_func_array('sprintf', array_merge(
array($data['source']['url']),
array_map(
function ($element) {
return urlencode($element);
},
$data['arguments']
)
));
$method = 'GET';
if (isset($data['source']['method'])) {
$method = $data['source']['method'];
}
$response = $client->request($method, $url);
return new Response((string) $response->getBody());
}
}
|
Add small change for retina | 'use strict';
import PIXI from 'pixi.js';
import RendererStore from '../stores/RendererStore.js';
export default class Renderer extends PIXI.WebGLRenderer {
constructor(...args) {
this.resolution = window.devicePixelRatio;
if(!args.length) {
args = this.getDefaults();
}
super(...args);
window.addEventListener('resize', this.resizeHanlder.bind(this));
RendererStore.set('resolution', this.resolution);
this.setStore();
}
setStore() {
RendererStore.set('width', this.getWindowSize()[0]);
RendererStore.set('height', this.getWindowSize()[1]);
}
resizeHanlder() {
this.resize(...this.getWindowSize());
this.setStore();
RendererStore.emitChange();
}
getWindowSize() {
var width = window.innerWidth / this.resolution;
var height = window.innerHeight / this.resolution;
return [width, height];
}
getDefaults() {
return [...this.getWindowSize(), {"resolution": this.resolution, "antialias" : true}];
}
}
| 'use strict';
import PIXI from 'pixi.js';
import RendererStore from '../stores/RendererStore.js';
export default class Renderer extends PIXI.WebGLRenderer {
constructor(...args) {
this.resolution = window.devicePixelRatio;
if(!args.length) {
args = this.getDefaults();
}
super(...args);
window.addEventListener('resize', this.resizeHanlder.bind(this));
RendererStore.set('resolution', this.resolution);
this.setStore();
}
setStore() {
RendererStore.set('width', this.getWindowSize()[0]);
RendererStore.set('height', this.getWindowSize()[1]);
}
resizeHanlder() {
this.resize(...this.getWindowSize());
this.setStore();
RendererStore.emitChange();
}
getWindowSize() {
var width = window.innerWidth;
var height = window.innerHeight;
return [width, height];
}
getDefaults() {
return [...this.getWindowSize(), {"resolution": this.resolution, "antialias" : true}];
}
}
|
Use external_url when TLS enabled or IP address otherwise
- Allow self-signed certificates only when in development mode
[#119388165]
Signed-off-by: Jacob Frank <e2b78b2ae98d5304f4676b7cd3c5892a0e3e7c9f@pivotal.io> | package web
import (
"crypto/tls"
"net/http"
"github.com/concourse/go-concourse/concourse"
)
type ClientFactory interface {
Build(request *http.Request) concourse.Client
}
type clientFactory struct {
apiEndpoint string
allowSelfSignedCertificates bool
}
func NewClientFactory(apiEndpoint string, allowSelfSignedCertificates bool) ClientFactory {
return &clientFactory{
apiEndpoint: apiEndpoint,
allowSelfSignedCertificates: allowSelfSignedCertificates,
}
}
func (cf *clientFactory) Build(r *http.Request) concourse.Client {
transport := authorizationTransport{
Authorization: r.Header.Get("Authorization"),
Base: &http.Transport{
DisableKeepAlives: true, // disable connection pooling
TLSClientConfig: &tls.Config{
InsecureSkipVerify: cf.allowSelfSignedCertificates,
},
},
}
httpClient := &http.Client{
Transport: transport,
}
return concourse.NewClient(cf.apiEndpoint, httpClient)
}
type authorizationTransport struct {
Base http.RoundTripper
Authorization string
}
func (transport authorizationTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Set("Authorization", transport.Authorization)
return transport.Base.RoundTrip(r)
}
| package web
import (
"net/http"
"github.com/concourse/go-concourse/concourse"
)
type ClientFactory interface {
Build(request *http.Request) concourse.Client
}
type clientFactory struct {
apiEndpoint string
}
func NewClientFactory(apiEndpoint string) ClientFactory {
return &clientFactory{
apiEndpoint: apiEndpoint,
}
}
func (cf *clientFactory) Build(r *http.Request) concourse.Client {
transport := authorizationTransport{
Authorization: r.Header.Get("Authorization"),
Base: &http.Transport{
// disable connection pooling
DisableKeepAlives: true,
},
}
httpClient := &http.Client{
Transport: transport,
}
return concourse.NewClient(cf.apiEndpoint, httpClient)
}
type authorizationTransport struct {
Base http.RoundTripper
Authorization string
}
func (transport authorizationTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Set("Authorization", transport.Authorization)
return transport.Base.RoundTrip(r)
}
|
Allow for multiple service file formats | <?php
namespace ContainerTools\Configuration;
use ContainerTools\Configuration;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class Loader
{
/**
* @var array
*/
private $serviceConfigs;
/**
* @var string
*/
private $servicesFormat;
/**
* @param Configuration $configuration
*
* @return $this
*/
public function load(Configuration $configuration)
{
$this->serviceConfigs = $configuration->getServicesFolders();
$this->servicesFormat = $configuration->getServicesFormat();
return $this;
}
/**
* @param ContainerBuilder $containerBuilder
*/
public function into(ContainerBuilder $containerBuilder)
{
$loader = new DelegatingLoader(new LoaderResolver(array(
new XmlFileLoader($containerBuilder, new FileLocator($this->serviceConfigs)),
new YamlFileLoader($containerBuilder, new FileLocator($this->serviceConfigs)),
)));
$loader->load('services.' . $this->servicesFormat);
}
} | <?php
namespace ContainerTools\Configuration;
use ContainerTools\Configuration;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class Loader
{
/**
* @var array
*/
private $serviceConfigs;
/**
* @var string
*/
private $servicesFormat;
/**
* @param Configuration $configuration
*
* @return $this
*/
public function load(Configuration $configuration)
{
$this->serviceConfigs = $configuration->getServicesFolders();
$this->servicesFormat = $configuration->getServicesFormat();
return $this;
}
/**
* @param ContainerBuilder $containerBuilder
*/
public function into(ContainerBuilder $containerBuilder)
{
$loader = new XmlFileLoader($containerBuilder, new FileLocator($this->serviceConfigs));
$loader->load('services.' . $this->servicesFormat);
}
} |
Use Object.assign for better performance | var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
this.addDependency(this.resourcePath);
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var options = loaderUtils.getOptions(this) || {};
var context = options.context || this.context || this.rootContext;
var emitFile = !options.noEmit;
// Make sure to not modify options object directly
var creatorOptions = Object.assign({}, options);
delete creatorOptions.noEmit;
var creator = new DtsCreator(creatorOptions);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
if (emitFile) {
// Emit the created content as well
this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
}
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
this.addDependency(this.resourcePath);
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var options = loaderUtils.getOptions(this) || {};
var context = options.context || this.context || this.rootContext;
var emitFile = !options.noEmit;
// Make sure to not modify options object directly
var creatorOptions = JSON.parse(JSON.stringify(options));
delete creatorOptions.noEmit;
var creator = new DtsCreator(creatorOptions);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
if (emitFile) {
// Emit the created content as well
this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
}
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
|
Use a shorter timeout when using a range slider | var dimTimer;
angular.module('onmote')
.controller('DeviceListCtrl', function ($scope, $timeout, socket) {
socket.on('telldus:*',function(event, data) {
console.log(event, data);
});
socket.on('telldus:devices', function(data) {
$scope.devices = data;
});
$scope.toggle = function($event, id) {
var checkbox = $event.target;
var command = (checkbox.checked ? 'on' : 'off');
socket.emit('telldus:sendCommand', {
id: id,
command: command
});
};
$scope.dim = function($event, id) {
var that = this;
$timeout.cancel(dimTimer);
dimTimer = $timeout(function() {
socket.emit('telldus:sendCommand', {
id: that.device.id,
command: 'dim',
value: that.device.status.level
});
}, 100);
};
}); | var dimTimer;
angular.module('onmote')
.controller('DeviceListCtrl', function ($scope, $timeout, socket) {
socket.on('telldus:*',function(event, data) {
console.log(event, data);
});
socket.on('telldus:devices', function(data) {
$scope.devices = data;
});
$scope.toggle = function($event, id) {
var checkbox = $event.target;
var command = (checkbox.checked ? 'on' : 'off');
socket.emit('telldus:sendCommand', {
id: id,
command: command
});
};
$scope.dim = function($event, id) {
var that = this;
$timeout.cancel(dimTimer);
dimTimer = $timeout(function() {
socket.emit('telldus:sendCommand', {
id: that.device.id,
command: 'dim',
value: that.device.status.level
});
}, 500);
};
}); |
Make sure entity exist before trying to use it | var index = function(req, res) {
res.writeHead(200);
return res.end();
};
var app = require('http').createServer(index);
var io = require('socket.io')(app);
var _ = require('lodash');
app.listen(3001);
var entities = {};
io.on('connection', function(socket) {
socket.emit('id', { id: socket.id });
_.forEach(entities, function(entity) {
socket.emit('new', entity);
});
socket.on('new', function(data) {
data.id = socket.id;
entities[socket.id] = data;
io.emit('new', data);
});
socket.on('position', function(data) {
if (!entities[socket.id]) return;
entities[socket.id].position = data.position;
io.emit('position', { id: socket.id, position: data.position });
});
socket.on('disconnect', function() {
io.emit('delete', { id: socket.id });
delete entities[socket.id];
});
});
| var index = function(req, res) {
res.writeHead(200);
return res.end();
};
var app = require('http').createServer(index);
var io = require('socket.io')(app);
var _ = require('lodash');
app.listen(3001);
var entities = {};
io.on('connection', function(socket) {
socket.emit('id', { id: socket.id });
_.forEach(entities, function(entity) {
socket.emit('new', entity);
});
socket.on('new', function(data) {
data.id = socket.id;
entities[socket.id] = data;
io.emit('new', data);
});
socket.on('position', function(data) {
entities[socket.id].position = data.position;
io.emit('position', { id: socket.id, position: data.position });
});
socket.on('disconnect', function() {
io.emit('delete', { id: socket.id });
delete entities[socket.id];
});
});
|
Remove replacement of commas by points | import color
def parse(mat_node):
materials = []
for node in mat_node:
materials.append(Material(node))
class Material:
''' it’s a material
'''
def __init__(self, node):
for c in node:
if c.tag == 'ambient':
self.ambient_color = color.parse(c[0])
self.ambient_color *= float(c.attrib['factor'])
elif c.tag == 'diffuse':
self.diffuse_color = color.parse(c[0])
self.diffuse_color *= float(c.attrib['factor'])
elif c.tag == 'specular':
self.specular_color = color.parse(c[0])
self.specular_color *= float(c.attrib['factor'])
elif c.tag == 'reflection':
self.reflection_color = color.parse(c[0])
self.reflection_color *= float(c.attrib['factor'])
| import color
def parse(mat_node):
materials = []
for node in mat_node:
materials.append(Material(node))
class Material:
''' it’s a material
'''
def __init__(self, node):
for c in node:
if c.tag == 'ambient':
self.ambient_color = color.parse(c[0])
self.ambient_color *= float(c.attrib['factor'].replace(',', '.'))
elif c.tag == 'diffuse':
self.diffuse_color = color.parse(c[0])
self.diffuse_color *= float(c.attrib['factor'].replace(',', '.'))
elif c.tag == 'specular':
self.specular_color = color.parse(c[0])
self.specular_color *= float(c.attrib['factor'].replace(',', '.'))
elif c.tag == 'reflection':
self.reflection_color = color.parse(c[0])
self.reflection_color *= float(c.attrib['factor'].replace(',', '.'))
|
Create loadMap function to load map images | function ImageFile(_game) {
this.game = _game;
this.name = new Array();
this.data = new Array();
this.counter = 0;
return this;
};
ImageFile.prototype.load = function(_imageSrc, _width, _height) {
if(!this.getImageDataByName(_imageSrc)) {
var self = this;
var _image = new Image();
_image.src = _imageSrc;
_image.addEventListener('load', function(){self.counter++});
this.name.push(_imageSrc);
this.data.push(_image);
}
var s = new Sprite(_imageSrc, _width, _height);
s.image = this.getImageDataByName(_imageSrc);
this.game.current.scene.sprite.push(s);
return s;
};
ImageFile.prototype.loadMap = function(_imageSrc, _width, _height) {
if(!this.getImageDataByName(_imageSrc)) {
var self = this;
var _image = new Image();
_image.src = _imageSrc;
_image.addEventListener('load', function(){self.counter++});
this.name.push(_imageSrc);
this.data.push(_image);
}
return this.getImageDataByName(_imageSrc);
}
ImageFile.prototype.isLoaded = function() {
if(this.counter === this.data.length) {
return true;
}
return false;
};
ImageFile.prototype.getImageDataByName = function(_imageName) {
return this.data[this.name.indexOf(_imageName)];
}; | function ImageFile(_game) {
this.game = _game;
this.name = new Array();
this.data = new Array();
this.counter = 0;
return this;
};
ImageFile.prototype.load = function(_imageSrc, _width, _height) {
if(!this.getImageDataByName(_imageSrc)) {
var self = this;
var _image = new Image();
_image.src = _imageSrc;
_image.addEventListener('load', function(){self.counter++});
this.name.push(_imageSrc);
this.data.push(_image);
}
var s = new Sprite(_imageSrc, _width, _height);
s.image = this.getImageDataByName(_imageSrc);
this.game.current.scene.sprite.push(s);
return s;
};
ImageFile.prototype.isLoaded = function() {
if(this.counter === this.data.length) {
return true;
}
return false;
};
ImageFile.prototype.getImageDataByName = function(_imageName) {
return this.data[this.name.indexOf(_imageName)];
}; |
Fix External and Faces contexts scopes | package org.gluu.jsf2.service;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.faces.application.ViewHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
/**
* @author Yuriy Movchan
* @version 03/17/2017
*/
public class FacesResources {
@Produces
@RequestScoped
public FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
@Produces
@RequestScoped
public ExternalContext getExternalContext() {
FacesContext facesContext = getFacesContext();
if (facesContext != null) {
return facesContext.getExternalContext();
}
return null;
}
@Produces
@Dependent
public ViewHandler getViewHandler() {
FacesContext facesContext = getFacesContext();
if (facesContext != null) {
return facesContext.getApplication().getViewHandler();
}
return null;
}
}
| package org.gluu.jsf2.service;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.faces.application.ViewHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
/**
* @author Yuriy Movchan
* @version 03/17/2017
*/
public class FacesResources {
@Produces
@Dependent
public FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
@Produces
@Dependent
public ExternalContext getExternalContext() {
FacesContext facesContext = getFacesContext();
if (facesContext != null) {
return facesContext.getExternalContext();
}
return null;
}
@Produces
@Dependent
public ViewHandler getViewHandler() {
FacesContext facesContext = getFacesContext();
if (facesContext != null) {
return facesContext.getApplication().getViewHandler();
}
return null;
}
}
|
Drop TODO for getVmVersion method
Review URL: https://codereview.chromium.org/12324002 | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.io.IOException;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* Abstraction of a remote JavaScript virtual machine which is embedded into
* some application and accessed via TCP/IP connection to a port opened by
* DebuggerAgent. Clients can use it to conduct debugging process.
*/
public interface StandaloneVm extends JavascriptVm {
/**
* Connects to the target VM.
*
* @param listener to report the debug events to
* @throws IOException if there was a transport layer error
* @throws UnsupportedVersionException if the SDK protocol version is not
* compatible with that supported by the browser
* @throws MethodIsBlockingException because initialization implies couple of remote calls
* (to request version etc)
*/
void attach(DebugEventListener listener)
throws IOException, UnsupportedVersionException, MethodIsBlockingException;
/**
* @return name of embedding application as it wished to name itself; might be null
*/
String getEmbedderName();
/**
* This version should correspond to {@link JavascriptVm#getVersion()}. However it gets available
* earlier, at the transport handshake stage.
* @return version of V8 implementation, format is unspecified; must not be null if
* {@link StandaloneVm} has been attached
*/
String getVmVersion();
/**
* @return message explaining why VM is detached; may be null
*/
String getDisconnectReason();
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.io.IOException;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* Abstraction of a remote JavaScript virtual machine which is embedded into
* some application and accessed via TCP/IP connection to a port opened by
* DebuggerAgent. Clients can use it to conduct debugging process.
*/
public interface StandaloneVm extends JavascriptVm {
/**
* Connects to the target VM.
*
* @param listener to report the debug events to
* @throws IOException if there was a transport layer error
* @throws UnsupportedVersionException if the SDK protocol version is not
* compatible with that supported by the browser
* @throws MethodIsBlockingException because initialization implies couple of remote calls
* (to request version etc)
*/
void attach(DebugEventListener listener)
throws IOException, UnsupportedVersionException, MethodIsBlockingException;
/**
* @return name of embedding application as it wished to name itself; might be null
*/
String getEmbedderName();
/**
* @return version of V8 implementation, format is unspecified; must not be null if
* {@link StandaloneVm} has been attached
*/
// TODO: align this with {@link JavascriptVm#getVersion()} method.
String getVmVersion();
/**
* @return message explaining why VM is detached; may be null
*/
String getDisconnectReason();
}
|
Set card to 'disabled' if player isn't 'active' | export default class CardController {
constructor($rootScope, $scope, $log, _, playerModel, cardsApi) {
'ngInject';
this.$rootScope = $rootScope;
this.$scope = $scope;
this.$log = $log;
this._ = _;
this.cardsApi = cardsApi;
this.playerModel = playerModel.model;
this.$log.info('constructor()', this);
}
$onInit() {
let onSuccess = (res => {
this.$log.info('onSuccess()', res, this);
if (res.status === 200) {
this.$scope.cardData = res.data[0];
}
}),
onError = (err => {
this.$log.error(err);
});
this.$log.info('$onInit()', this);
this.$scope.cardData = {};
this.$scope.isDisabled = !this.cardId || this.cardType === 'storage' || !this.player.isActive;
if (this.cardId) {
this.cardsApi
.get(this.cardId)
.then(onSuccess, onError);
}
}
$onDestroy() {
return () => {
this.$log.info('$onDestroy()', this);
};
}
onClick($e) {
this.$log.info('onClick()', this);
$e.preventDefault();
}
};
| export default class CardController {
constructor($rootScope, $scope, $log, _, playerModel, cardsApi) {
'ngInject';
this.$rootScope = $rootScope;
this.$scope = $scope;
this.$log = $log;
this._ = _;
this.cardsApi = cardsApi;
this.playerModel = playerModel.model;
this.$log.info('constructor()', this);
}
$onInit() {
let onSuccess = (res => {
this.$log.info('onSuccess()', res, this);
if (res.status === 200) {
this.$scope.cardData = res.data[0];
}
}),
onError = (err => {
this.$log.error(err);
});
this.$log.info('$onInit()', this);
this.$scope.cardData = {};
this.$scope.isDisabled = !this.cardId || this.cardType === 'storage';
if (this.cardId) {
this.cardsApi
.get(this.cardId)
.then(onSuccess, onError);
}
}
$onDestroy() {
return () => {
this.$log.info('$onDestroy()', this);
};
}
onClick($e) {
this.$log.info('onClick()', this);
$e.preventDefault();
}
};
|
Correct clearing of fanart cache | import os,mc
import xbmc, xbmcgui
def fanart_function():
if mc.ShowDialogConfirm("Clear fanart cache", "Are you sure you want to clear the fanart cache?", "Cancel", "OK"):
pass
def thumbnail_function():
if mc.ShowDialogConfirm("Clear thumbnail cache", "Are you sure you want to clear the thumbnail cache?", "Cancel", "OK"):
os.system("rm %s" % xbmc.translatePath('special://profile/.fanart'))
os.system("find /data/.boxee/UserData/profiles/*/Thumbnails/ -name \*.tbn | xargs rm")
mc.ShowDialogNotification("Clearing thumbnail cache")
if (__name__ == "__main__"):
section = sys.argv[1]
if section == "fanart":
fanart_function()
if section == "thumbnail":
thumbnail_function()
| import os,mc
import xbmc, xbmcgui
def fanart_function():
if mc.ShowDialogConfirm("Clear fanart cache", "Are you sure you want to clear the fanart cache?", "Cancel", "OK"):
pass
def thumbnail_function():
if mc.ShowDialogConfirm("Clear thumbnail cache", "Are you sure you want to clear the thumbnail cache?", "Cancel", "OK"):
os.system("rm /data/etc/.fanart")
os.system("find /data/.boxee/UserData/profiles/*/Thumbnails/ -name \*.tbn | xargs rm")
mc.ShowDialogNotification("Clearing thumbnail cache")
if (__name__ == "__main__"):
section = sys.argv[1]
if section == "fanart":
fanart_function()
if section == "thumbnail":
thumbnail_function()
|
Add core-js polyfill for Promise.finally() | // ECMAScript polyfills
import 'core-js/fn/array/fill';
import 'core-js/fn/array/find';
import 'core-js/fn/array/find-index';
import 'core-js/fn/array/from';
import 'core-js/fn/array/includes';
import 'core-js/fn/object/assign';
import 'core-js/fn/object/values';
import 'core-js/fn/promise';
import 'core-js/fn/promise/finally';
import 'core-js/fn/string/code-point-at';
import 'core-js/fn/string/from-code-point';
import 'core-js/fn/string/includes';
import 'core-js/fn/symbol';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
// Browser polyfills
import 'formdata-polyfill';
import './polyfills/custom_event';
import './polyfills/element';
import './polyfills/event';
import './polyfills/nodelist';
import './polyfills/request_idle_callback';
import './polyfills/svg';
| // ECMAScript polyfills
import 'core-js/fn/array/fill';
import 'core-js/fn/array/find';
import 'core-js/fn/array/find-index';
import 'core-js/fn/array/from';
import 'core-js/fn/array/includes';
import 'core-js/fn/object/assign';
import 'core-js/fn/object/values';
import 'core-js/fn/promise';
import 'core-js/fn/string/code-point-at';
import 'core-js/fn/string/from-code-point';
import 'core-js/fn/string/includes';
import 'core-js/fn/symbol';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
// Browser polyfills
import 'formdata-polyfill';
import './polyfills/custom_event';
import './polyfills/element';
import './polyfills/event';
import './polyfills/nodelist';
import './polyfills/request_idle_callback';
import './polyfills/svg';
|
Add 'type' support and use Promise with convert method. | "use strict"
var Converter = module.exports = (function() {
var keyMap = {
createdAt: 'parseCreateAt'
, updatedAt: 'parseUpdateAt'
, objectId: 'parseObjectId'
};
function Converter(ncmb, type) {
this.__proto__.ncmb = ncmb;
this._type = type;
}
Converter.prototype.convert = function(obj) {
switch (this._type) {
case 'installation':
return this.convInstallation(obj);
break;
default:
return this.convObject(obj);
break;
}
};
Converter.prototype.convInstallation = function(obj) {
let map = keyMap;
// add key depends on installations
map['appName'] = 'applicationName';
let NCMBInstallationEx = require('./installation_ex');
let installation = new NCMBInstallationEx(this.ncmb);
let attrs = {};
Object.keys(obj).forEach(function(key) {
if (map[key] == undefined) {
attrs[key] = obj[key];
} else {
attrs[map[key]] = obj[key];
}
});
return new Promise(function(resolve, reject) {
installation
.register(attrs)
.then(function() {
resolve();
})
.catch(function(err) {
reject(err);
});
});
}
Converter.prototype.convObject = function(obj) {
return new Promise(function(resolve, reject) {
resolve();
});
}
return Converter;
})();
| "use strict"
var Converter = module.exports = (function() {
function Converter(ncmb, type) {
this.__proto__.ncmb = ncmb;
this._type = type;
}
Converter.prototype.convert = function(obj) {
let map = {
appName: 'applicationName'
, createdAt: 'parseCreateAt'
, updatedAt: 'parseUpdateAt'
, objectId: 'parseObjectId'
};
let NCMBInstallationEx = require('./installation_ex');
let installation = new NCMBInstallationEx(this.ncmb);
let attrs = {};
Object.keys(obj).forEach(function(key) {
if (map[key] == undefined) {
attrs[key] = obj[key];
} else {
attrs[map[key]] = obj[key];
}
});
installation.register(attrs)
.catch(function(err) {
console.log(err);
});
}
return Converter;
})();
|
Change main route to get session user | 'use strict';
var path = process.cwd();
var Graphriend = require(path + '/app/controllers/Graphriend.server.js');
var sess;
module.exports = function (app) {
function isLoggedIn (req, res, next) {
sess = req.session;
if (sess.user || req.url === '/') {
return next();
} else {
res.redirect('/');
}
}
var graPhriend = new Graphriend();
var user = {
isLogged: false,
name: 'Jinme',
username: 'mirabalj'
}
app.route('/')
.get(isLoggedIn, function (req, res) {
res.render('main', { user: sess.user, page: 'index' });
});
app.post('/api/signup', graPhriend.signUp);
app.post('/api/login', graPhriend.logIn);
/* Example Authenticated verify
app.route('/profile')
.get(isLoggedIn, function (req, res) {
res.render('main', { user: sess.user, page: 'profile' });
});
*/
/* Example REST api
app.route('/friends')
.get(isLoggedIn, graPhriend.getFriend)
.post(isLoggedIn, graPhriend.addFriend)
.delete(isLoggedIn, graPhriend.delFriend);
*/
};
| 'use strict';
var path = process.cwd();
var Graphriend = require(path + '/app/controllers/Graphriend.server.js');
var sess;
module.exports = function (app) {
function isLoggedIn (req, res, next) {
sess = req.session;
if (sess.user) {
return next();
} else {
res.redirect('/');
}
}
var graPhriend = new Graphriend();
var user = {
isLogged: false,
name: 'Jinme',
username: 'mirabalj'
}
app.route('/')
.get(function (req, res) {
res.render('main', { user: user, page: 'index' });
});
app.post('/api/signup', graPhriend.signUp);
app.post('/api/login', graPhriend.logIn);
/* Example Authenticated verify
app.route('/profile')
.get(isLoggedIn, function (req, res) {
res.render('main', { user: sess.user, page: 'profile' });
});
*/
/* Example REST api
app.route('/friends')
.get(isLoggedIn, graPhriend.getFriend)
.post(isLoggedIn, graPhriend.addFriend)
.delete(isLoggedIn, graPhriend.delFriend);
*/
};
|
Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification | import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsig.requests_auth import HTTPSignatureAuth
import requests
from keybar.models.user import User
# TODO: Use a secret RSA key as secret.
secret = open('extras/example_keys/private_key.pem', 'rb').read()
user = User.objects.get(username='admin')
signature_headers = ['(request-target)', 'accept', 'date', 'host']
now = datetime.now()
stamp = mktime(now.timetuple())
headers = {
'Host': 'keybar.local:8443',
'Method': 'GET',
'Path': '/api/v1/users/',
'Accept': 'application/json',
'X-Api-Key': user.api_key.hex,
'Date': formatdate(timeval=stamp, localtime=False, usegmt=True)
}
auth = HTTPSignatureAuth(
key_id=user.api_key.hex,
secret=secret,
headers=signature_headers,
algorithm='rsa-sha256')
response = requests.get(
'https://keybar.local:8443/api/v1/users/',
auth=auth,
headers=headers,
verify=settings.KEYBAR_CA_BUNDLE)
print(response.content)
| import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsig.requests_auth import HTTPSignatureAuth
import requests
from keybar.models.user import User
# TODO: Use a secret RSA key as secret.
secret = open('example_keys/private_key.pem', 'rb').read()
user = User.objects.get(username='admin')
signature_headers = ['(request-target)', 'accept', 'date', 'host']
now = datetime.now()
stamp = mktime(now.timetuple())
headers = {
'Host': 'keybar.local:8443',
'Method': 'GET',
'Path': '/api/v1/users/',
'Accept': 'application/json',
'X-Api-Key': user.api_key.hex,
'Date': formatdate(timeval=stamp, localtime=False, usegmt=True)
}
auth = HTTPSignatureAuth(
key_id=user.api_key.hex,
secret=secret,
headers=signature_headers,
algorithm='hmac-sha256')
response = requests.get(
'https://keybar.local:8443/api/v1/users/',
auth=auth,
headers=headers,
verify=settings.KEYBAR_CA_BUNDLE)
print(response.content)
|
Set backend to production backend | import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {setConfiguration} from './src/utils/configuration';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';
const Hemmo = React.createClass({
componentWillMount() {
BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
setConfiguration('API_ROOT', 'http://hemmo.pelastakaalapset.fi');
// setConfiguration('API_ROOT', 'http://localhost:3001');
},
navigateBack() {
const navigationState = store.getState().get('navigationState');
if (navigationState.get('index') === 0) {
return false;
}
/* Check if returning from current page is allowed */
var currentPageIndex = navigationState.get('index');
var allowReturn = navigationState.getIn(['children', currentPageIndex, 'allowReturn']);
if (allowReturn === false) {
return true;
}
store.dispatch(NavigationStateActions.popRoute());
return true;
},
render() {
return (
<Provider store={store}>
<AppViewContainer />
</Provider>
);
}
});
AppRegistry.registerComponent('Hemmo', () => Hemmo);
| import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {setConfiguration} from './src/utils/configuration';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';
const Hemmo = React.createClass({
componentWillMount() {
BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
setConfiguration('API_ROOT', 'http://hemmo-backend.herokuapp.com');
// setConfiguration('API_ROOT', 'http://localhost:3001');
},
navigateBack() {
const navigationState = store.getState().get('navigationState');
if (navigationState.get('index') === 0) {
return false;
}
/* Check if returning from current page is allowed */
var currentPageIndex = navigationState.get('index');
var allowReturn = navigationState.getIn(['children', currentPageIndex, 'allowReturn']);
if (allowReturn === false) {
return true;
}
store.dispatch(NavigationStateActions.popRoute());
return true;
},
render() {
return (
<Provider store={store}>
<AppViewContainer />
</Provider>
);
}
});
AppRegistry.registerComponent('Hemmo', () => Hemmo);
|
Fix headless unit test running
Now "npm install && npm test" works locally again. | /*
Copyright 2014 Spotify AB
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.
*/
/* global require */
var gulp = require('gulp');
var qunit = require('gulp-qunit');
var jshint = require('gulp-jshint');
var htmlhint = require("gulp-htmlhint");
var csslint = require("gulp-csslint");
gulp.task('test', function() {
return gulp.src('file://test.html').pipe(qunit());
});
gulp.task('jslint', function() {
return gulp.src('*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('htmllint', function() {
return gulp.src(["*.html", "!test.html"])
.pipe(htmlhint())
.pipe(htmlhint.reporter())
.pipe(htmlhint.failReporter());
});
gulp.task('csslint', function() {
gulp.src('*.css')
.pipe(csslint())
.pipe(csslint.reporter())
.pipe(csslint.failReporter());
});
| /*
Copyright 2014 Spotify AB
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.
*/
/* global require */
var gulp = require('gulp');
var qunit = require('gulp-qunit');
var jshint = require('gulp-jshint');
var htmlhint = require("gulp-htmlhint");
var csslint = require("gulp-csslint");
gulp.task('test', function() {
return gulp.src('./test.html').pipe(qunit());
});
gulp.task('jslint', function() {
return gulp.src('*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('htmllint', function() {
return gulp.src(["*.html", "!test.html"])
.pipe(htmlhint())
.pipe(htmlhint.reporter())
.pipe(htmlhint.failReporter());
});
gulp.task('csslint', function() {
gulp.src('*.css')
.pipe(csslint())
.pipe(csslint.reporter())
.pipe(csslint.failReporter());
});
|
Write name and version to output file. | from __future__ import unicode_literals
import pyaavso
class VisualFormatWriter(object):
"""
A class responsible for writing observation data in AAVSO
`Visual File Format`_.
The API here mimics the ``csv`` module in Python standard library.
.. _`Visual File Format`: http://www.aavso.org/aavso-visual-file-format
"""
def __init__(self, fp, observer_code, delimiter=',', date_format='JD', obstype='Visual'):
"""
Creates the writer which will write observations into the file-like
object given in first parameter. The only other required parameter
is the official AAVSO-assigned observer code.
"""
self.observer_code = observer_code
self.date_format = date_format
self.obstype = obstype
fp.write('#TYPE=Visual\n')
fp.write('#OBSCODE=%s\n' % observer_code)
fp.write("#SOFTWARE=pyaavso %s\n" % pyaavso.get_version())
| from __future__ import unicode_literals
class VisualFormatWriter(object):
"""
A class responsible for writing observation data in AAVSO
`Visual File Format`_.
The API here mimics the ``csv`` module in Python standard library.
.. _`Visual File Format`: http://www.aavso.org/aavso-visual-file-format
"""
def __init__(self, fp, observer_code, delimiter=',', date_format='JD', obstype='Visual'):
"""
Creates the writer which will write observations into the file-like
object given in first parameter. The only other required parameter
is the official AAVSO-assigned observer code.
"""
self.observer_code = observer_code
self.date_format = date_format
self.obstype = obstype
fp.write('#TYPE=Visual\n')
fp.write('#OBSCODE=%s\n' % observer_code)
|
Generalize service module plugin loader, in preparation for same loading mechanism for language specification Module plugins. | package org.metaborg.core.plugin;
import java.util.Collection;
import java.util.ServiceLoader;
import org.metaborg.core.MetaborgException;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Module;
/**
* Module plugin loader using Java's {@link ServiceLoader}.
*/
public class ServiceModulePluginLoader<T extends IServiceModulePlugin> implements IModulePluginLoader {
private final Class<T> serviceClass;
public ServiceModulePluginLoader(Class<T> serviceClass) {
this.serviceClass = serviceClass;
}
@Override public Iterable<Module> modules() throws MetaborgException {
try {
final ServiceLoader<T> modulePlugins = ServiceLoader.load(serviceClass);
final Collection<Module> modules = Lists.newLinkedList();
for(T plugin : modulePlugins) {
Iterables.addAll(modules, plugin.modules());
}
return modules;
} catch(Exception e) {
throw new MetaborgException("Unhandled exception while loading module plugins with Java's ServiceLoader", e);
}
}
}
| package org.metaborg.core.plugin;
import java.util.Collection;
import java.util.ServiceLoader;
import org.metaborg.core.MetaborgException;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Module;
/**
* Module plugin loader using Java's {@link ServiceLoader}.
*/
public class ServiceModulePluginLoader implements IModulePluginLoader {
@Override public Iterable<Module> modules() throws MetaborgException {
try {
final ServiceLoader<IServiceModulePlugin> modulePlugins = ServiceLoader.load(IServiceModulePlugin.class);
final Collection<Module> modules = Lists.newLinkedList();
for(IServiceModulePlugin plugin : modulePlugins) {
Iterables.addAll(modules, plugin.modules());
}
return modules;
} catch(Exception e) {
throw new MetaborgException("Unhandled exception while loading module plugins with Java's ServiceLoader", e);
}
}
}
|
Use reify instead of properties for the task backend connections. | from celery import Celery, Task
from classtools import reify
from redis import StrictRedis
from charat2.model import sm
from charat2.model.connections import redis_pool
celery = Celery("newparp", include=[
"charat2.tasks.background",
"charat2.tasks.matchmaker",
"charat2.tasks.reaper",
"charat2.tasks.roulette_matchmaker",
])
celery.config_from_object('charat2.tasks.config')
class WorkerTask(Task):
abstrct = True
@reify
def db(self):
return sm()
@reify
def redis(self):
return StrictRedis(connection_pool=redis_pool)
def after_return(self, *args, **kwargs):
if hasattr(self, "db"):
self.db.close()
del self.db
if hasattr(self, "redis"):
del self.redis
| from celery import Celery, Task
from redis import StrictRedis
from charat2.model import sm
from charat2.model.connections import redis_pool
celery = Celery("newparp", include=[
"charat2.tasks.background",
"charat2.tasks.matchmaker",
"charat2.tasks.reaper",
"charat2.tasks.roulette_matchmaker",
])
celery.config_from_object('charat2.tasks.config')
class WorkerTask(Task):
abstrct = True
_db = None
_redis = None
@property
def db(self):
if self._db is None:
self._db = sm()
return self._db
@property
def redis(self):
if self._redis is None:
self._redis = StrictRedis(connection_pool=redis_pool)
return self._redis
|
Add a method to get savedata from the world quit easy | package info.u_team.u_team_core.util.world;
import java.util.function.Function;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.*;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.storage.WorldSavedData;
public class WorldUtil {
public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range) {
return rayTraceServerSide(player, range, RayTraceFluidMode.NEVER, false, true);
}
public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range, RayTraceFluidMode liquidMode, boolean ignoreBlockWithoutBoundingBox, boolean returnLastUncollidableBlock) {
Vec3d playerVector = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ);
Vec3d lookVector = player.getLookVec();
Vec3d locationVector = playerVector.add(lookVector.x * range, lookVector.y * range, lookVector.z * range);
return player.world.rayTraceBlocks(playerVector, locationVector, liquidMode, ignoreBlockWithoutBoundingBox, returnLastUncollidableBlock);
}
public static <T extends WorldSavedData> T getSaveData(World world, String name, Function<String, T> function) {
final DimensionType type = world.getDimension().getType();
T instance = world.getSavedData(type, function, name);
if (instance == null) {
instance = function.apply(name);
world.setSavedData(type, name, instance);
}
return instance;
}
}
| package info.u_team.u_team_core.util.world;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.*;
public class WorldUtil {
public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range) {
return rayTraceServerSide(player, range, RayTraceFluidMode.NEVER, false, true);
}
public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range, RayTraceFluidMode liquidMode, boolean ignoreBlockWithoutBoundingBox, boolean returnLastUncollidableBlock) {
Vec3d playerVector = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ);
Vec3d lookVector = player.getLookVec();
Vec3d locationVector = playerVector.add(lookVector.x * range, lookVector.y * range, lookVector.z * range);
return player.world.rayTraceBlocks(playerVector, locationVector, liquidMode, ignoreBlockWithoutBoundingBox, returnLastUncollidableBlock);
}
}
|
Use a placeholder string instead of a README.
Until I work out why README.rst isn't being included, use this. | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.6",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
packages=setuptools.find_packages(),
package_data={
"dudebot": ["README.rst"]
},
scripts=[],
url="https://github.com/sujaymansingh/dudebot",
license="LICENSE.txt",
description="A really simple framework for chatroom bots",
long_description="View the github page (https://github.com/sujaymansingh/dudebot) for more details.",
install_requires=REQUIREMENTS
)
| import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.6",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
packages=setuptools.find_packages(),
package_data={
"dudebot": ["README.rst"]
},
scripts=[],
url="https://github.com/sujaymansingh/dudebot",
license="LICENSE.txt",
description="A really simple framework for chatroom bots",
long_description=open("README.rst").read(),
install_requires=REQUIREMENTS
)
|
Fix: Scale XYZ matrix generator didn't use 1.0 as the default
component value, as it obviously should. | E2.p = E2.plugins["scale_xyz_matrix"] = function(core, node)
{
this.desc = 'Create a matrix that scales the X, Y and Z axis.';
this.input_slots = [
{ name: 'x', dt: core.datatypes.FLOAT, desc: 'Amount to scale the X-axis.', def: 1.0 },
{ name: 'y', dt: core.datatypes.FLOAT, desc: 'Amount to scale the Y-axis.', def: 1.0 },
{ name: 'z', dt: core.datatypes.FLOAT, desc: 'Amount to scale the Z-axis.', def: 1.0 }
];
this.output_slots = [
{ name: 'matrix', dt: core.datatypes.MATRIX, desc: 'The resulting scale matrix.', def: core.renderer.matrix_identity }
];
};
E2.p.prototype.reset = function()
{
this.factors = vec3.createFrom(1.0, 1.0, 1.0);
this.matrix = mat4.create();
mat4.identity(this.matrix);
};
E2.p.prototype.update_input = function(slot, data)
{
this.factors[slot.index] = data;
};
E2.p.prototype.update_state = function()
{
mat4.identity(this.matrix);
mat4.scale(this.matrix, this.factors);
};
E2.p.prototype.update_output = function(slot)
{
return this.matrix;
};
| E2.p = E2.plugins["scale_xyz_matrix"] = function(core, node)
{
this.desc = 'Create a matrix that scales the X, Y and Z axis.';
this.input_slots = [
{ name: 'x', dt: core.datatypes.FLOAT, desc: 'Amount to scale the X-axis.', def: 1 },
{ name: 'y', dt: core.datatypes.FLOAT, desc: 'Amount to scale the Y-axis.', def: 1 },
{ name: 'z', dt: core.datatypes.FLOAT, desc: 'Amount to scale the Z-axis.', def: 1 }
];
this.output_slots = [
{ name: 'matrix', dt: core.datatypes.MATRIX, desc: 'The resulting scale matrix.', def: core.renderer.matrix_identity }
];
};
E2.p.prototype.reset = function()
{
this.factors = vec3.create();
this.matrix = mat4.create();
mat4.identity(this.matrix);
};
E2.p.prototype.update_input = function(slot, data)
{
this.factors[slot.index] = data;
};
E2.p.prototype.update_state = function()
{
mat4.identity(this.matrix);
mat4.scale(this.matrix, this.factors);
};
E2.p.prototype.update_output = function(slot)
{
return this.matrix;
};
|
Change to use short flag for 2.4 | #!/usr/bin/env python
import os
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
def test_for_version(filename):
stdin, stdout = os.popen4('%s -V' % filename, 'r')
response = stdout.read()
return '.'.join(response.strip().split(' ')[1].split('.')[:-1])
versions = ['python', 'python2.4', 'python2.5', 'python2.6']
valid = {}
for filename in versions:
version = test_for_version(filename)
if version not in valid:
valid[version] = filename
# Prefer the latest version of python
output = []
if '2.6' in valid:
output.append(valid['2.6'])
for version in valid.keys():
if valid[version] not in output:
output.append(valid[version])
print ' '.join(output)
| #!/usr/bin/env python
import os
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
def test_for_version(filename):
stdin, stdout = os.popen4('%s --version' % filename, 'r')
response = stdout.read()
return '.'.join(response.strip().split(' ')[1].split('.')[:-1])
versions = ['python', 'python2.4', 'python2.5', 'python2.6']
valid = {}
for filename in versions:
version = test_for_version(filename)
if version not in valid:
valid[version] = filename
# Prefer the latest version of python
output = []
if '2.6' in valid:
output.append(valid['2.6'])
for version in valid.keys():
if valid[version] not in output:
output.append(valid[version])
print ' '.join(output)
|
Use argparse for 4D to 3D | #!/usr/bin/env python
''' Tiny script to write 4D files in any format that we read (nifti,
analyze, MINC, at the moment, as nifti 3D files '''
import os
import nipy.externals.argparse as argparse
import nipy.io.imageformats as nii
def main():
# create the parser
parser = argparse.ArgumentParser()
# add the arguments
parser.add_argument('filename', type=str,
help='4D image filename')
# parse the command line
args = parser.parse_args()
img = nii.load(args.filename)
imgs = nii.four_to_three(img)
froot, ext = os.path.splitext(args.filename)
if ext in ('.gz', '.bz2'):
froot, ext = os.path.splitext(froot)
for i, img3d in enumerate(imgs):
fname3d = '%s_%04d.nii' % (froot, i)
nii.save(img3d, fname3d)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
''' Tiny script to write 4D files in any format that we read (nifti,
analyze, MINC, at the moment, as nifti 3D files '''
import os
import sys
import nipy.io.imageformats as nii
if __name__ == '__main__':
try:
fname = sys.argv[1]
except IndexError:
raise OSError('Expecting 4d image filename')
img = nii.load(fname)
imgs = nii.four_to_three(img)
froot, ext = os.path.splitext(fname)
if ext in ('.gz', '.bz2'):
froot, ext = os.path.splitext(froot)
for i, img3d in enumerate(imgs):
fname3d = '%s_%04d.nii' % (froot, i)
nii.save(img3d, fname3d)
|
Use SIO:is_data _item in rather than void:inDataset | package ws.biotea.ld2rdf.rdf.model;
import ws.biotea.ld2rdf.util.OntologyPrefix;
import java.io.Serializable;
/**
* OpenAnnotation: This class represents a general annotation on a Document.
* @author leylajael
*/
public class BaseAnnotation implements Serializable {
private static final long serialVersionUID = 1L;
/* OWL Descriptors */
public final static String ANNOTATION_DP_LABEL = OntologyPrefix.RDFS.getURL() + "label";
public final static String RDFS_COMMENT = OntologyPrefix.RDFS.getURL() + "comment";
public final static String BIOTEA_OCURRENCES = OntologyPrefix.BIOTEA.getURL() + "tf";
public final static String BIOTEA_IDF = OntologyPrefix.BIOTEA.getURL() + "idf";
public final static String RDFS_SEE_ALSO = OntologyPrefix.RDFS.getURL() + "seeAlso";
public final static String OWL_SAME_AS = OntologyPrefix.OWL.getURL() + "sameAs";
public final static String DC_IS_REFERENCED_BY = OntologyPrefix.DCTERMS.getURL() + "isReferencedBy";
public final static String SIO_IN_DATASET = OntologyPrefix.SIO.getURL() + "001278";
public final static String DP_SCORE = OntologyPrefix.BIOTEA.getURL() + "score";
}
| package ws.biotea.ld2rdf.rdf.model;
import ws.biotea.ld2rdf.util.OntologyPrefix;
import java.io.Serializable;
/**
* OpenAnnotation: This class represents a general annotation on a Document.
* @author leylajael
*/
public class BaseAnnotation implements Serializable {
private static final long serialVersionUID = 1L;
/* OWL Descriptors */
public final static String ANNOTATION_DP_LABEL = OntologyPrefix.RDFS.getURL() + "label";
public final static String RDFS_COMMENT = OntologyPrefix.RDFS.getURL() + "comment";
public final static String BIOTEA_OCURRENCES = OntologyPrefix.BIOTEA.getURL() + "tf";
public final static String BIOTEA_IDF = OntologyPrefix.BIOTEA.getURL() + "idf";
public final static String RDFS_SEE_ALSO = OntologyPrefix.RDFS.getURL() + "seeAlso";
public final static String OWL_SAME_AS = OntologyPrefix.OWL.getURL() + "sameAs";
public final static String DC_IS_REFERENCED_BY = OntologyPrefix.DCTERMS.getURL() + "isReferencedBy";
public final static String VOID_IN_DATASET = OntologyPrefix.VOID.getURL() + "inDataset";
public final static String DP_SCORE = OntologyPrefix.BIOTEA.getURL() + "score";
}
|
Fix bug with JSONPointer if part passed via __truediv__ is integer | """
Extended JSONPointer from python-json-pointer_
==============================================
.. _python-json-pointer: https://github.com/stefankoegl/python-json-pointer
"""
import typing
from jsonpointer import JsonPointer as BaseJsonPointer
class JSONPointer(BaseJsonPointer):
def __init__(self, pointer):
super(JSONPointer, self).__init__(pointer)
def __truediv__(self,
path: typing.Union['JSONPointer', str]) -> 'JSONPointer':
parts = self.parts.copy()
if isinstance(path, int):
path = str(path)
if isinstance(path, str):
if not path.startswith('/'):
path = f'/{path}'
new_parts = JSONPointer(path).parts.pop(0)
parts.append(new_parts)
else:
new_parts = path.parts
parts.extend(new_parts)
return JSONPointer.from_parts(parts)
| """
Extended JSONPointer from python-json-pointer_
==============================================
.. _python-json-pointer: https://github.com/stefankoegl/python-json-pointer
"""
import typing
from jsonpointer import JsonPointer as BaseJsonPointer
class JSONPointer(BaseJsonPointer):
def __init__(self, pointer):
super(JSONPointer, self).__init__(pointer)
def __truediv__(self,
path: typing.Union['JSONPointer', str]) -> 'JSONPointer':
parts = self.parts.copy()
if isinstance(path, str):
if not path.startswith('/'):
path = f'/{path}'
new_parts = JSONPointer(path).parts.pop(0)
parts.append(new_parts)
else:
new_parts = path.parts
parts.extend(new_parts)
return JSONPointer.from_parts(parts)
|
Define charset at start as well | <?php
/**
* This file is part of the Krystal Framework
*
* Copyright (c) No Global State Lab
*
* For the full copyright and license information, please view
* the license file that was distributed with this source code.
*/
namespace Krystal\Db\Sql\Connector;
use PDO;
final class MySQL implements ConnectorInterface
{
/**
* {@inheritDoc}
*/
public function getArgs(array $config)
{
$dsn = 'mysql:host='.$config['host'];
if (isset($config['dbname'])) {
$dsn .= ';dbname='.$config['dbname'];
}
$dsn .= ';charset=utf8';
return array($dsn, $config['username'], $config['password'], array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
// Disable STRICT mode
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION", NAMES utf8'
));
}
}
| <?php
/**
* This file is part of the Krystal Framework
*
* Copyright (c) No Global State Lab
*
* For the full copyright and license information, please view
* the license file that was distributed with this source code.
*/
namespace Krystal\Db\Sql\Connector;
use PDO;
final class MySQL implements ConnectorInterface
{
/**
* {@inheritDoc}
*/
public function getArgs(array $config)
{
$dsn = 'mysql:host='.$config['host'];
if (isset($config['dbname'])) {
$dsn .= ';dbname='.$config['dbname'];
}
$dsn .= ';charset=utf8';
return array($dsn, $config['username'], $config['password'], array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
// Disable STRICT mode
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"'
));
}
}
|
test: Update test after adding cleaning of dist | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
mock_run.call_args_list,
[
mock.call('rm -rf build dist'),
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.call('rm -rf build dist')
]
)
| from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
mock_run.call_args_list,
[
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.call('rm -rf build dist')
]
)
|
Improve javadoc of temporary allowed application status | package org.synyx.urlaubsverwaltung.application.domain;
/**
* Enum describing which states an {@link Application} may have.
*/
public enum ApplicationStatus {
/**
* After applying for the leave, the saved application for leave gets this status.
*/
WAITING,
/**
* After the department head has allowed the application in a two stage approval process and before the
* second stage authority has rejected or allowed the application.
* This status is a special case of WAITING and needs to be handled as a waiting, not yet allowed, application for leave.
*
* @since 2.15.0
*/
TEMPORARY_ALLOWED,
/**
* Status after a boss has allowed the application for leave or after HeadOf has allowed the application in a one
* stage approval process or after a SECOND_STAGE_AUTHORITY (Role) has released a TEMPORARY_ALLOWED application.
*/
ALLOWED,
/**
* Status after the application for leave was allowed but the applicant wants to cancel the own application.
* The application for leave is at this point not cancelled and can only be approved by OFFICE Role.
*/
ALLOWED_CANCELLATION_REQUESTED,
/**
* Status after a boss has rejected application for leave.
*/
REJECTED,
/**
* If an application for leave has been allowed and is cancelled afterwards, it gets this status.
*/
CANCELLED,
/**
* If an application for leave has **not** been allowed yet and is cancelled, it gets this status.
*
* @since 2.5.2
*/
REVOKED
}
| package org.synyx.urlaubsverwaltung.application.domain;
/**
* Enum describing which states an {@link Application} may have.
*/
public enum ApplicationStatus {
/**
* After applying for the leave, the saved application for leave gets this status.
*/
WAITING,
/**
* After the HeadOf has allowed the application in a two stage approval process.
*
* @since 2.15.0
*/
TEMPORARY_ALLOWED,
/**
* Status after a boss has allowed the application for leave or after HeadOf has allowed the application in a one
* stage approval process or after a SECOND_STAGE_AUTHORITY (Role) has released a TEMPORARY_ALLOWED application.
*/
ALLOWED,
/**
* Status after the application for leave was allowed but the applicant wants to cancel the own application.
* The application for leave is at this point not cancelled and can only be approved by OFFICE Role.
*/
ALLOWED_CANCELLATION_REQUESTED,
/**
* Status after a boss has rejected application for leave.
*/
REJECTED,
/**
* If an application for leave has been allowed and is cancelled afterwards, it gets this status.
*/
CANCELLED,
/**
* If an application for leave has **not** been allowed yet and is cancelled, it gets this status.
*
* @since 2.5.2
*/
REVOKED
}
|
Use hostname instead of ip | """
Utility functions to retrieve information about available services and setting up security for the Hops platform.
These utils facilitates development by hiding complexity for programs interacting with Hops services.
"""
import socket
import subprocess
import os
import pydoop.hdfs as pyhdfs
def register(logdir):
#find free port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',0))
addr, port = s.getsockname()
s.close()
#let tb bind to port
pypath = os.getenv("PYSPARK_PYTHON")
pydir = os.path.dirname(pypath)
subprocess.Popen([pypath, "%s/tensorboard"%pydir, "--logdir=%s"%logdir, "--port=%d"%port, "--debug"])
host = socket.gethostname()
tb_url = "http://{0}:{1}".format(host, port)
#dump tb host:port to hdfs
hops_user = os.environ["USER"];
hops_user_split = hops_user.split("__");
project = hops_user_split[0];
pyhdfs.dump(tb_url, "hdfs:///Projects/" + project + "/Jupyter/.jupyter.tensorboard", user=hops_user) | """
Utility functions to retrieve information about available services and setting up security for the Hops platform.
These utils facilitates development by hiding complexity for programs interacting with Hops services.
"""
import socket
import subprocess
import os
import pydoop.hdfs as pyhdfs
def register(logdir):
#find free port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',0))
addr, port = s.getsockname()
s.close()
#let tb bind to port
pypath = os.getenv("PYSPARK_PYTHON")
pydir = os.path.dirname(pypath)
subprocess.Popen([pypath, "%s/tensorboard"%pydir, "--logdir=%s"%logdir, "--port=%d"%port, "--debug"])
tb_url = "http://{0}:{1}".format(addr, port)
#dump tb host:port to hdfs
hops_user = os.environ["USER"];
hops_user_split = hops_user.split("__");
project = hops_user_split[0];
pyhdfs.dump(tb_url, "hdfs:///Projects/" + project + "/Jupyter/.jupyter.tensorboard", user=hops_user) |
TASK: Use reference instead of index | <?php
namespace EditorconfigChecker\Fix;
class TrailingWhitespaceFix
{
/**
* Insert a final newline at the end of the file
*
* @param string $filename
* @return boolean
*/
public static function trim($filename)
{
if (is_file($filename)) {
$lines = file($filename);
foreach ($lines as &$line) {
$line = rtrim($line);
}
$fp = fopen($filename, 'w');
fwrite($fp, implode(PHP_EOL, $lines));
fclose($fp);
return true;
}
return false;
}
}
| <?php
namespace EditorconfigChecker\Fix;
class TrailingWhitespaceFix
{
/**
* Insert a final newline at the end of the file
*
* @param string $filename
* @return boolean
*/
public static function trim($filename)
{
if (is_file($filename)) {
$lines = file($filename);
foreach ($lines as $index => $line) {
$lines[$index] = rtrim($line);
}
$fp = fopen($filename, 'w');
fwrite($fp, implode(PHP_EOL, $lines));
fclose($fp);
return true;
}
return false;
}
}
|
Remove stop propagation from toggle text module | var locastyle = locastyle || {};
locastyle.toggleText = (function() {
'use strict';
var config = {
trigger: '[data-ls-module=toggleText]',
triggerChange: 'toggleText:change'
};
function eventHandler(el, target, text) {
el.trigger(config.triggerChange, [target, text]);
}
function bindToggle(el) {
var $target = el.data('target-text') ? $(el.data('target-text')) : el;
var textChange = el.data('toggle-text');
var textOriginal = $target.text();
el.data('toggle-text', textOriginal);
$target.text(textChange);
eventHandler(el, $target, textChange);
}
function bindEventOnClick() {
$(config.trigger).on('click.ls', function(event) {
event.preventDefault();
bindToggle($(this));
});
}
function unbind() {
$(config.trigger).off('click.ls');
}
function init() {
unbind();
bindEventOnClick();
}
return {
init: init
};
}());
| var locastyle = locastyle || {};
locastyle.toggleText = (function() {
'use strict';
var config = {
trigger: '[data-ls-module=toggleText]',
triggerChange: 'toggleText:change'
};
function eventHandler(el, target, text) {
el.trigger(config.triggerChange, [target, text]);
}
function bindToggle(el) {
var $target = el.data('target-text') ? $(el.data('target-text')) : el;
var textChange = el.data('toggle-text');
var textOriginal = $target.text();
el.data('toggle-text', textOriginal);
$target.text(textChange);
eventHandler(el, $target, textChange);
}
function bindEventOnClick() {
$(config.trigger).on('click.ls', function(event) {
event.preventDefault();
bindToggle($(this));
event.stopPropagation();
});
}
function unbind() {
$(config.trigger).off('click.ls');
}
function init() {
unbind();
bindEventOnClick();
}
return {
init: init
};
}());
|
Add new unit tests to collection |
#
# This source file is part of appleseed.
# Visit http://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import unittest
from testbasis import *
from testdict2dict import *
from testentitymap import *
from testentityvector import *
unittest.TestProgram(testRunner = unittest.TextTestRunner())
|
#
# This source file is part of appleseed.
# Visit http://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import unittest
from testdict2dict import *
from testentitymap import *
from testentityvector import *
unittest.TestProgram(testRunner = unittest.TextTestRunner())
|
Write access to new output file | import os
import sys
import re
import subprocess
def lemmatize( text ):
text = text.encode('utf8')
text = re.sub( '[\.,?!:;]' , '' , text )
out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True)
lemma = ''
for line in out.split('\n'):
line = line.strip()
line = line.split('\t')
if len( line ) >= 2:
lemma += line[1] + ' '
return lemma
## folder usecase
path = sys.argv[1]
for file in os.listdir( path ):
text = open( path + file )
text = text.readlines()
text = map( lambda x: x.strip(), text )
text = ' '.join( text )
lemma = lemmatize( text )
fo = open( path + file + '.lemma', 'w' )
fo.write( lemma )
fo.close()
| import os
import sys
import re
import subprocess
def lemmatize( text ):
text = text.encode('utf8')
text = re.sub( '[\.,?!:;]' , '' , text )
out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True)
lemma = ''
for line in out.split('\n'):
line = line.strip()
line = line.split('\t')
if len( line ) >= 2:
lemma += line[1] + ' '
return lemma
## folder usecase
path = sys.argv[1]
for file in os.listdir( path ):
text = open( path + file )
text = text.readlines()
text = map( lambda x: x.strip(), text )
text = ' '.join( text )
lemma = lemmatize( text )
fo = open( path + file + '.lemma' )
fo.write( lemma )
fo.close()
|
Add importing absolute_import & division from Prague | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def hash_str(a_str, table_size):
"""Hash a string by the folding method.
- Get ordinal number for each char.
- Sum all of the ordinal numbers.
- Return the remainder of the sum with table_size.
"""
sum = 0
for c in a_str:
sum += ord(c)
return sum % table_size
def weighted_hash_str(a_str, table_size):
"""Weighted-Hash a string by the folding method.
- Get ordinal number for each char.
- Weighted-sum all of the ordinal numbers.
- Return the remainder of the sum with table_size.
"""
sum = 0
for i, c in enumerate(a_str):
sum += (i + 1) * ord(c)
return sum % table_size
def main():
a_str = 'cat'
print('For hash_str(): {}'.format(hash_str(a_str, 11)))
print('For weighted_hash_str(): {}'
.format(weighted_hash_str(a_str, 11)))
if __name__ == '__main__':
main()
| from __future__ import print_function
def hash_str(a_str, table_size):
"""Hash a string by the folding method.
- Get ordinal number for each char.
- Sum all of the ordinal numbers.
- Return the remainder of the sum with table_size.
"""
sum = 0
for c in a_str:
sum += ord(c)
return sum % table_size
def weighted_hash_str(a_str, table_size):
"""Weighted-Hash a string by the folding method.
- Get ordinal number for each char.
- Weighted-sum all of the ordinal numbers.
- Return the remainder of the sum with table_size.
"""
sum = 0
for i, c in enumerate(a_str):
sum += (i + 1) * ord(c)
return sum % table_size
def main():
a_str = 'cat'
print('For hash_str(): {}'.format(hash_str(a_str, 11)))
print('For weighted_hash_str(): {}'
.format(weighted_hash_str(a_str, 11)))
if __name__ == '__main__':
main()
|
Change 2nd hidden layer size | import tensorflow as tf
class ANN:
def __init__(self):
self.inputNodes = 7
self.hiddenNodes = 64
self.hiddenNodes2 = 64 # weight3
self.outputNodes = 1
self.x = tf.placeholder("float", shape=[None, self.inputNodes], name="sensor-input")
self.W1 = tf.placeholder("float", shape=[self.inputNodes, self.hiddenNodes])
self.W2 = tf.placeholder("float", shape=[self.hiddenNodes, self.hiddenNodes2]) # weight3
self.W3 = tf.placeholder("float", shape=[self.hiddenNodes2, self.outputNodes]) # weight3
self.y = tf.tanh(
tf.matmul(tf.tanh(tf.matmul(tf.tanh(tf.matmul(self.x, self.W1)), self.W2)), self.W3)) # weight3
self.session = tf.Session()
init = tf.initialize_all_variables()
self.session.run(init)
def propagate_forward(self, car, sensor_data):
return self.session.run(self.y, feed_dict={self.x: sensor_data, self.W1: car.W1,
self.W2: car.W2, self.W3: car.W3}) # weight3
| import tensorflow as tf
class ANN:
def __init__(self):
self.inputNodes = 7
self.hiddenNodes = 64
self.hiddenNodes2 = 32 # weight3
self.outputNodes = 1
self.x = tf.placeholder("float", shape=[None, self.inputNodes], name="sensor-input")
self.W1 = tf.placeholder("float", shape=[self.inputNodes, self.hiddenNodes])
self.W2 = tf.placeholder("float", shape=[self.hiddenNodes, self.hiddenNodes2]) # weight3
self.W3 = tf.placeholder("float", shape=[self.hiddenNodes2, self.outputNodes]) # weight3
self.y = tf.tanh(
tf.matmul(tf.tanh(tf.matmul(tf.tanh(tf.matmul(self.x, self.W1)), self.W2)), self.W3)) # weight3
self.session = tf.Session()
init = tf.initialize_all_variables()
self.session.run(init)
def propagate_forward(self, car, sensor_data):
return self.session.run(self.y, feed_dict={self.x: sensor_data, self.W1: car.W1,
self.W2: car.W2, self.W3: car.W3}) # weight3
|
Add dotcloud version requirement (I had 0.4.2 and that didn't work). | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
import skypipe
setup(
name='skypipe',
version=skypipe.VERSION,
author='Jeff Lindsay',
author_email='progrium@gmail.com',
description='Magic pipe in the sky',
long_description=open(os.path.join(os.path.dirname(__file__),
"README.md")).read().replace(':', '::'),
license='MIT',
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
url="http://github.com/progrium/skypipe",
packages=find_packages(),
install_requires=['pyzmq', 'dotcloud>=0.7', 'argparse'],
zip_safe=False,
package_data={
'skypipe': ['satellite/*']},
entry_points={
'console_scripts': [
'skypipe = skypipe.cli:run',]}
)
| #!/usr/bin/env python
import os
from setuptools import setup, find_packages
import skypipe
setup(
name='skypipe',
version=skypipe.VERSION,
author='Jeff Lindsay',
author_email='progrium@gmail.com',
description='Magic pipe in the sky',
long_description=open(os.path.join(os.path.dirname(__file__),
"README.md")).read().replace(':', '::'),
license='MIT',
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
url="http://github.com/progrium/skypipe",
packages=find_packages(),
install_requires=['pyzmq', 'dotcloud', 'argparse'],
zip_safe=False,
package_data={
'skypipe': ['satellite/*']},
entry_points={
'console_scripts': [
'skypipe = skypipe.cli:run',]}
)
|
Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots.
BUG=424027
TBR=dtu@chromium.org
Review URL: https://codereview.chromium.org/643763005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#299833} | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_monitor import ippet_power_monitor
class IppetPowerMonitorTest(unittest.TestCase):
@decorators.Disabled
def testFindOrInstallIppet(self):
self.assertTrue(ippet_power_monitor.IppetPath())
@decorators.Enabled('win')
def testIppetRunsWithoutErrors(self):
# Very basic test, doesn't validate any output data.
platform_backend = win_platform_backend.WinPlatformBackend()
power_monitor = ippet_power_monitor.IppetPowerMonitor(platform_backend)
if not power_monitor.CanMonitorPower():
logging.warning('Test not supported on this platform.')
return
power_monitor.StartMonitoringPower(None)
statistics = power_monitor.StopMonitoringPower()
self.assertEqual(statistics['identifier'], 'ippet')
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_monitor import ippet_power_monitor
class IppetPowerMonitorTest(unittest.TestCase):
@decorators.Enabled('win')
def testFindOrInstallIppet(self):
self.assertTrue(ippet_power_monitor.IppetPath())
@decorators.Enabled('win')
def testIppetRunsWithoutErrors(self):
# Very basic test, doesn't validate any output data.
platform_backend = win_platform_backend.WinPlatformBackend()
power_monitor = ippet_power_monitor.IppetPowerMonitor(platform_backend)
if not power_monitor.CanMonitorPower():
logging.warning('Test not supported on this platform.')
return
power_monitor.StartMonitoringPower(None)
statistics = power_monitor.StopMonitoringPower()
self.assertEqual(statistics['identifier'], 'ippet')
|
Update Border Colour for ClassicButtonToggle | import { css } from 'styled-components';
import { THEMES } from '../../style/themes';
export default ({ theme }) => theme.name === THEMES.classic && css`
height: 47px;
font-weight: 900;
border: 1px solid #ccd6db;
input:checked ~ & {
color: ${theme.colors.white};
background-color: #1573e6;
}
input:focus ~ & {
outline: 0;
}
&:hover {
border-color: #1e499f;
color: ${theme.colors.white};
background-color: #1e499f;
}
${({ size }) => size === 'small' && css`
height: auto;
padding: 5px 8px;
font-weight: 700;
font-size: 12px;
`};
${({ size, buttonIcon, buttonIconSize }) => buttonIcon && size === 'large' && buttonIconSize === 'large' && css`
height: auto;
padding-top: 15px;
padding-bottom: 15px;
`};
`;
| import { css } from 'styled-components';
import { THEMES } from '../../style/themes';
export default ({ theme }) => theme.name === THEMES.classic && css`
height: 47px;
font-weight: 900;
input:checked ~ & {
color: ${theme.colors.white};
background-color: #1573e6;
}
input:focus ~ & {
outline: 0;
}
&:hover {
border-color: #1e499f;
color: ${theme.colors.white};
background-color: #1e499f;
}
${({ size }) => size === 'small' && css`
height: auto;
padding: 5px 8px;
font-weight: 700;
font-size: 12px;
`};
${({ size, buttonIcon, buttonIconSize }) => buttonIcon && size === 'large' && buttonIconSize === 'large' && css`
height: auto;
padding-top: 15px;
padding-bottom: 15px;
`};
`;
|
Add version number to menu screen | package com.chaquo.python.demo;
import android.content.pm.*;
import android.os.*;
import android.support.v7.app.*;
import android.support.v7.preference.*;
import android.text.method.*;
import android.widget.*;
import com.chaquo.python.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
setTitle(getTitle() + " " + version);
} catch (PackageManager.NameNotFoundException ignored) {}
if (! Python.isStarted()) {
Python.start(new AndroidPlatform(this));
}
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.flMenu, new MenuFragment())
.commit();
((TextView)findViewById(R.id.tvCaption)).setMovementMethod(LinkMovementMethod.getInstance());
}
public static class MenuFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.activity_main);
}
}
}
| package com.chaquo.python.demo;
import android.os.*;
import android.support.v7.app.*;
import android.support.v7.preference.*;
import android.text.method.*;
import android.widget.*;
import com.chaquo.python.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (! Python.isStarted()) {
Python.start(new AndroidPlatform(this));
}
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.flMenu, new MenuFragment())
.commit();
((TextView)findViewById(R.id.tvCaption)).setMovementMethod(LinkMovementMethod.getInstance());
}
public static class MenuFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.activity_main);
}
}
}
|
Fix missing import in contrib script added in [2630].
git-svn-id: f68c6b3b1dcd5d00a2560c384475aaef3bc99487@2631 af82e41b-90c4-0310-8c96-b1721e28e2e2 | #!/usr/bin/env python
#
# This script completely migrates a <= 0.8.x Trac environment to use the new
# default ticket model introduced in Trac 0.9.
#
# In particular, this means that the severity field is removed (or rather
# disabled by removing all possible values), and the priority values are
# changed to the more meaningful new defaults.
#
# Make sure to make a backup of the Trac environment before running this!
import os
import sys
from trac.env import open_environment
from trac.ticket.model import Priority, Severity
priority_mapping = {
'highest': 'blocker',
'high': 'critical',
'normal': 'major',
'low': 'minor',
'lowest': 'trivial'
}
def main():
if len(sys.argv) < 2:
print >> sys.stderr, 'usage: %s /path/to/projenv' \
% os.path.basename(sys.argv[0])
sys.exit(2)
env = open_environment(sys.argv[1])
db = env.get_db_cnx()
for oldprio, newprio in priority_mapping.items():
priority = Priority(env, oldprio, db)
priority.name = newprio
priority.update(db)
for severity in list(Severity.select(env, db)):
severity.delete(db)
db.commit()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
#
# This script completely migrates a <= 0.8.x Trac environment to use the new
# default ticket model introduced in Trac 0.9.
#
# In particular, this means that the severity field is removed (or rather
# disabled by removing all possible values), and the priority values are
# changed to the more meaningful new defaults.
#
# Make sure to make a backup of the Trac environment before running this!
import sys
from trac.env import open_environment
from trac.ticket.model import Priority, Severity
priority_mapping = {
'highest': 'blocker',
'high': 'critical',
'normal': 'major',
'low': 'minor',
'lowest': 'trivial'
}
def main():
if len(sys.argv) < 2:
print >> sys.stderr, 'usage: %s /path/to/projenv' \
% os.path.basename(sys.argv[0])
sys.exit(2)
env = open_environment(sys.argv[1])
db = env.get_db_cnx()
for oldprio, newprio in priority_mapping.items():
priority = Priority(env, oldprio, db)
priority.name = newprio
priority.update(db)
for severity in list(Severity.select(env, db)):
severity.delete(db)
db.commit()
if __name__ == '__main__':
main()
|
Move module name filtering into own function | <?php
declare(strict_types = 1);
namespace Raml2Apigility\Generator;
use Raml\ApiDefinition;
use Zend\ModuleManager\ModuleManager;
use ZF\Apigility\Admin\Model\ModuleModel;
use ZF\Apigility\Admin\Model\ModulePathSpec;
use Zend\I18n\Filter\Alpha as AlphaFilter;
use ZF\Configuration\ModuleUtils;
final class ModuleGenerator extends AbstractGenerator
{
protected function filterModuleName(string $name): string
{
return (new AlphaFilter())->filter($name);
}
public function generate(ApiDefinition $api): bool
{
$moduleName = $this->filterModuleName($api->getTitle());
$moduleManager = new ModuleManager(
include $this->getBasePath() . '/config/modules.config.php'
);
$moduleUtils = new ModuleUtils($moduleManager);
$moduleModel = new ModuleModel(
$moduleManager,
[],
[]
);
$moduleModel->setUseShortArrayNotation(true);
$modulePathSpec = new ModulePathSpec(
$moduleUtils,
ModulePathSpec::PSR_4,
$this->getBasePath()
);
$moduleModel->createModule($moduleName, $modulePathSpec);
return true;
}
}
| <?php
declare(strict_types = 1);
namespace Raml2Apigility\Generator;
use Raml\ApiDefinition;
use Zend\ModuleManager\ModuleManager;
use ZF\Apigility\Admin\Model\ModuleModel;
use ZF\Apigility\Admin\Model\ModulePathSpec;
use Zend\I18n\Filter\Alpha as AlphaFilter;
use ZF\Configuration\ModuleUtils;
final class ModuleGenerator extends AbstractGenerator
{
public function generate(ApiDefinition $api): bool
{
$alphaFilter = new AlphaFilter();
$namespace = $alphaFilter->filter($api->getTitle());
$moduleManager = new ModuleManager(
include $this->getBasePath() . '/config/modules.config.php'
);
$moduleUtils = new ModuleUtils($moduleManager);
$moduleModel = new ModuleModel(
$moduleManager,
[],
[]
);
$moduleModel->setUseShortArrayNotation(true);
$modulePathSpec = new ModulePathSpec(
$moduleUtils,
ModulePathSpec::PSR_4,
$this->getBasePath()
);
$moduleModel->createModule($namespace, $modulePathSpec);
return true;
}
}
|
Solve a problem with Webpack 4 | var path = require('path')
var pkg = require('./package.json')
var UglifyjsPlugin = require('uglifyjs-webpack-plugin')
var BannerPlugin = require('webpack').BannerPlugin
module.exports = {
entry: {
'extenso': './index.js',
'extenso.min': './index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'extenso',
libraryTarget: 'umd',
// To solve a problem with Webpack 4 (webpack#6522).
globalObject: `typeof self !== 'undefined' ? self : this`
},
module: {
rules: [{
test: /\.js$/i,
use: 'babel-loader'
}]
},
plugins: [
new UglifyjsPlugin({
include: /\.min\.js$/,
uglifyOptions: {
output: {
comments: false
}
}
}),
new BannerPlugin([
'Extenso.js ' + pkg.version,
'© 2015-' + (new Date()).getFullYear() + ' ' + pkg.author,
'License: ' + pkg.license
].join('\n'))
]
}
| var path = require('path')
var pkg = require('./package.json')
var UglifyjsPlugin = require('uglifyjs-webpack-plugin')
var BannerPlugin = require('webpack').BannerPlugin
module.exports = {
entry: {
'extenso': './index.js',
'extenso.min': './index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'extenso',
libraryTarget: 'umd'
},
module: {
rules: [{
test: /\.js$/i,
use: 'babel-loader'
}]
},
plugins: [
new UglifyjsPlugin({
include: /\.min\.js$/,
uglifyOptions: {
output: {
comments: false
}
}
}),
new BannerPlugin([
'Extenso.js ' + pkg.version,
'© 2015-' + (new Date()).getFullYear() + ' ' + pkg.author,
'License: ' + pkg.license
].join('\n'))
]
}
|
Add z-index to the Header | import styled from 'styled-components';
import { navbarHeight } from '../../common-styles/layout';
export const Wrapper = styled.nav`
align-items: center;
background-color: #fff;
color: #666;
display: flex;
flex-direction: row;
font-family: Raleway, 'Open Sans', Helvetica, sans-serif;
font-size: 14px;
font-weight: 600;
height: ${navbarHeight}px;
justify-content: flex-start;
left: 0;
position: fixed;
right: 0;
text-transform: uppercase;
top: 0;
width: 100%;
z-index: 1;
`;
export const Logo = styled.div`
align-items: center;
background-image: url(${props => props.imgUrl});
background-size: contain;
background-repeat: no-repeat;
border: 2px solid #fff;
color: #18e28c;
display: flex;
flex-direction: row;
height: ${navbarHeight}px;
max-height: ${navbarHeight}px;
width: ${navbarHeight * 2}px;
& p {
position: relative;
left: 80px;
}
`;
export const ProfileLink = styled.div`
border-bottom: 2px solid transparent;
flex: 1;
text-align: center;
`;
| import styled from 'styled-components';
import { navbarHeight } from '../../common-styles/layout';
export const Wrapper = styled.nav`
align-items: center;
background-color: #fff;
color: #666;
display: flex;
flex-direction: row;
font-family: Raleway, 'Open Sans', Helvetica, sans-serif;
font-size: 14px;
font-weight: 600;
height: ${navbarHeight}px;
justify-content: flex-start;
left: 0;
position: fixed;
right: 0;
text-transform: uppercase;
top: 0;
width: 100%;
`;
export const Logo = styled.div`
align-items: center;
background-image: url(${props => props.imgUrl});
background-size: contain;
background-repeat: no-repeat;
border: 2px solid #fff;
color: #18e28c;
display: flex;
flex-direction: row;
height: ${navbarHeight}px;
max-height: ${navbarHeight}px;
width: ${navbarHeight * 2}px;
& p {
position: relative;
left: 80px;
}
`;
export const ProfileLink = styled.div`
border-bottom: 2px solid transparent;
flex: 1;
text-align: center;
`;
|
Remove css to apply each time. | $('#dripbot-title').css({
"display": "inline-block",
"margin-right": "20px"
});
$('#dripbot').css({
"text-align": "left"
});
$('#dripbot-toggle.stop').css({
"background-color": "#e9656d",
"color": "white",
"margin-top": "-10px"
});
$('#dripbot ul li p').css({
"margin-bottom":"5px",
"margin-right": "40px",
"display": "inline-block"
});
$('img#dripbot-logo').css({
"margin-bottom": "10px",
"margin-right": "5px"
});
$('div#dripbot-update').css({
"background-color": "#47a447",
"padding": "10px"
});
$('div#dripbot-update h1').css({
"font-weight": "800",
});
$('#save-game').css({
"background-color": "#5cb85c",
"color": "white",
"margin-left": "20px"
});
| $('#dripbot-title').css({
"display": "inline-block",
"margin-right": "20px"
});
$('#dripbot').css({
"text-align": "left"
});
$('#dripbot-toggle.stop').css({
"background-color": "#e9656d",
"color": "white",
"margin-top": "-10px"
});
$('#dripbot ul li p').css({
"margin-bottom":"5px",
"margin-right": "40px",
"display": "inline-block"
});
$('img#dripbot-logo').css({
"margin-bottom": "10px",
"margin-right": "5px"
});
$('div#dripbot-update').css({
"background-color": "#47a447",
"padding": "10px"
});
$('div#dripbot-update h1').css({
"font-weight": "800",
});
$('#save-game').css({
"background-color": "#5cb85c",
"color": "white",
"margin-left": "20px"
});
$('div#leaderBoard table tbody tr td.leader-diff').css({
"color": "#47a447"
}); |
Add some spacing to search results | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import ALL_DATA from '../fixtures/alldata.js';
class SearchResultItem extends Component {
render() {
const { id, title, previewText, authors, year, currentSearch} = this.props;
const boldTerms = function(text, term){
return text.split(' ').map(function(word){
if(word === term) {
return (<b>{word} </b>);
} else {
return (<span>{word} </span>);
}
});
}
const boldedPreviewText = boldTerms(previewText, currentSearch);
const boldedTitle = boldTerms(title, currentSearch);
return (
<div className="searchResultItem" >
{boldedTitle}<br/>
{authors}<br/>
{year}<br/>
{boldedPreviewText}<br/><br/>
</div>
);
}
}
export default SearchResultItem;
| // @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import ALL_DATA from '../fixtures/alldata.js';
class SearchResultItem extends Component {
render() {
const { id, title, previewText, authors, year, currentSearch} = this.props;
const boldTerms = function(text, term){
return text.split(' ').map(function(word){
if(word === term) {
return (<b>{word} </b>);
} else {
return (<span>{word} </span>);
}
});
}
const boldedPreviewText = boldTerms(previewText, currentSearch);
const boldedTitle = boldTerms(title, currentSearch);
return (
<div className="searchResultItem">
{boldedTitle}
{authors}
{year}
{boldedPreviewText}
</div>
);
}
}
export default SearchResultItem;
|
Break dependency on profiler to the json package
This lays more of the groundwork for the core package to
no longer be split (required for Java 9 modules) without
us having to do a lot of additional work or move classes
around. | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.logging.profiler;
public class HttpProfilerLogEntry extends ProfilerLogEntry {
public HttpProfilerLogEntry(String commandName, boolean isStart) {
super(EventType.HTTP_COMMAND, constructMessage(EventType.HTTP_COMMAND, commandName, isStart));
}
private static String constructMessage(EventType eventType, String commandName, boolean isStart) {
// We're going to make the assumption that command name is a simple string which doesn't need
// escaping.
return String.format(
"{\"event\": \"%s\", \"command\": \"%s\", \"startorend\": \"%s\"}",
eventType.toString(),
commandName,
isStart ? "start" : "end");
}
}
| // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.logging.profiler;
import org.openqa.selenium.json.Json;
import java.util.TreeMap;
public class HttpProfilerLogEntry extends ProfilerLogEntry {
public HttpProfilerLogEntry(String commandName, boolean isStart) {
super(EventType.HTTP_COMMAND, constructMessage(EventType.HTTP_COMMAND, commandName, isStart));
}
private static String constructMessage(EventType eventType, String commandName, boolean isStart) {
TreeMap<Object, Object> map = new TreeMap<>();
map.put("event", eventType.toString());
map.put("command", commandName);
map.put("startorend", isStart ? "start" : "end");
return new Json().toJson(map);
}
}
|
Write initial response using bytes.Buffer | package eventsource
import (
"bytes"
"fmt"
"net/http"
)
const header string = `HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
Access-Control-Allow-Credentials: true`
const body string = "\n\nretry: 2000\n"
func Handler (res http.ResponseWriter, req *http.Request) {
hj, ok := res.(http.Hijacker)
if !ok {
http.Error(res, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, _, err := hj.Hijack()
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
_, err = conn.Write(initialResponse(req))
if err != nil {
conn.Close()
}
}
func initialResponse(req *http.Request) []byte {
var buf bytes.Buffer
buf.WriteString(header)
if origin := req.Header.Get("origin"); origin != "" {
cors:= fmt.Sprintf("Access-Control-Allow-Origin: %s", origin)
buf.WriteString(cors)
}
buf.WriteString(body)
return buf.Bytes()
}
| package eventsource
import (
"fmt"
"net/http"
)
var header string = `HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
Access-Control-Allow-Origin: %s
Access-Control-Allow-Credentials: true
retry: 2000
`
func Handler (res http.ResponseWriter, req *http.Request) {
hj, ok := res.(http.Hijacker)
if !ok {
http.Error(res, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, _, err := hj.Hijack()
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
origin := req.Header.Get("origin")
h := fmt.Sprintf(header, origin)
_, err = conn.Write([]byte(h))
if err != nil {
conn.Close()
}
}
|
Fix copy page when permission is disabled | # -*- coding: utf-8 -*-
from django.utils.html import conditional_escape
from django.core.serializers.json import DjangoJSONEncoder
class SafeJSONEncoder(DjangoJSONEncoder):
def _recursive_escape(self, o, esc=conditional_escape):
if isinstance(o, dict):
return type(o)((esc(k), self._recursive_escape(v)) for (k, v) in o.iteritems())
if isinstance(o, (list, tuple)):
return type(o)(self._recursive_escape(v) for v in o)
if type(o) is bool:
return o
try:
return type(o)(esc(o))
except ValueError:
return esc(o)
def encode(self, o):
value = self._recursive_escape(o)
return super(SafeJSONEncoder, self).encode(value)
| # -*- coding: utf-8 -*-
from django.utils.html import conditional_escape
from django.core.serializers.json import DjangoJSONEncoder
class SafeJSONEncoder(DjangoJSONEncoder):
def _recursive_escape(self, o, esc=conditional_escape):
if isinstance(o, dict):
return type(o)((esc(k), self._recursive_escape(v)) for (k, v) in o.iteritems())
if isinstance(o, (list, tuple)):
return type(o)(self._recursive_escape(v) for v in o)
try:
return type(o)(esc(o))
except ValueError:
return esc(o)
def encode(self, o):
value = self._recursive_escape(o)
return super(SafeJSONEncoder, self).encode(value)
|
Revert "format to 'n/a' if no value is passed to the formatter"
This reverts commit 17bcf50a6d27b0221ae56c6a060ea2e6f1d2f240. | /* @flow */
/**
* @jsx React.DOM
*/
'use strict';
var React = require('react');
var CheckboxEditor = React.createClass({
PropTypes : {
value : React.PropTypes.bool.isRequired,
rowIdx : React.PropTypes.number.isRequired,
column: React.PropTypes.shape({
key: React.PropTypes.string.isRequired,
onCellChange: React.PropTypes.func.isRequired
}).isRequired
},
render(): ? ReactElement {
var checked = this.props.value != null ? this.props.value : false;
return (<input className="react-grid-CheckBox" type="checkbox" checked={checked} onClick={this.handleChange} />);
},
handleChange(e: Event){
this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, e);
}
});
module.exports = CheckboxEditor;
| /* @flow */
/**
* @jsx React.DOM
*/
'use strict';
var React = require('react');
var CheckboxEditor = React.createClass({
PropTypes : {
value : React.PropTypes.bool.isRequired,
rowIdx : React.PropTypes.number.isRequired,
column: React.PropTypes.shape({
key: React.PropTypes.string.isRequired,
onCellChange: React.PropTypes.func.isRequired
}).isRequired
},
render(): ? ReactElement {
var formatter = <span> n/a </span>
if (this.props.value != null ) {
var checked = this.props.value;
formatter = <input className="react-grid-CheckBox" type="checkbox" checked={checked} onClick={this.handleChange} />
}
return (formatter);
},
handleChange(e: Event){
this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, e);
}
});
module.exports = CheckboxEditor;
|
ENH: Use emailadministrator in createpublicdashboard test | <?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
require_once('kwtest/kw_db.php');
class CreatePublicDashboardTestCase extends KWWebTestCase
{
var $url = null;
var $db = null;
function __construct()
{
parent::__construct();
require('config.test.php');
$this->url = $configure['urlwebsite'];
$this->db =& new database($db['type']);
$this->db->setDb($db['name']);
$this->db->setHost($db['host']);
$this->db->setUser($db['login']);
$this->db->setPassword($db['pwd']);
}
function testCreatePublicDashboard()
{
$content = $this->connect($this->url);
if(!$content)
{
return;
}
$this->login();
if(!$this->analyse($this->clickLink('[Create new project]')))
{
return;
}
$this->setField('name', 'PublicDashboard');
$this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
$this->setField('public', '1');
$this->setField('emailAdministrator','1');
$this->clickSubmitByName('Submit');
$this->checkErrors();
$this->assertText('The project PublicDashboard has been created successfully.');
}
}
?>
| <?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
require_once('kwtest/kw_db.php');
class CreatePublicDashboardTestCase extends KWWebTestCase
{
var $url = null;
var $db = null;
function __construct()
{
parent::__construct();
require('config.test.php');
$this->url = $configure['urlwebsite'];
$this->db =& new database($db['type']);
$this->db->setDb($db['name']);
$this->db->setHost($db['host']);
$this->db->setUser($db['login']);
$this->db->setPassword($db['pwd']);
}
function testCreatePublicDashboard()
{
$content = $this->connect($this->url);
if(!$content)
{
return;
}
$this->login();
if(!$this->analyse($this->clickLink('[Create new project]')))
{
return;
}
$this->setField('name', 'PublicDashboard');
$this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
$this->setField('public', '1');
$this->clickSubmitByName('Submit');
$this->checkErrors();
$this->assertText('The project PublicDashboard has been created successfully.');
}
}
?>
|
Use parameter instead of hardcoded "manual" | package camelinaction;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Processor to stop a route by its name
*/
public class StopRouteProcessor implements Processor {
private final static Logger LOG = LoggerFactory.getLogger(StopRouteProcessor.class);
private final String name;
/**
* @param name route to stop
*/
public StopRouteProcessor(String name) {
this.name = name;
}
public void process(Exchange exchange) throws Exception {
// force stopping this route while we are routing an Exchange
// requires two steps:
// 1) unregister from the inflight registry
// 2) stop the route
LOG.info("Stopping route: " + name);
exchange.getContext().getInflightRepository().remove(exchange, name);
exchange.getContext().stopRoute(name);
}
}
| package camelinaction;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Processor to stop a route by its name
*/
public class StopRouteProcessor implements Processor {
private final static Logger LOG = LoggerFactory.getLogger(StopRouteProcessor.class);
private final String name;
/**
* @param name route to stop
*/
public StopRouteProcessor(String name) {
this.name = name;
}
public void process(Exchange exchange) throws Exception {
// force stopping this route while we are routing an Exchange
// requires two steps:
// 1) unregister from the inflight registry
// 2) stop the route
LOG.info("Stopping route: " + name);
exchange.getContext().getInflightRepository().remove(exchange, "manual");
exchange.getContext().stopRoute(name);
}
}
|
Add css to grunt watch. | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';',
},
dist: {
src: ['js/actions.js', 'js/main.js', 'js/vendor/fuse.min.js'],
dest: 'js/dist/built.js',
},
},
watch: {
js: {
files: [
'js/*.js',
'css/*.css'
],
tasks: [
'default',
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat']);
} | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';',
},
dist: {
src: ['js/actions.js', 'js/main.js', 'js/vendor/fuse.min.js'],
dest: 'js/dist/built.js',
},
},
watch: {
js: {
files: [
'js/*.js'
],
tasks: [
'default',
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat']);
} |
Remove an unneeded method from Feed class | import equal from 'deep-equal';
export default class Feed {
constructor(api, path, params) {
this.api = api;
this.path = path;
this.params = params;
this.nextURL = undefined;
this.items = [];
}
fetchAll() {
return new Promise((resolve, reject) => {
const next = () => {
if (this.hasMore()) {
this.fetchNext().then(next).catch(reject);
} else {
resolve(this.items);
}
}
next();
});
}
fetchNext() {
return this._fetchNextData()
.then(data => {
const items = data.results;
this.nextURL = data.next;
this.items = this.items.concat(items);
return items;
});
}
hasAnything() {
return this.items.length !== 0;
}
hasMore() {
return this.nextURL !== null; // undefined means we don't know yet
}
_fetchNextData() {
if (this.nextURL) {
return this.api.get(this.nextURL);
} else {
return this.api.get(this.path, this.params);
}
}
}
| import equal from 'deep-equal';
export default class Feed {
constructor(api, path, params) {
this.api = api;
this.path = path;
this.params = params;
this.nextURL = undefined;
this.items = [];
}
sameAs(other) {
return this.path == other.path && equal(this.params, other.params);
}
fetchAll() {
return new Promise((resolve, reject) => {
const next = () => {
if (this.hasMore()) {
this.fetchNext().then(next).catch(reject);
} else {
resolve(this.items);
}
}
next();
});
}
fetchNext() {
return this._fetchNextData()
.then(data => {
const items = data.results;
this.nextURL = data.next;
this.items = this.items.concat(items);
return items;
});
}
hasAnything() {
return this.items.length !== 0;
}
hasMore() {
return this.nextURL !== null; // undefined means we don't know yet
}
_fetchNextData() {
if (this.nextURL) {
return this.api.get(this.nextURL);
} else {
return this.api.get(this.path, this.params);
}
}
}
|
Fix a missing property bug | <?php
namespace Transmission\Model;
use Transmission\Client;
/**
* Base class for Transmission models
*
* @author Ramon Kleiss <ramon@cubilon.nl>
*/
abstract class AbstractModel implements ModelInterface
{
/**
* @var Transmission\Client
*/
protected $client;
/**
* Constructor
*
* @param Transmission\Client $client
*/
public function __construct(Client $client = null)
{
$this->client = $client;
}
/**
* @param Transmission\Client $client
*/
public function setClient(Client $client)
{
$this->client = $client;
}
/**
* @return Transmission\Client
*/
public function getClient()
{
return $this->client;
}
/**
* {@inheritDoc}
*/
public static function getMapping()
{
return array();
}
}
| <?php
namespace Transmission\Model;
use Transmission\Client;
/**
* Base class for Transmission models
*
* @author Ramon Kleiss <ramon@cubilon.nl>
*/
abstract class AbstractModel implements ModelInterface
{
/**
* Constructor
*
* @param Transmission\Client $client
*/
public function __construct(Client $client = null)
{
$this->client = $client;
}
/**
* @param Transmission\Client $client
*/
public function setClient(Client $client)
{
$this->client = $client;
}
/**
* @return Transmission\Client
*/
public function getClient()
{
return $this->client;
}
/**
* {@inheritDoc}
*/
public static function getMapping()
{
return array();
}
}
|
Change namespace name to Coolblue | "use strict";
var Hapi = require("hapi");
var halacious = require("halacious");
var fs = require("fs");
var MongoDbConnection = require("./lib/services/mongoDb");
const config = require("./etc/conf.json");
var server = new Hapi.Server();
server.connection(config.connection);
server.register(halacious, function registerHalacious(error) {
if (error) {
return console.log(error);
}
var ns = server.plugins.halacious.namespaces.add({
name: "Coolblue",
description: "Hackathon",
prefix: "hack"
});
ns.rel({ name: "qaid", description: "A collection of questions" });
ns.rel({ name: "question", description: "A question" });
ns.rel({ name: "answer", description: "An answer" });
});
fs.readdir("./lib/resources/", function getFiles(error, files) {
if (error) {
throw error;
}
files.forEach(function getFile(file) {
if (file.includes(".js") < 0) {
return;
}
server.route(require("./lib/resources/" + file));
});
});
MongoDbConnection.connect((error) => {
if (error) {
process.exit(2);
}
// Start the Server
server.start(() => console.log("Server running at:", server.info.uri));
}); | "use strict";
var Hapi = require("hapi");
var halacious = require("halacious");
var fs = require("fs");
var MongoDbConnection = require("./lib/services/mongoDb");
const config = require("./etc/conf.json");
var server = new Hapi.Server();
server.connection(config.connection);
server.register(halacious, function registerHalacious(error) {
if (error) {
return console.log(error);
}
var ns = server.plugins.halacious.namespaces.add({
name: "undefined",
description: "Hackathon",
prefix: "hack"
});
ns.rel({ name: "qaid", description: "A collection of questions" });
ns.rel({ name: "question", description: "A question" });
ns.rel({ name: "answer", description: "An answer" });
});
fs.readdir("./lib/resources/", function getFiles(error, files) {
if (error) {
throw error;
}
files.forEach(function getFile(file) {
if (file.includes(".js") < 0) {
return;
}
server.route(require("./lib/resources/" + file));
});
});
MongoDbConnection.connect((error) => {
if (error) {
process.exit(2);
}
// Start the Server
server.start(() => console.log("Server running at:", server.info.uri));
}); |
Use abs time in <= 1.5.2 | package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_4_5_6_7_8_9r1_9r2_10_11_12r1_12r2;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleTimeUpdate;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;
public class TimeUpdate extends MiddleTimeUpdate {
@Override
public RecyclableCollection<ClientBoundPacketData> toData() {
ProtocolVersion version = connection.getVersion();
ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_UPDATE_TIME_ID, version);
if (version.isBeforeOrEq(ProtocolVersion.MINECRAFT_1_5_2)) {
timeOfDay = Math.abs(timeOfDay);
}
serializer.writeLong(worldAge);
serializer.writeLong(timeOfDay);
return RecyclableSingletonList.create(serializer);
}
}
| package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_4_5_6_7_8_9r1_9r2_10_11_12r1_12r2;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleTimeUpdate;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;
public class TimeUpdate extends MiddleTimeUpdate {
@Override
public RecyclableCollection<ClientBoundPacketData> toData() {
ProtocolVersion version = connection.getVersion();
ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_UPDATE_TIME_ID, version);
if (version.isBeforeOrEq(ProtocolVersion.MINECRAFT_1_4_7)) {
timeOfDay = Math.abs(timeOfDay);
}
serializer.writeLong(worldAge);
serializer.writeLong(timeOfDay);
return RecyclableSingletonList.create(serializer);
}
}
|
Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION. | # Copyright 2011 OpenStack Foundation
#
# 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.
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
| # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
|
Remove SA from the blueprints | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.core.config.localsearch;
import java.util.Arrays;
public enum LocalSearchType {
HILL_CLIMBING,
TABU_SEARCH,
SIMULATED_ANNEALING,
LATE_ACCEPTANCE,
GREAT_DELUGE,
VARIABLE_NEIGHBORHOOD_DESCENT;
/**
* @return {@link #values()} without duplicates (abstract types that end up behaving as one of the other types).
*/
public static LocalSearchType[] getBluePrintTypes() {
return Arrays.stream(values())
// Workaround for https://issues.jboss.org/browse/PLANNER-1294
.filter(localSearchType -> localSearchType != SIMULATED_ANNEALING)
.toArray(LocalSearchType[]::new);
}
}
| /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.core.config.localsearch;
public enum LocalSearchType {
HILL_CLIMBING,
TABU_SEARCH,
SIMULATED_ANNEALING,
LATE_ACCEPTANCE,
GREAT_DELUGE,
VARIABLE_NEIGHBORHOOD_DESCENT;
/**
* @return {@link #values()} without duplicates (abstract types that end up behaving as one of the other types).
*/
public static LocalSearchType[] getBluePrintTypes() {
return values();
}
}
|
Enforce parens around all ES6 arrow functions | module.exports = {
"extends": "chiton/configurations/default",
"env": {
"es6": true
},
"ecmaFeatures": {
"modules": true
},
"rules": {
"arrow-body-style": [2, "as-needed"],
"arrow-parens": [2, "always"],
"arrow-spacing": [2, {"after": true, "before": true}],
"no-arrow-condition": 2,
"no-class-assign": 2,
"no-const-assign": 2,
"no-dupe-class-members": 2,
"no-var": 2,
"object-shorthand": [2, "never"],
"prefer-const": 2,
"prefer-spread": 2,
"prefer-template": 2,
"require-yield": 2
}
};
| module.exports = {
"extends": "chiton/configurations/default",
"env": {
"es6": true
},
"ecmaFeatures": {
"modules": true
},
"rules": {
"arrow-body-style": [2, "as-needed"],
"arrow-parens": [2, "as-needed"],
"arrow-spacing": [2, {"after": true, "before": true}],
"no-arrow-condition": 2,
"no-class-assign": 2,
"no-const-assign": 2,
"no-dupe-class-members": 2,
"no-var": 2,
"object-shorthand": [2, "never"],
"prefer-const": 2,
"prefer-spread": 2,
"prefer-template": 2,
"require-yield": 2
}
};
|
Use option instead of argument | <?php
/**
* @copyright Frederic G. Østby
* @license http://www.makoframework.com/license
*/
namespace mako\application\commands\migrations;
use mako\application\commands\migrations\Command;
use mako\application\commands\migrations\RollbackTrait;
/**
* Command that rolls back the last batch of migrations.
*
* @author Frederic G. Østby
*/
class Down extends Command
{
use RollbackTrait;
/**
* Command information.
*
* @var array
*/
protected $commandInformation =
[
'description' => 'Rolls back the last batch of migrations.',
'arguments' => [],
'options' =>
[
'batches' =>
[
'optional' => true,
'description' => 'Number of batches to roll back'
],
],
];
/**
* Executes the command.
*
* @access public
* @param string $batches Number of batches to roll back
*/
public function execute($batches = 1)
{
$this->rollback($batches);
}
} | <?php
/**
* @copyright Frederic G. Østby
* @license http://www.makoframework.com/license
*/
namespace mako\application\commands\migrations;
use mako\application\commands\migrations\Command;
use mako\application\commands\migrations\RollbackTrait;
/**
* Command that rolls back the last batch of migrations.
*
* @author Frederic G. Østby
*/
class Down extends Command
{
use RollbackTrait;
/**
* Command information.
*
* @var array
*/
protected $commandInformation =
[
'description' => 'Rolls back the last batch of migrations.',
'arguments' =>
[
'batches' =>
[
'optional' => true,
'description' => 'Number of batches to roll back'
],
],
'options' => [],
];
/**
* Executes the command.
*
* @access public
* @param string $arg2 Number of batches to roll back
*/
public function execute($arg2 = 1)
{
$this->rollback($arg2);
}
} |
Fix inverted coordinate bug in Compass .PLT Parser example script | #!/usr/bin/env python
import sys
import networkx as nx
from matplotlib import pyplot
from davies.compass.plt import CompassPltParser
def pltparser(pltfilename):
parser = CompassPltParser(pltfilename)
plt = parser.parse()
g = nx.Graph()
pos = {}
ele = {}
for segment in plt:
prev = None
for cmd in segment:
pos[cmd.name] = (cmd.x, cmd.y)
ele[cmd.name] = cmd.z
if not prev or cmd.cmd == 'M':
prev = cmd # move
continue
g.add_edge(prev.name, cmd.name)
prev = cmd
pyplot.figure().suptitle(plt.name, fontweight='bold')
colors = [ele[n] for n in g]
nx.draw(g, pos, node_color=colors, vmin=min(colors), vmax=max(colors), with_labels=True, node_size=15)
pyplot.show()
if __name__ == '__main__':
pltparser(sys.argv[1])
| #!/usr/bin/env python
import sys
import networkx as nx
from matplotlib import pyplot
from davies.compass.plt import CompassPltParser
def pltparser(pltfilename):
parser = CompassPltParser(pltfilename)
plt = parser.parse()
g = nx.Graph()
pos = {}
ele = {}
for segment in plt:
prev = None
for cmd in segment:
pos[cmd.name] = (-cmd.x, cmd.y)
ele[cmd.name] = cmd.z
if not prev or cmd.cmd == 'M':
prev = cmd # move
continue
g.add_edge(prev.name, cmd.name)
prev = cmd
pyplot.figure().suptitle(plt.name, fontweight='bold')
colors = [ele[n] for n in g]
nx.draw(g, pos, node_color=colors, vmin=min(colors), vmax=max(colors), with_labels=False, node_size=15)
pyplot.show()
if __name__ == '__main__':
pltparser(sys.argv[1])
|
Clarify AfterEach execution flow (naming) | package com.greghaskins.spectrum;
import com.greghaskins.spectrum.Spectrum.Block;
import java.util.ArrayList;
import java.util.List;
class AfterEachBlock implements Block {
private final List<Block> blocks;
public AfterEachBlock() {
this.blocks = new ArrayList<>();
}
@Override
public void run() throws Throwable {
runRemainingBlocksInReverseOrder(this.blocks.size() - 1);
}
private void runRemainingBlocksInReverseOrder(final int currentIndex) throws Throwable {
if (currentIndex < 0) {
return;
}
try {
this.blocks.get(currentIndex).run();
} finally {
runRemainingBlocksInReverseOrder(currentIndex - 1);
}
}
public void addBlock(final Block block) {
this.blocks.add(block);
}
}
| package com.greghaskins.spectrum;
import com.greghaskins.spectrum.Spectrum.Block;
import java.util.ArrayList;
import java.util.List;
class AfterEachBlock implements Block {
private final List<Block> blocks;
public AfterEachBlock() {
this.blocks = new ArrayList<>();
}
@Override
public void run() throws Throwable {
runAllBlocksInReverseOrder(this.blocks.size() - 1);
}
private void runAllBlocksInReverseOrder(final int index) throws Throwable {
if (index < 0) {
return;
}
try {
this.blocks.get(index).run();
} finally {
runAllBlocksInReverseOrder(index - 1);
}
}
public void addBlock(final Block block) {
this.blocks.add(block);
}
}
|
Fix typo in form (Submit button, label -> value) | <?php
namespace CdliTwoStageSignup\Form;
use Zend\Form\Form,
Zend\Form\Element\Csrf,
ZfcUser\Mapper\UserInterface as UserMapper,
ZfcBase\Form\ProvidesEventsForm;
class EmailVerification extends ProvidesEventsForm
{
public function __construct()
{
parent::__construct();
$this->add(array(
'name' => 'email',
'attributes' => array(
'label' => 'Email Address',
'type' => 'text',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'value' => 'Verify Email Address',
'type' => 'submit',
),
));
$this->add(new Csrf('csrf'));
$this->events()->trigger('init', $this);
}
}
| <?php
namespace CdliTwoStageSignup\Form;
use Zend\Form\Form,
Zend\Form\Element\Csrf,
ZfcUser\Mapper\UserInterface as UserMapper,
ZfcBase\Form\ProvidesEventsForm;
class EmailVerification extends ProvidesEventsForm
{
public function __construct()
{
parent::__construct();
$this->add(array(
'name' => 'email',
'attributes' => array(
'label' => 'Email Address',
'type' => 'text',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'label' => 'Verify Email Address',
'type' => 'submit',
),
));
$this->add(new Csrf('csrf'));
$this->events()->trigger('init', $this);
}
}
|
Fix duplicated classnames being applied to list items | import React, {PropTypes} from 'react';
import Util from '../Util/Util';
const CSSTransitionGroup = React.addons.CSSTransitionGroup;
export default class ListItem extends React.Component {
render() {
let Tag = this.props.tag;
// Uses all passed properties as attributes, excluding propTypes
let attributes = Util.exclude(this.props, Object.keys(ListItem.propTypes)) || {};
if (attributes.transition) {
return (
<CSSTransitionGroup
{...attributes}
className={this.props.className}
component={this.props.tag}>
{this.props.children}
</CSSTransitionGroup>
);
}
return (
<Tag {...attributes} className={this.props.className}>
{this.props.children}
</Tag>
);
}
}
ListItem.defaultProps = {
className: 'list-item',
tag: 'li'
};
ListItem.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
tag: PropTypes.string
};
| import classNames from 'classnames';
import React, {PropTypes} from 'react';
import Util from '../Util/Util';
const CSSTransitionGroup = React.addons.CSSTransitionGroup;
export default class ListItem extends React.Component {
render() {
let defaultClass = ListItem.defaultProps.className;
let classes = classNames(this.props.className, defaultClass);
let Tag = this.props.tag;
// Uses all passed properties as attributes, excluding propTypes
let attributes = Util.exclude(this.props, Object.keys(ListItem.propTypes)) || {};
if (attributes.transition) {
return (
<CSSTransitionGroup
{...attributes}
className={classes}
component={this.props.tag}>
{this.props.children}
</CSSTransitionGroup>
);
}
return (
<Tag {...attributes} className={classes}>
{this.props.children}
</Tag>
);
}
}
ListItem.defaultProps = {
className: 'list-item',
tag: 'li'
};
ListItem.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
tag: PropTypes.string
};
|
Make the paths not relative, so tests can be run from anywhere. | # -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), tests_path))
json_files = [f for f in os.listdir(path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
| # -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
json_files = [f for f in os.listdir(tests_path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(tests_path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
|
Fix an import error. pylons.config doesn't exist anymore, use pylons.configuration | """Base objects to be exported for use in Controllers"""
from paste.registry import StackedObjectProxy
from pylons.configuration import config
__all__ = ['app_globals', 'c', 'cache', 'config', 'g', 'request', 'response',
'session', 'tmpl_context', 'url']
def __figure_version():
try:
from pkg_resources import require
import os
# NOTE: this only works when the package is either installed,
# or has an .egg-info directory present (i.e. wont work with raw
# SVN checkout)
info = require('pylons')[0]
if os.path.dirname(os.path.dirname(__file__)) == info.location:
return info.version
else:
return '(not installed)'
except:
return '(not installed)'
__version__ = __figure_version()
app_globals = g = StackedObjectProxy(name="app_globals")
cache = StackedObjectProxy(name="cache")
request = StackedObjectProxy(name="request")
response = StackedObjectProxy(name="response")
session = StackedObjectProxy(name="session")
tmpl_context = c = StackedObjectProxy(name="tmpl_context or C")
url = StackedObjectProxy(name="url")
translator = StackedObjectProxy(name="translator")
| """Base objects to be exported for use in Controllers"""
from paste.registry import StackedObjectProxy
from pylons.config import config
__all__ = ['app_globals', 'c', 'cache', 'config', 'g', 'request', 'response',
'session', 'tmpl_context', 'url']
def __figure_version():
try:
from pkg_resources import require
import os
# NOTE: this only works when the package is either installed,
# or has an .egg-info directory present (i.e. wont work with raw
# SVN checkout)
info = require('pylons')[0]
if os.path.dirname(os.path.dirname(__file__)) == info.location:
return info.version
else:
return '(not installed)'
except:
return '(not installed)'
__version__ = __figure_version()
app_globals = g = StackedObjectProxy(name="app_globals")
cache = StackedObjectProxy(name="cache")
request = StackedObjectProxy(name="request")
response = StackedObjectProxy(name="response")
session = StackedObjectProxy(name="session")
tmpl_context = c = StackedObjectProxy(name="tmpl_context or C")
url = StackedObjectProxy(name="url")
translator = StackedObjectProxy(name="translator")
|
Add error handler for express | import express from 'express';
import handleRoutes from './handle-routes';
import config from './commons/config';
import connectDb from './commons/db';
const app = express();
handleRoutes(app);
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something failed!' });
next();
});
// app.start = () => {
// return connectDb()
// .then(() => {
// app.listen(config.app.port, config.app.host, () => {
// console.log(`Example app listening on http://${config.app.host}:${config.app.port}!`);
// });
// })
// .catch(() => process.exit());
// }
connectDb()
.then(() => {
app.listen(config.app.port, config.app.host, () => {
console.log(`Example app listening on http://${config.app.host}:${config.app.port}!`);
app.emit('started');
});
})
.catch(() => process.exit());
export default app;
| import express from 'express';
import handleRoutes from './handle-routes';
import config from './commons/config';
import connectDb from './commons/db';
const app = express();
handleRoutes(app);
// app.start = () => {
// return connectDb()
// .then(() => {
// app.listen(config.app.port, config.app.host, () => {
// console.log(`Example app listening on http://${config.app.host}:${config.app.port}!`);
// });
// })
// .catch(() => process.exit());
// }
connectDb()
.then(() => {
app.listen(config.app.port, config.app.host, () => {
console.log(`Example app listening on http://${config.app.host}:${config.app.port}!`);
app.emit('started');
});
})
.catch(() => process.exit());
export default app;
|
Allow TestAgent pass a CA to request |
/**
* Module dependencies.
*/
var Agent = require('superagent').agent
, methods = require('methods')
, http = require('http')
, Test = require('./test');
/**
* Expose `Agent`.
*/
module.exports = TestAgent;
/**
* Initialize a new `TestAgent`.
*
* @param {Function|Server} app
* @param {Object} options
* @api public
*/
function TestAgent(app, options){
if (!(this instanceof TestAgent)) return new TestAgent(app, options);
if ('function' == typeof app) app = http.createServer(app);
if (options) this._ca = options.ca;
Agent.call(this);
this.app = app;
}
/**
* Inherits from `Agent.prototype`.
*/
TestAgent.prototype.__proto__ = Agent.prototype;
// override HTTP verb methods
methods.forEach(function(method){
TestAgent.prototype[method] = function(url, fn){
var req = new Test(this.app, method.toUpperCase(), url);
req.ca(this._ca);
req.on('response', this.saveCookies.bind(this));
req.on('redirect', this.saveCookies.bind(this));
req.on('redirect', this.attachCookies.bind(this, req));
this.attachCookies(req);
return req;
};
});
TestAgent.prototype.del = TestAgent.prototype.delete;
|
/**
* Module dependencies.
*/
var Agent = require('superagent').agent
, methods = require('methods')
, http = require('http')
, Test = require('./test');
/**
* Expose `Agent`.
*/
module.exports = TestAgent;
/**
* Initialize a new `TestAgent`.
*
* @param {Function|Server} app
* @api public
*/
function TestAgent(app){
if (!(this instanceof TestAgent)) return new TestAgent(app);
if ('function' == typeof app) app = http.createServer(app);
Agent.call(this);
this.app = app;
}
/**
* Inherits from `Agent.prototype`.
*/
TestAgent.prototype.__proto__ = Agent.prototype;
// override HTTP verb methods
methods.forEach(function(method){
TestAgent.prototype[method] = function(url, fn){
var req = new Test(this.app, method.toUpperCase(), url);
req.on('response', this.saveCookies.bind(this));
req.on('redirect', this.saveCookies.bind(this));
req.on('redirect', this.attachCookies.bind(this, req));
this.attachCookies(req);
return req;
};
});
TestAgent.prototype.del = TestAgent.prototype.delete;
|
Solve 1000 digit fib number | '''
Problem 025
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
Solution: Copyright 2017 Dave Cuthbert, MIT License
'''
def gen_fibonacci():
term_1 = 1
term_2 = 1
while True:
next_term = term_1 + term_2
yield next_term
term_2 = term_1
term_1 = next_term
def solve_problem():
get_fibonacci = gen_fibonacci()
count = 3 # Not starting with first term in sequence
while True:
current_fib = next(get_fibonacci)
if len(str(current_fib)) >= 1000:
return(count)
count +=1
if __name__ == "__main__":
print(solve_problem())
| '''
Problem 025
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
Solution: Copyright 2017 Dave Cuthbert, MIT License
'''
def gen_fibonacci():
term_1 = 1
term_2 = 1
while True:
next_term = term_1 + term_2
yield next
term_2 = term_1
term_1 = next_term
def solve_problem():
get_fibonacci = gen_fibonacci
for i in range(10):
print(next(get_fibonacci))
return("DONE")
if __name__ == "__main__":
print(solve_problem())
|
Add example for werkzeug middleware installation. | from sling import Application
from sling.core.logger import logger
from sling.ext import hello
import localmodule
app = Application([
hello,
])
# Other way of installing a module
app.add_module(localmodule)
# Install a Falcon middleware
class HelloMiddleware(object):
def process_request(self, req, res):
logger.info('hellomiddleware processing request...')
def process_resource(self, req, res, resource):
logger.info('hellomiddleware processing resource...')
def process_response(self, req, res, resource):
logger.info('hellomiddleware processing response...')
app.add_middleware(HelloMiddleware)
# Install a standard WSGI Middleware
from werkzeug.contrib.profiler import ProfilerMiddleware
app.add_wsgi_middleware(ProfilerMiddleware, sort_by=('cumtime',), restrictions=('/opt', 30))
# Install werkzeug debugger
from werkzeug.debug import DebuggedApplication
app.add_wsgi_middleware(DebuggedApplication, evalex=True)
wsgi = app.wsgi
if __name__ == '__main__':
app.manage()
| from sling import Application
from sling.core.logger import logger
from sling.ext import hello
import localmodule
app = Application([
hello,
])
# Other way of installing a module
app.add_module(localmodule)
# Install a Falcon middleware
class HelloMiddleware(object):
def process_request(self, req, res):
logger.info('hellomiddleware processing request...')
def process_resource(self, req, res, resource):
logger.info('hellomiddleware processing resource...')
def process_response(self, req, res, resource):
logger.info('hellomiddleware processing response...')
app.add_middleware(HelloMiddleware)
# Install a standard WSGI Middleware
from werkzeug.contrib.profiler import ProfilerMiddleware
app.add_wsgi_middleware(
ProfilerMiddleware, sort_by=('cumtime',), restrictions=('/opt', 30))
wsgi = app.wsgi
if __name__ == '__main__':
app.manage()
|
Make canUndo true because @jaredlll08 told me to. | package joshie.harvest.plugins.crafttweaker;
import minetweaker.IUndoableAction;
import minetweaker.api.item.IIngredient;
import minetweaker.api.oredict.IOreDictEntry;
import net.minecraft.item.ItemStack;
public abstract class BaseUndoable implements IUndoableAction {
private boolean applied;
@Override
public boolean canUndo() {
return true;
}
@Override
public void undo() {}
public abstract String getDescription();
@Override
public void apply() {
if (!applied) {
applied = true;
applyOnce();
}
}
public abstract void applyOnce();
@Override
public String describe() {
return "[Harvest Festival] " + getDescription();
}
@Override
public String describeUndo() {
return "";
}
@Override
public Object getOverrideKey() {
return null;
}
//Helpers
public static ItemStack asStack(IIngredient ingredient) {
return ingredient.getInternal() instanceof ItemStack ? (ItemStack) ingredient.getInternal() : null;
}
public static String asOre(IIngredient ingredient) {
return ingredient.getInternal() instanceof IOreDictEntry ? ((IOreDictEntry) ingredient).getName() : null;
}
}
| package joshie.harvest.plugins.crafttweaker;
import minetweaker.IUndoableAction;
import minetweaker.api.item.IIngredient;
import minetweaker.api.oredict.IOreDictEntry;
import net.minecraft.item.ItemStack;
public abstract class BaseUndoable implements IUndoableAction {
private boolean applied;
@Override
public boolean canUndo() {
return false;
}
@Override
public void undo() {}
public abstract String getDescription();
@Override
public void apply() {
if (!applied) {
applied = true;
applyOnce();
}
}
public abstract void applyOnce();
@Override
public String describe() {
return "[Harvest Festival] " + getDescription();
}
@Override
public String describeUndo() {
return "";
}
@Override
public Object getOverrideKey() {
return null;
}
//Helpers
public static ItemStack asStack(IIngredient ingredient) {
return ingredient.getInternal() instanceof ItemStack ? (ItemStack) ingredient.getInternal() : null;
}
public static String asOre(IIngredient ingredient) {
return ingredient.getInternal() instanceof IOreDictEntry ? ((IOreDictEntry) ingredient).getName() : null;
}
}
|
Split system import and project import | import time
from chainer.training import extension
def observe_value(key, target_func):
"""Returns a trainer extension to continuously record a value.
Args:
key (str): Key of observation to record.
target_func (function): Function that returns the value to record.
It must take one argument: trainer object.
Returns:
The extension function.
"""
@extension.make_extension(
trigger=(1, 'epoch'), priority=extension.PRIORITY_WRITER)
def _observe_value(trainer):
trainer.observation[key] = target_func(trainer)
return _observe_value
def observe_time(key='time'):
"""Returns a trainer extension to record the elapsed time.
Args:
key (str): Key of observation to record.
Returns:
The extension function.
"""
start_time = time.time()
return observe_value(key, lambda _: time.time() - start_time)
def observe_lr(optimizer, key='lr'):
"""Returns a trainer extension to record the learning rate.
Args:
optimizer: Optimizer object whose learning rate is recorded.
key (str): Key of observation to record.
Returns:
The extension function.
"""
return observe_value(key, lambda _: optimizer.lr)
| from chainer.training import extension
import time
def observe_value(key, target_func):
"""Returns a trainer extension to continuously record a value.
Args:
key (str): Key of observation to record.
target_func (function): Function that returns the value to record.
It must take one argument: trainer object.
Returns:
The extension function.
"""
@extension.make_extension(
trigger=(1, 'epoch'), priority=extension.PRIORITY_WRITER)
def _observe_value(trainer):
trainer.observation[key] = target_func(trainer)
return _observe_value
def observe_time(key='time'):
"""Returns a trainer extension to record the elapsed time.
Args:
key (str): Key of observation to record.
Returns:
The extension function.
"""
start_time = time.time()
return observe_value(key, lambda _: time.time() - start_time)
def observe_lr(optimizer, key='lr'):
"""Returns a trainer extension to record the learning rate.
Args:
optimizer: Optimizer object whose learning rate is recorded.
key (str): Key of observation to record.
Returns:
The extension function.
"""
return observe_value(key, lambda _: optimizer.lr)
|
Fix tests for Python 3 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
import types
from rakuten_ws.webservice import RakutenWebService
from rakuten_ws.base import RakutenAPIResponse
@pytest.mark.online
def test_response(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
assert isinstance(response, RakutenAPIResponse)
@pytest.mark.online
def test_single_item(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
item = response['Items'][0]
assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa
@pytest.mark.online
def test_item_pages(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
items = response.pages()
# search should also allow to retrieve all the available responses
# within a generator
assert isinstance(items, types.GeneratorType)
# The iteration should switch to the next page
assert next(items)['page'] == 1
assert next(items)['page'] == 2
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
import types
from rakuten_ws.webservice import RakutenWebService
from rakuten_ws.base import RakutenAPIResponse
@pytest.mark.online
def test_response(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
assert isinstance(response, RakutenAPIResponse)
@pytest.mark.online
def test_single_item(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
item = response['Items'][0]
assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa
@pytest.mark.online
def test_item_pages(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
items = response.pages()
# search should also allow to retrieve all the available responses
# within a generator
assert isinstance(items, types.GeneratorType)
# The iteration should switch to the next page
assert items.next()['page'] == 1
assert items.next()['page'] == 2
|
Fix name for extra arguments | #!/usr/bin/env python
from setuptools import setup
version = '0.6.0.dev'
required = open('requirements.txt').read().split('\n')
extra = {'all': ['mist', 'rime']}
setup(
name='thunder-python',
version=version,
description='large-scale image and time series analysis',
author='freeman-lab',
author_email='the.freeman.lab@gmail.com',
url='https://github.com/thunder-project/thunder',
packages=[
'thunder',
'thunder',
'thunder.blocks',
'thunder.series',
'thunder.images'
],
package_data={'thunder.lib': ['thunder_python-' + version + '-py2.7.egg']},
install_requires=required,
extras_require=extra,
long_description='See https://github.com/thunder-project/thunder'
)
| #!/usr/bin/env python
from setuptools import setup
version = '0.6.0.dev'
required = open('requirements.txt').read().split('\n')
extra = {'all': ['mist', 'rime']}
setup(
name='thunder-python',
version=version,
description='large-scale image and time series analysis',
author='freeman-lab',
author_email='the.freeman.lab@gmail.com',
url='https://github.com/thunder-project/thunder',
packages=[
'thunder',
'thunder',
'thunder.blocks',
'thunder.series',
'thunder.images'
],
package_data={'thunder.lib': ['thunder_python-' + version + '-py2.7.egg']},
install_requires=required,
extra_requires=extra,
long_description='See https://github.com/thunder-project/thunder'
)
|
Change camelCasing strategy for `target_age` and `target_group` | from hvad.contrib.restframework import TranslatableModelSerializer
from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import Category, TargetGroup, TargetAge, Event
from pagoeta.apps.core.functions import get_absolute_uri
from pagoeta.apps.places.serializers import PlaceListSerializer
class TypeField(serializers.RelatedField):
def to_representation(self, value):
return {
'code': value.code,
'name': value.name
}
class EventSerializer(TranslatableModelSerializer):
category = TypeField(read_only=True)
place = PlaceListSerializer(read_only=True)
# camelCase some field names
targetGroup = TypeField(source='target_group', read_only=True)
targetAge = TypeField(source='target_age', read_only=True)
startAt = serializers.DateTimeField(source='start_at', read_only=True)
endAt = serializers.DateTimeField(source='end_at', read_only=True)
isFeatured = serializers.BooleanField(source='is_featured', read_only=True)
isVisible = serializers.BooleanField(source='is_visible', read_only=True)
href = serializers.SerializerMethodField()
class Meta(object):
model = Event
exclude = ('target_group', 'target_age', 'start_at', 'end_at', 'is_featured', 'is_visible', 'language_code')
def get_href(self, obj):
return get_absolute_uri(reverse('v1:event-detail', [obj.id]))
| from hvad.contrib.restframework import TranslatableModelSerializer
from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import Category, TargetGroup, TargetAge, Event
from pagoeta.apps.core.functions import get_absolute_uri
from pagoeta.apps.places.serializers import PlaceListSerializer
class TypeField(serializers.RelatedField):
def to_representation(self, value):
return {
'code': value.code,
'name': value.name
}
class EventSerializer(TranslatableModelSerializer):
category = TypeField(read_only=True)
target_group = TypeField(read_only=True)
targetGroup = target_group
target_age = TypeField(read_only=True)
targetAge = target_age
place = PlaceListSerializer(read_only=True)
# camelCase some field names
startAt = serializers.DateTimeField(source='start_at', read_only=True)
endAt = serializers.DateTimeField(source='end_at', read_only=True)
isFeatured = serializers.BooleanField(source='is_featured', read_only=True)
isVisible = serializers.BooleanField(source='is_visible', read_only=True)
href = serializers.SerializerMethodField()
class Meta(object):
model = Event
exclude = ('start_at', 'end_at', 'is_featured', 'is_visible', 'language_code')
def get_href(self, obj):
return get_absolute_uri(reverse('v1:event-detail', [obj.id]))
|
[IMPROVED] Debug logging for purgeArchive calls | #!/usr/bin/php
<?php
/*
Copyright:: 2013, Sebastian Grewe
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.
*/
// Change to working directory
chdir(dirname(__FILE__));
// Include all settings and classes
require_once('shared.inc.php');
// If we don't keep archives, delete some now to release disk space
if (!$affected_rows = $share->purgeArchive()) {
$log->logError("Failed to delete archived shares, not critical but should be checked: " . $share->getCronError());
$monitoring->endCronjob($cron_name, 'E0008', 1, true);
} else {
$log->logDebug("Deleted $affected_rows archived shares this run");
}
// Cron cleanup and monitoring
require_once('cron_end.inc.php');
?>
| #!/usr/bin/php
<?php
/*
Copyright:: 2013, Sebastian Grewe
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.
*/
// Change to working directory
chdir(dirname(__FILE__));
// Include all settings and classes
require_once('shared.inc.php');
// If we don't keep archives, delete some now to release disk space
if (!$share->purgeArchive()) {
$log->logError("Failed to delete archived shares, not critical but should be checked: " . $share->getCronError());
$monitoring->endCronjob($cron_name, 'E0008', 1, true);
}
// Cron cleanup and monitoring
require_once('cron_end.inc.php');
?>
|
Allow Herald rules to apply "only the first time" to Calendar events
Summary: Fixes T12821. (Some events only happen once, so the default behavior doesn't let you pick this rule, and objects must opt into it by saying "yeah, I support multiple edits".)
Test Plan:
Note "only the first time" selected:
{F4999093}
Reviewers: chad
Reviewed By: chad
Maniphest Tasks: T12821
Differential Revision: https://secure.phabricator.com/D18117 | <?php
final class PhabricatorCalendarEventHeraldAdapter extends HeraldAdapter {
private $object;
public function getAdapterApplicationClass() {
return 'PhabricatorCalendarApplication';
}
public function getAdapterContentDescription() {
return pht('React to events being created or updated.');
}
protected function newObject() {
return new PhabricatorCalendarEvent();
}
public function isTestAdapterForObject($object) {
return ($object instanceof PhabricatorCalendarEvent);
}
public function getAdapterTestDescription() {
return pht(
'Test rules which run when an event is created or updated.');
}
public function setObject($object) {
$this->object = $object;
return $this;
}
public function getObject() {
return $this->object;
}
public function getAdapterContentName() {
return pht('Calendar Events');
}
public function supportsRuleType($rule_type) {
switch ($rule_type) {
case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL:
case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL:
return true;
case HeraldRuleTypeConfig::RULE_TYPE_OBJECT:
default:
return false;
}
}
public function getRepetitionOptions() {
return array(
HeraldRepetitionPolicyConfig::EVERY,
HeraldRepetitionPolicyConfig::FIRST,
);
}
public function getHeraldName() {
return $this->getObject()->getMonogram();
}
}
| <?php
final class PhabricatorCalendarEventHeraldAdapter extends HeraldAdapter {
private $object;
public function getAdapterApplicationClass() {
return 'PhabricatorCalendarApplication';
}
public function getAdapterContentDescription() {
return pht('React to events being created or updated.');
}
protected function newObject() {
return new PhabricatorCalendarEvent();
}
public function isTestAdapterForObject($object) {
return ($object instanceof PhabricatorCalendarEvent);
}
public function getAdapterTestDescription() {
return pht(
'Test rules which run when an event is created or updated.');
}
public function setObject($object) {
$this->object = $object;
return $this;
}
public function getObject() {
return $this->object;
}
public function getAdapterContentName() {
return pht('Calendar Events');
}
public function supportsRuleType($rule_type) {
switch ($rule_type) {
case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL:
case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL:
return true;
case HeraldRuleTypeConfig::RULE_TYPE_OBJECT:
default:
return false;
}
}
public function getHeraldName() {
return $this->getObject()->getMonogram();
}
}
|
Make print_filelist sort the list before printing | import click
def print_message(message):
print message
def print_filelist(header, filelist, colour=None):
click.echo(header)
for line in sorted(filelist):
if colour:
line = click.style(line, fg=colour)
click.echo(" {}".format(line))
def print_filelists(new_files, changed_files, missing_files):
if not any([new_files, changed_files, missing_files]):
print_message("Index is up-to-date (no changes)")
return
if new_files:
print_filelist("Added files (not in index):", new_files, 'green')
# Print a blank space between sections
if changed_files or missing_files:
click.echo()
if changed_files:
print_filelist("Changed files (hash differs from index):", changed_files, 'red')
# Print a blank space between sections
if missing_files:
click.echo()
if missing_files:
print_filelist("Missing files:", missing_files, 'red')
| import click
def print_message(message):
print message
def print_filelist(header, filelist, colour=None):
click.echo(header)
for line in filelist:
if colour:
line = click.style(line, fg=colour)
click.echo(" {}".format(line))
def print_filelists(new_files, changed_files, missing_files):
if not any([new_files, changed_files, missing_files]):
print_message("Index is up-to-date (no changes)")
return
if new_files:
print_filelist("Added files (not in index):", new_files, 'green')
# Print a blank space between sections
if changed_files or missing_files:
click.echo()
if changed_files:
print_filelist("Changed files (hash differs from index):", changed_files, 'red')
# Print a blank space between sections
if missing_files:
click.echo()
if missing_files:
print_filelist("Missing files:", missing_files, 'red')
|
Tag updated and download link added | import os
from setuptools import setup
from setuptools import find_packages
setup(
name='MobOff',
version='0.2',
py_modules=['moboff'],
packages=find_packages(),
description = 'Download youtube music and send to devices',
author = 'Parth Verma',
author_email = 'vermaparth97@gmail.com',
url = "https://github.com/parth-vader/MobOff",
download_url = 'https://codeload.github.com/Parth-Vader/MobOff/tar.gz/0.2'
license = "MIT License",
install_requires=[
'pushbullet.py',
'youtube_dl',
'Click',
],
entry_points='''
[console_scripts]
moboff=mainscript:cli
''',
)
os.system('chmod a+x mainscript.py')
os.system('export PATH=mainscript.py:$PATH')
| import os
from setuptools import setup
from setuptools import find_packages
setup(
name='MobOff',
version='0.1',
py_modules=['moboff'],
packages=find_packages(),
description = 'Download youtube music and send to devices',
author = 'Parth Verma',
author_email = 'vermaparth97@gmail.com',
url = "https://github.com/parth-vader/MobOff",
license = "MIT License",
install_requires=[
'pushbullet.py',
'youtube_dl',
'Click',
],
entry_points='''
[console_scripts]
moboff=mainscript:cli
''',
)
os.system('chmod a+x mainscript.py')
os.system('export PATH=mainscript.py:$PATH')
|
Indent Gist file name with '»' character | package com.github.mobile.android.gist;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.github.mobile.android.R.layout;
import org.eclipse.egit.github.core.GistFile;
/**
* Adapter for viewing the files in a Gist
*/
public class GistFileListAdapter extends ArrayAdapter<GistFile> {
private final Activity activity;
/**
* Create adapter for files
*
* @param activity
* @param files
*/
public GistFileListAdapter(Activity activity, GistFile[] files) {
super(activity, layout.gist_view_file_item, files);
this.activity = activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final TextView view = (TextView) activity.getLayoutInflater().inflate(layout.gist_view_file_item, null);
view.setText("» " + getItem(position).getFilename());
return view;
}
}
| package com.github.mobile.android.gist;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.github.mobile.android.R;
import org.eclipse.egit.github.core.GistFile;
/**
* Adapter for viewing the files in a Gist
*/
public class GistFileListAdapter extends ArrayAdapter<GistFile> {
private final Activity activity;
/**
* Create adapter for files
*
* @param activity
* @param files
*/
public GistFileListAdapter(Activity activity, GistFile[] files) {
super(activity, R.layout.gist_view_file_item, files);
this.activity = activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final GistFile file = getItem(position);
final TextView view = (TextView) activity.getLayoutInflater().inflate(R.layout.gist_view_file_item, null);
view.setText(file.getFilename());
return view;
}
}
|
Remove leftover line in solution for 01_keras | model = Sequential()
model.add(Dense(hidden_dim, input_dim=input_dim,
activation="tanh"))
model.add(Dense(output_dim, activation="softmax"))
optimizer = optimizers.SGD(lr=0.1, momentum=0.9, nesterov=True)
model.compile(optimizer=optimizer, loss='categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(X_train, Y_train, validation_split=0.2,
epochs=15, batch_size=32)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(12, 6))
history_df = pd.DataFrame(history.history)
history_df["epoch"] = history.epoch
history_df.plot(x="epoch", y=["loss", "val_loss"], ax=ax0)
history_df.plot(x="epoch", y=["accuracy", "val_accuracy"], ax=ax1);
# Analysis:
#
# Setting the learning rate value to a small value (e.g. lr=0.001 on
# this dataset) makes the model train much slower (it has not
# converged yet after 15 epochs).
#
# Using momentum tends to mitigate the small learning rate / slow
# training problem a bit.
#
# Setting the learning rate to a very large value (e.g. lr=10)
# makes the model randomly bounce around a good local
# minimum and therefore prevent it to reach a low training loss even
# after 30 epochs.
| model = Sequential()
model.add(Dense(hidden_dim, input_dim=input_dim,
activation="tanh"))
model.add(Dense(output_dim, activation="softmax"))
model.add(Activation("softmax"))
optimizer = optimizers.SGD(lr=0.1, momentum=0.9, nesterov=True)
model.compile(optimizer=optimizer, loss='categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(X_train, Y_train, validation_split=0.2,
epochs=15, batch_size=32)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(12, 6))
history_df = pd.DataFrame(history.history)
history_df["epoch"] = history.epoch
history_df.plot(x="epoch", y=["loss", "val_loss"], ax=ax0)
history_df.plot(x="epoch", y=["accuracy", "val_accuracy"], ax=ax1);
# Analysis:
#
# Setting the learning rate value to a small value (e.g. lr=0.001 on
# this dataset) makes the model train much slower (it has not
# converged yet after 15 epochs).
#
# Using momentum tends to mitigate the small learning rate / slow
# training problem a bit.
#
# Setting the learning rate to a very large value (e.g. lr=10)
# makes the model randomly bounce around a good local
# minimum and therefore prevent it to reach a low training loss even
# after 30 epochs. |
Move KMS key retrieval to its own function. | 'use strict';
const AWS = require('aws-sdk');
const Err = require('./error');
const upload = require('multer')();
const rp = require('request-promise');
// Hit the Vault health check endpoint to see if we're actually working with a Vault server
/**
* Checks whether there is an actual Vault server running at the Vault endpoint
*
* @returns {Promise}
*/
const checkVault = function() {
const VAULT_ENDPOINT = Config.get('vault:endpoint');
return rp({uri: `${VAULT_ENDPOINT}/sys/health`, json: true})
.then(() => true)
.catch(() => false);
};
/**
* Gets a list of KMS keys and their aliases
*
* @returns {Promise}
*/
const getKmsKeys = function() {
const KMS = new AWS.KMS({region: Config.get('aws:region')});
if (Config.get('aws:key')) {
return Promise.resolve([]);
}
return new Promise((resolve, reject) => {
KMS.listAliases({}, (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
});
};
module.exports = function Index(app) {
app.get('/', function(req, res, next) {
}).catch((err) => {
next(err);
});
});
app.post('/v1/vault', upload.none(), require('./vault')());
app.post('/v1/kms', upload.none(), require('./kms')());
app.use(Err);
};
| 'use strict';
const AWS = require('aws-sdk');
const Err = require('./error');
const upload = require('multer')();
const rp = require('request-promise');
// Hit the Vault health check endpoint to see if we're actually working with a Vault server
/**
* Checks whether there is an actual Vault server running at the Vault endpoint
*
* @returns {Promise}
*/
const checkVault = function() {
const VAULT_ENDPOINT = Config.get('vault:endpoint');
return rp({uri: `${VAULT_ENDPOINT}/sys/health`, json: true})
.then(() => true)
.catch(() => false);
};
module.exports = function Index(app) {
app.get('/', function(req, res, next) {
const KMS = new AWS.KMS({region: Config.get('aws:region')});
if (Config.get('aws:key')) {
return res.render('index', {title: 'ACS'});
}
return new Promise((resolve, reject) => {
KMS.listAliases({}, (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
}).then((keys) => {
res.render('index', {title: 'ACS', kms: keys.Aliases});
}).catch((err) => {
next(err);
});
});
app.post('/v1/vault', upload.none(), require('./vault')());
app.post('/v1/kms', upload.none(), require('./kms')());
app.use(Err);
};
|
Add replace double quotation mark from configuration file parameters. | import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
| import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH']
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.