text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
:bug: Fix package data to include styles.css
# -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages IS_PY3 = sys.version_info > (3,) install_requires = [ 'jinja2', 'lxml', ] tests_require = [ ] extras_require = { 'test': tests_require, } description = "Library for building and paring Connexions' EPUBs." if not IS_PY3: tests_require.append('mock') setup( name='cnx-epub', version='0.8.0', author='Connexions team', author_email='info@cnx.org', url="https://github.com/connexions/cnx-epub", license='AGPL, See also LICENSE.txt', description=description, install_requires=install_requires, tests_require=tests_require, extras_require=extras_require, packages=find_packages(), include_package_data=True, entry_points={ 'console_scripts': [ 'cnx-epub-single_html = cnxepub.scripts.single_html.main:main', ], }, test_suite='cnxepub.tests', zip_safe=False, )
# -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages IS_PY3 = sys.version_info > (3,) install_requires = [ 'jinja2', 'lxml', ] tests_require = [ ] extras_require = { 'test': tests_require, } description = "Library for building and paring Connexions' EPUBs." if not IS_PY3: tests_require.append('mock') setup( name='cnx-epub', version='0.8.0', author='Connexions team', author_email='info@cnx.org', url="https://github.com/connexions/cnx-epub", license='AGPL, See also LICENSE.txt', description=description, install_requires=install_requires, tests_require=tests_require, extras_require=extras_require, packages=find_packages(), include_package_data=False, entry_points={ 'console_scripts': [ 'cnx-epub-single_html = cnxepub.scripts.single_html.main:main', ], }, test_suite='cnxepub.tests', zip_safe=False, )
Use https for lorempixel to avoid mixed-content security warnings
import Ember from 'ember'; import RSVP from 'rsvp'; import DS from 'ember-data'; import config from '../config/environment'; import buildQueryParamsMixin from 'wholetale/mixins/build-query-params'; export default DS.RESTAdapter.extend(buildQueryParamsMixin, { tokenHandler: Ember.inject.service("token-handler"), authRequest: Ember.inject.service(), host: config.apiHost, namespace: config.apiPath, primaryKey: "_id", query(store, type, query) { let url = this.buildURL(type.modelName, null, null, 'query', query); console.log("sending request for sils ... "); return new RSVP.Promise(resolve => resolve([{ _id: 1, _modelType: "sils", icon: "https://lorempixel.com/400/400/abstract/" }])); //TODO: uncomment this after sils endpoint working // return this.get('authRequest').send(url, {headers:{'content-type':'application/json'}}); }, urlForQuery(query, modelName) { let url = this._super(query, modelName); if (query) { query.w = query.w || config.taleIconWidth; query.h = query.h || config.taleIconHeight; let q = this.buildQueryParams(query); url += "?" + q; } return url; } });
import Ember from 'ember'; import RSVP from 'rsvp'; import DS from 'ember-data'; import config from '../config/environment'; import buildQueryParamsMixin from 'wholetale/mixins/build-query-params'; export default DS.RESTAdapter.extend(buildQueryParamsMixin, { tokenHandler: Ember.inject.service("token-handler"), authRequest: Ember.inject.service(), host: config.apiHost, namespace: config.apiPath, primaryKey: "_id", query(store, type, query) { let url = this.buildURL(type.modelName, null, null, 'query', query); console.log("sending request for sils ... "); return new RSVP.Promise(resolve => resolve([{ _id: 1, _modelType: "sils", icon: "http://lorempixel.com/400/400/abstract/" }])); //TODO: uncomment this after sils endpoint working // return this.get('authRequest').send(url, {headers:{'content-type':'application/json'}}); }, urlForQuery(query, modelName) { let url = this._super(query, modelName); if (query) { query.w = query.w || config.taleIconWidth; query.h = query.h || config.taleIconHeight; let q = this.buildQueryParams(query); url += "?" + q; } return url; } });
Fix typo in import statement
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.test.suitebuilder.TestSuiteBuilder; import junit.framework.Test; import junit.framework.TestSuite; public class FullTestSuite extends TestSuite { public static Test suite() { return new TestSuiteBuilder(FullTestSuite.class) .includeAllPackagesUnderHere().build(); } public FullTestSuite() { super(); } }
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import ndroid.test.suitebuilder.TestSuiteBuilder; import junit.framework.Test; import junit.framework.TestSuite; public class FullTestSuite extends TestSuite { public static Test suite() { return new TestSuiteBuilder(FullTestSuite.class) .includeAllPackagesUnderHere().build(); } public FullTestSuite() { super(); } }
Refactor odd even sort to reduce duplication
/** * @license * js-sorting <http://github.com/Tyriar/js-sorting> * Copyright 2014-2015 Daniel Imms <http://www.growingwiththeweb.com> * Released under the MIT license <http://github.com/Tyriar/js-sorting/blob/master/LICENSE> */ 'use strict'; var defaultCompare = require('./common/default-compare'); var defaultSwap = require('./common/default-swap'); function innerSort(array, i, compare, swap) { var sorted = true; for (; i < array.length - 1; i += 2) { if (compare(array[i], array[i + 1]) > 0) { swap(array, i, i + 1); sorted = false; } } return sorted; } function sort(array, compare, swap) { var sorted = false; while (!sorted) { sorted = innerSort(array, 1, compare, swap); sorted = sorted && innerSort(array, 0, compare, swap); } return array; } module.exports = function (array, customCompare, customSwap) { var compare = customCompare || defaultCompare; var swap = customSwap || defaultSwap; return sort(array, compare, swap); };
/** * @license * js-sorting <http://github.com/Tyriar/js-sorting> * Copyright 2014-2015 Daniel Imms <http://www.growingwiththeweb.com> * Released under the MIT license <http://github.com/Tyriar/js-sorting/blob/master/LICENSE> */ 'use strict'; var defaultCompare = require('./common/default-compare'); var defaultSwap = require('./common/default-swap'); function sort(array, compare, swap) { var i; var sorted = false; while(!sorted) { sorted = true; for (i = 1; i < array.length - 1; i += 2) { if (compare(array[i], array[i + 1]) > 0) { swap(array, i, i + 1); sorted = false; } } for (i = 0; i < array.length - 1; i += 2) { if (compare(array[i], array[i + 1]) > 0) { swap(array, i, i + 1); sorted = false; } } } return array; } module.exports = function (array, customCompare, customSwap) { var compare = customCompare || defaultCompare; var swap = customSwap || defaultSwap; return sort(array, compare, swap); };
Put data into alphabetical order
'use strict'; const Utils = require("../../util/utils"); module.exports = class FeatureList { constructor() { this.features = [] } add(properties, geometry) { let feature = { geometry: Utils.sortObject(geometry), properties: Utils.sortObject(properties), type: "Feature" }; this.features.push(feature); } getFeatures() { return this.features; } getFeatureCollection() { return { type: "FeatureCollection", features: this.features, }; } static createFromArray(array) { if (!array.hasOwnProperty("features")) { throw("Supplied JSON does not contain required property 'features'"); } let instance = new FeatureList(); let features = array.features; for (let i in features) { instance.add(features[i].properties, features[i].geometry) } return instance; } };
'use strict'; const Utils = require("../../util/utils"); module.exports = class FeatureList { constructor() { this.features = [] } add(properties, geometry) { let feature = { type: "Feature", geometry: Utils.sortObject(geometry), properties: Utils.sortObject(properties) }; this.features.push(feature); } getFeatures() { return this.features; } getFeatureCollection() { return { type: "FeatureCollection", features: this.features, }; } static createFromArray(array) { if (!array.hasOwnProperty("features")) { throw("Supplied JSON does not contain required property 'features'"); } let instance = new FeatureList(); let features = array.features; for (let i in features) { instance.add(features[i].properties, features[i].geometry) } return instance; } };
Add try/except in case select function fails
"""Export all responses from yesterday and save them to a .csv file.""" import sqlite3 import csv from datetime import datetime, timedelta import os today = str(datetime.now().strftime('%Y-%m-%d')) yesterday = str((datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')) export_directory = 'export' export_filename = 'srvy' + yesterday + '.csv' full_export_path = os.path.join(export_directory, export_filename) sqlite_file = 'srvy.db' table_name = 'responses' date_column = 'date' time_column = 'time' score_column = 'score' question_column = 'question' conn = sqlite3.connect(sqlite_file) c = conn.cursor() #c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'") try: c.execute("SELECT * FROM responses WHERE date = ?", (yesterday,)) csvWriter = csv.writer(open(full_export_path, 'w')) rows = c.fetchall() for row in rows: csvWriter.writerow(row) except: pass
"""Export all responses from yesterday and save them to a CSV file.""" import sqlite3 import csv from datetime import datetime, timedelta import os today = str(datetime.now().strftime('%Y-%m-%d')) yesterday = str((datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')) export_directory = 'export' export_filename = 'srvy' + yesterday + '.csv' full_export_path = os.path.join(export_directory, export_filename) sqlite_file = 'srvy.db' table_name = 'responses' date_column = 'date' time_column = 'time' score_column = 'score' question_column = 'question' conn = sqlite3.connect(sqlite_file) c = conn.cursor() #c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'") c.execute("SELECT * FROM responses WHERE date = ?", (yesterday,)) csvWriter = csv.writer(open(full_export_path, 'w')) rows = c.fetchall() for row in rows: csvWriter.writerow(row)
Remove empty lines in representative graph.
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. function VoteStatsGraph(selector, options) { this.selector = selector; this.options = options; } VoteStatsGraph.prototype.render = function() { this.chart = new Highcharts.Chart({ chart: { renderTo: this.selector, type: 'spline', backgroundColor: null }, credits: { enabled: false }, title: { text: this.options.title }, subtitle: { text: this.options.subtitle }, xAxis: { type: 'datetime', dateTimeLabelFormats: { month: '%Y-%m', year: '%b' } }, yAxis: { title: { text: '' }, labels: false, tickInterval: 1, }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%Y-%m-%d', this.x); } }, series: this.options.series }); };
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. function VoteStatsGraph(selector, options) { this.selector = selector; this.options = options; } VoteStatsGraph.prototype.render = function() { this.chart = new Highcharts.Chart({ chart: { renderTo: this.selector, type: 'spline', backgroundColor: null }, credits: { enabled: false }, title: { text: this.options.title }, subtitle: { text: this.options.subtitle }, xAxis: { type: 'datetime', dateTimeLabelFormats: { month: '%Y-%m', year: '%b' } }, yAxis: { title: { text: '' }, labels: false, }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%Y-%m-%d', this.x); } }, series: this.options.series }); };
Add check for the thumbnail in base64 (requests inter pods)
'use strict' const validator = require('validator') const constants = require('../initializers/constants') const customValidators = { eachIsRemoteVideosAddValid: eachIsRemoteVideosAddValid, eachIsRemoteVideosRemoveValid: eachIsRemoteVideosRemoveValid, isArray: isArray } function eachIsRemoteVideosAddValid (values) { return values.every(function (val) { return validator.isLength(val.name, 1, 50) && validator.isLength(val.description, 1, 50) && validator.isLength(val.magnetUri, 10) && validator.isURL(val.podUrl) && !isNaN(val.duration) && val.duration >= 0 && val.duration < constants.MAXIMUM_VIDEO_DURATION && validator.isLength(val.author, 1, constants.MAXIMUM_AUTHOR_LENGTH) && validator.isBase64(val.thumbnailBase64) && validator.isByteLength(val.thumbnailBase64, { min: 0, max: 20000 }) && validator.isDate(val.createdDate) }) } function eachIsRemoteVideosRemoveValid (values) { return values.every(function (val) { return validator.isLength(val.magnetUri, 10) }) } function isArray (value) { return Array.isArray(value) } // --------------------------------------------------------------------------- module.exports = customValidators
'use strict' const validator = require('validator') const constants = require('../initializers/constants') const customValidators = { eachIsRemoteVideosAddValid: eachIsRemoteVideosAddValid, eachIsRemoteVideosRemoveValid: eachIsRemoteVideosRemoveValid, isArray: isArray } function eachIsRemoteVideosAddValid (values) { return values.every(function (val) { return validator.isLength(val.name, 1, 50) && validator.isLength(val.description, 1, 50) && validator.isLength(val.magnetUri, 10) && validator.isURL(val.podUrl) && !isNaN(val.duration) && val.duration >= 0 && val.duration < constants.MAXIMUM_VIDEO_DURATION && validator.isLength(val.author, 1, constants.MAXIMUM_AUTHOR_LENGTH) && validator.isDate(val.createdDate) }) } function eachIsRemoteVideosRemoveValid (values) { return values.every(function (val) { return validator.isLength(val.magnetUri, 10) }) } function isArray (value) { return Array.isArray(value) } // --------------------------------------------------------------------------- module.exports = customValidators
Remove unneeded moment locales from bundle
/* eslint-disable no-var */ var autoprefixer = require('autoprefixer'); var path = require('path'); var webpack = require('webpack'); module.exports = { module: { loaders: [ { test: /\.png$/, loader: 'url?limit=100000&mimetype=image/png', }, { test: /\.gif$/, loader: 'url?limit=100000&mimetype=image/gif', }, { test: /\.jpg$/, loader: 'file', }, { test: /\.woff|\.woff2|\.svg|.eot|\.ttf/, loader: 'url?prefix=font/&limit=10000', }, ], }, postcss: [ autoprefixer({ browsers: ['last 2 version', 'ie 9'] }), ], resolve: { alias: { app: path.resolve(__dirname, '../app'), tests: path.resolve(__dirname, '../tests'), }, extensions: ['', '.js', '.json'], modulesDirectories: ['node_modules', 'app'], }, plugins: [ new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en|fi|sv/), ], };
/* eslint-disable no-var */ var autoprefixer = require('autoprefixer'); var path = require('path'); module.exports = { module: { loaders: [ { test: /\.png$/, loader: 'url?limit=100000&mimetype=image/png', }, { test: /\.gif$/, loader: 'url?limit=100000&mimetype=image/gif', }, { test: /\.jpg$/, loader: 'file', }, { test: /\.woff|\.woff2|\.svg|.eot|\.ttf/, loader: 'url?prefix=font/&limit=10000', }, ], }, postcss: [ autoprefixer({ browsers: ['last 2 version', 'ie 9'] }), ], resolve: { alias: { app: path.resolve(__dirname, '../app'), tests: path.resolve(__dirname, '../tests'), }, extensions: ['', '.js', '.json'], modulesDirectories: ['node_modules', 'app'], }, };
Add new meta field for healthy hearing, add id attribute to heading.
<?php /** * Single Re Google Review * * @package Google Review */ get_header(); $google_review = get_post_meta( $post->ID, 're-google-review-google-place-id', true ); $facebook_review = get_post_meta( $post->ID, 're-google-review-facebook', true ); $healthy_hearing_review = get_post_meta( $post->ID, 're-google-review-healthy-hearing', true ); ?> <div class="open-review"> <h2 id="review-heading">Use <span>Google</span><br>to leave your review?</h2> <a href="http://search.google.com/local/writereview?placeid=<?php echo esc_html( $google_review ); ?>" class="button"><?php esc_html_e( 'Yes', 'domain' ); ?></a> <?php if ( $facebook_review ) { ?> <p><?php esc_html_e( '- OR -', 'domain' ); ?></p> <a href="<?php echo esc_url( $facebook_review ); ?>" class="button"><?php esc_html_e( 'Facebook', 'domain' ); ?></a> <?php } ?> </div> <?php get_footer(); ?>
<?php /** * Single Re Google Review * * @package Google Review */ get_header(); $google_review = get_post_meta( $post->ID, 're-google-review-google-place-id', true ); $facebook_review = get_post_meta( $post->ID, 're-google-review-facebook', true ); ?> <div class="open-review"> <h2>Use <span>Google</span><br>to leave your review?</h2> <a href="http://search.google.com/local/writereview?placeid=<?php echo esc_html( $google_review ); ?>" class="button"><?php esc_html_e( 'Yes', 'domain' ); ?></a> <?php if ( $facebook_review ) { ?> <p><?php esc_html_e( '- OR -', 'domain' ); ?></p> <a href="<?php echo esc_url( $facebook_review ); ?>" class="button"><?php esc_html_e( 'Facebook', 'domain' ); ?></a> <?php } ?> </div> <?php get_footer(); ?>
Use PhanomJS instead of Chrome for testing (because: Travis-CI)
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['PhantomJS'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
Update documentation links to Django 1.9
# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its containing # directory. import os import sys sys.path.append(os.path.join(os.path.abspath('.'), '_ext')) sys.path.append(os.path.dirname(os.path.abspath('.'))) import analytical # -- General configuration -------------------------------------------------- project = u'django-analytical' copyright = u'2011, Joost Cassee <joost@cassee.net>' release = analytical.__version__ # The short X.Y version. version = release.rsplit('.', 1)[0] extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' add_function_parentheses = True pygments_style = 'sphinx' intersphinx_mapping = { 'http://docs.python.org/2.7': None, 'http://docs.djangoproject.com/en/1.9': 'http://docs.djangoproject.com/en/1.9/_objects/', } # -- Options for HTML output ------------------------------------------------ html_theme = 'default' htmlhelp_basename = 'analyticaldoc' # -- Options for LaTeX output ----------------------------------------------- latex_documents = [ ('index', 'django-analytical.tex', u'Documentation for django-analytical', u'Joost Cassee', 'manual'), ]
# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its containing # directory. import os import sys sys.path.append(os.path.join(os.path.abspath('.'), '_ext')) sys.path.append(os.path.dirname(os.path.abspath('.'))) import analytical # -- General configuration -------------------------------------------------- project = u'django-analytical' copyright = u'2011, Joost Cassee <joost@cassee.net>' release = analytical.__version__ # The short X.Y version. version = release.rsplit('.', 1)[0] extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' add_function_parentheses = True pygments_style = 'sphinx' intersphinx_mapping = { 'http://docs.python.org/2.7': None, 'http://docs.djangoproject.com/en/1.8': 'http://docs.djangoproject.com/en/1.8/_objects/', } # -- Options for HTML output ------------------------------------------------ html_theme = 'default' htmlhelp_basename = 'analyticaldoc' # -- Options for LaTeX output ----------------------------------------------- latex_documents = [ ('index', 'django-analytical.tex', u'Documentation for django-analytical', u'Joost Cassee', 'manual'), ]
Fix active menu item content.
const Handlebars = require('handlebars'); const templates = { active: Handlebars.compile('<li class="active"><a>{{{content}}}</a></li>'), unactive: Handlebars.compile('<li><a href="{{link}}">{{{content}}}</a></li>') }; module.exports = function(entries, current_page) { const items = entries.map((entry) => { const context = entry.page === '/' ? {content: '<i class="fa fa-home"></i>', link: '/'} : {content: entry.page, link: `/pages/${entry.page}.html`}; return entry.page === current_page ? templates.active(context) : templates.unactive(context); }).join(''); return `<ul class="menu">${items}</ul>`; }
const Handlebars = require('handlebars'); const templates = { active: Handlebars.compile('<li class="active">{{{content}}}</li>'), unactive: Handlebars.compile('<li><a href="{{link}}">{{{content}}}</a></li>') }; module.exports = function(entries, current_page) { const items = entries.map((entry) => { const context = entry.page === '/' ? {content: '<i class="fa fa-home"></i>', link: '/'} : {content: entry.page, link: `/pages/${entry.page}.html`}; return entry.page === current_page ? templates.active(context) : templates.unactive(context); }).join(''); return `<ul class="menu">${items}</ul>`; }
Change version to 0.3 due to functions changing name.
#!/usr/bin/env python from setuptools import setup setup(name = 'i2py', version = '0.3', description = 'Tools to work with i2p.', author = 'See contributors.txt', author_email = 'Anonymous', classifiers = [ 'Development Status :: 3 - Alpha', #'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Topic :: Utilities', ], install_requires = [ # If you plan on adding something, make it known why. # Let's try to keep the dependencies minimal, okay? 'bunch', # Needed by i2py.control.pyjsonrpc. 'python-geoip', # Needed by i2py.netdb. 'python-geoip-geolite2', # Needed by i2py.netdb. ], tests_require=['pytest'], url = 'https://github.com/chris-barry/i2py', packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'], )
#!/usr/bin/env python from setuptools import setup setup(name = 'i2py', version = '0.2', description = 'Tools to work with i2p.', author = 'contributors.txt', author_email = 'Anonymous', classifiers = [ 'Development Status :: 3 - Alpha', #'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Topic :: Utilities', ], install_requires = [ # If you plan on adding something, make it known why. # Let's try to keep the dependencies minimal, okay? 'bunch', # Needed by i2py.control.pyjsonrpc. 'python-geoip', # Needed by i2py.netdb. 'python-geoip-geolite2', # Needed by i2py.netdb. ], tests_require=['pytest'], url = 'https://github.com/chris-barry/i2py', packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'], )
Revert "Fix a mistake, this should use the specified tweet time" This reverts commit 25d711124e330c784fb4d0ebba1d46fa58f82e7b.
const TwitterPostBase = require('./TwitterPostBase'); const { captureGearScreenshot } = require('@/app/screenshots'); const { readData, getTopOfCurrentHour } = require('@/common/utilities'); class GearTweet extends TwitterPostBase { getKey() { return 'gear'; } getName() { return 'Gear'; } getMerchandises() { return readData('merchandises.json').merchandises; } getDataTime() { // We only have end_times for merchandise items, so we need to track the latest end_time let endTimes = this.getMerchandises().map(m => m.end_time); let lastEndTime = Math.max(...endTimes); return lastEndTime; } getData() { return this.getMerchandises().find(m => m.end_time == this.getDataTime()); } getTestData() { let merchandises = this.getMerchandises(); return merchandises[merchandises.length - 1]; } getImage(data) { let now = getTopOfCurrentHour(); return captureGearScreenshot(now); } getText(data) { return `Up now on SplatNet: ${data.gear.name} with ${data.skill.name} #splatnet2`; } } module.exports = GearTweet;
const TwitterPostBase = require('./TwitterPostBase'); const { captureGearScreenshot } = require('@/app/screenshots'); const { readData, getTopOfCurrentHour } = require('@/common/utilities'); class GearTweet extends TwitterPostBase { getKey() { return 'gear'; } getName() { return 'Gear'; } getMerchandises() { return readData('merchandises.json').merchandises; } getDataTime() { // We only have end_times for merchandise items, so we need to track the latest end_time let endTimes = this.getMerchandises().map(m => m.end_time); let lastEndTime = Math.max(...endTimes); return lastEndTime; } getData() { return this.getMerchandises().find(m => m.end_time == this.getDataTime()); } getTestData() { let merchandises = this.getMerchandises(); return merchandises[merchandises.length - 1]; } getImage() { return captureGearScreenshot(this.getDataTime()); } getText(data) { return `Up now on SplatNet: ${data.gear.name} with ${data.skill.name} #splatnet2`; } } module.exports = GearTweet;
Use system (application) class loader to load tool providers
package de.sormuras.bach.util; import java.util.Map; import java.util.NoSuchElementException; import java.util.ServiceLoader; import java.util.TreeMap; import java.util.function.Consumer; import java.util.spi.ToolProvider; /** Tool registry. */ public class Tools { final Map<String, ToolProvider> map; public Tools() { this.map = new TreeMap<>(); ServiceLoader.load(ToolProvider.class, ClassLoader.getSystemClassLoader()).stream() .map(ServiceLoader.Provider::get) .forEach(provider -> map.putIfAbsent(provider.name(), provider)); } public ToolProvider get(String name) { var tool = map.get(name); if (tool == null) { throw new NoSuchElementException("No such tool: " + name); } return tool; } public void forEach(Consumer<ToolProvider> action) { map.values().forEach(action); } }
package de.sormuras.bach.util; import java.util.Map; import java.util.NoSuchElementException; import java.util.ServiceLoader; import java.util.TreeMap; import java.util.function.Consumer; import java.util.spi.ToolProvider; /** Tool registry. */ public class Tools { final Map<String, ToolProvider> map; public Tools() { this.map = new TreeMap<>(); ServiceLoader.load(ToolProvider.class).stream() .map(ServiceLoader.Provider::get) .forEach(provider -> map.putIfAbsent(provider.name(), provider)); } public ToolProvider get(String name) { var tool = map.get(name); if (tool == null) { throw new NoSuchElementException("No such tool: " + name); } return tool; } public void forEach(Consumer<ToolProvider> action) { map.values().forEach(action); } }
Remove halign and valign on image_obj
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
Rename field `hasAlreadySet` -> `hasAlreadyStarted`
package com.cookpad.android.puree.retryable; import android.os.Handler; public class RetryableTaskRunner { private Handler handler; private boolean hasAlreadyStarted; private Runnable callback; private BuckoffCounter buckoffCounter; public RetryableTaskRunner(final Runnable task, final int interval) { this.buckoffCounter = new BuckoffCounter(interval); this.handler = new Handler(); this.hasAlreadyStarted = false; this.callback = new Runnable() { @Override public void run() { task.run(); } }; } public synchronized void tryToStart() { if (hasAlreadyStarted) { return; } buckoffCounter.resetRetryCount(); startDelayed(); } private synchronized void startDelayed() { handler.removeCallbacks(callback); handler.postDelayed(callback, buckoffCounter.time()); hasAlreadyStarted = true; } public synchronized void reset() { hasAlreadyStarted = false; buckoffCounter.resetRetryCount(); } public synchronized void retryLater() { buckoffCounter.incrementRetryCount(); startDelayed(); } }
package com.cookpad.android.puree.retryable; import android.os.Handler; public class RetryableTaskRunner { private Handler handler; private boolean hasAlreadySet; private Runnable callback; private BuckoffCounter buckoffCounter; public RetryableTaskRunner(final Runnable task, final int interval) { this.buckoffCounter = new BuckoffCounter(interval); this.handler = new Handler(); this.hasAlreadySet = false; this.callback = new Runnable() { @Override public void run() { task.run(); } }; } public synchronized void tryToStart() { if (hasAlreadySet) { return; } buckoffCounter.resetRetryCount(); startDelayed(); } private synchronized void startDelayed() { handler.removeCallbacks(callback); handler.postDelayed(callback, buckoffCounter.time()); hasAlreadySet = true; } public synchronized void reset() { hasAlreadySet = false; buckoffCounter.resetRetryCount(); } public synchronized void retryLater() { buckoffCounter.incrementRetryCount(); startDelayed(); } }
Use smallint for sort column on stories table
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddSortColumnToStoriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('stories', function(Blueprint $table) { $table->smallInteger('sort')->unsigned()->default(1); $table->unique(['sort', 'issue_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('stories', function(Blueprint $table) { $table->dropIndex('stories_sort_issue_id_unique'); $table->dropColumn('sort'); }); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddSortColumnToStoriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('stories', function(Blueprint $table) { $table->integer('sort')->unsigned()->default(1); $table->unique(['sort', 'issue_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('stories', function(Blueprint $table) { $table->dropIndex('stories_sort_issue_id_unique'); $table->dropColumn('sort'); }); } }
Fix to work on meetings landing page
var $ = require('jquery'); var m = require('mithril'); var Meetings = require('../meetings.js'); var Submissions = require('../submissions.js'); new Meetings(window.contextVars.meetings); var request = $.getJSON('/api/v1/meetings/submissions/'); var DonateBanner = require('js/home-page/donateBannerPlugin'); var columnSizeClass = '.col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2'; request.always(function() { $('#allMeetingsLoader').hide(); }); request.done(function(data) { new Submissions(data.submissions); }); $(document).ready(function(){ var osfDonateBanner = { view : function(ctrl, args) { return [ m('.donate-banner-background', m('.container', [ m(columnSizeClass, m.component(DonateBanner, {})) ] )), ]; } }; m.mount(document.getElementById('osfDonateBanner'), m.component(osfDonateBanner, {})); });
var $ = require('jquery'); var m = require('mithril'); var Meetings = require('../meetings.js'); var Submissions = require('../submissions.js'); new Meetings(window.contextVars.meetings); var request = $.getJSON('/api/v1/meetings/submissions/'); var DonateBanner = require('js/home-page/donateBannerPlugin'); var columnSizeClass = '.col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2'; request.always(function() { $('#allMeetingsLoader').hide(); }); request.done(function(data) { new Submissions(data.submissions); }); $(document).ready(function(){ var osfDonateBanner = { view : function(ctrl, args) { return [ m(DonateBanner.background, m('.container', [ m('.row', [ m(columnSizeClass, m.component(DonateBanner.Banner, {})) ]) ] )), ]; } }; m.mount(document.getElementById('osfDonateBanner'), m.component(osfDonateBanner, {})); });
Update base filter name and implment overrides The abstract class changed names and now implements a clear method. Remove the active state of the boolean filter on clear.
package org.azavea.otm.filters; import org.azavea.otm.R; import android.view.View; import android.widget.ToggleButton; public class BooleanFilter extends BaseFilter { public boolean active; public BooleanFilter(String key, String label) { initialize(key, label, false); } public BooleanFilter(String key, String label, boolean active) { initialize(key, label, active); } private void initialize(String key, String label, boolean active) { this.key = key; this.active = active; this.label = label; } @Override public String toQueryStringParam() { return key + "=" + Boolean.toString(active); } @Override public void updateFromView(View view) { this.active = ((ToggleButton)view.findViewById(R.id.active)).isChecked(); } @Override public boolean isActive() { return this.active; } @Override public void clear() { active = false; } }
package org.azavea.otm.filters; import org.azavea.otm.R; import android.view.View; import android.widget.ToggleButton; public class BooleanFilter extends MapFilter { public boolean active; public BooleanFilter(String key, String label) { initialize(key, label, false); } public BooleanFilter(String key, String label, boolean active) { initialize(key, label, active); } private void initialize(String key, String label, boolean active) { this.key = key; this.active = active; this.label = label; } @Override public String toQueryStringParam() { return key + "=" + Boolean.toString(active); } @Override public void updateFromView(View view) { this.active = ((ToggleButton)view.findViewById(R.id.active)).isChecked(); } @Override public boolean isActive() { return this.active; } }
Fix incorrect api usage, not Time rather TIME
var nodegit = require("../"), path = require("path"); // This code walks the history of the master branch and prints results // that look very similar to calling `git log` from the command line nodegit.Repository.open(path.resolve(__dirname, "../.git")) .then(function(repo) { return repo.getMasterCommit(); }) .then(function(firstCommitOnMaster){ // History returns an event. var history = firstCommitOnMaster.history(nodegit.Revwalk.SORT.TIME); // History emits "commit" event for each commit in the branch's history history.on("commit", function(commit) { console.log("commit " + commit.sha()); console.log("Author:", commit.author().name() + " <" + commit.author().email() + ">"); console.log("Date:", commit.date()); console.log("\n " + commit.message()); }); // Don't forget to call `start()`! history.start(); }) .done();
var nodegit = require("../"), path = require("path"); // This code walks the history of the master branch and prints results // that look very similar to calling `git log` from the command line nodegit.Repository.open(path.resolve(__dirname, "../.git")) .then(function(repo) { return repo.getMasterCommit(); }) .then(function(firstCommitOnMaster){ // History returns an event. var history = firstCommitOnMaster.history(nodegit.Revwalk.SORT.Time); // History emits "commit" event for each commit in the branch's history history.on("commit", function(commit) { console.log("commit " + commit.sha()); console.log("Author:", commit.author().name() + " <" + commit.author().email() + ">"); console.log("Date:", commit.date()); console.log("\n " + commit.message()); }); // Don't forget to call `start()`! history.start(); }) .done();
Fix input field for password, change from 'Text' to 'Password'.
<?php namespace SanAuth\Model; use Zend\Form\Form; class User extends Form { public function __construct($name = null) { // we want to ignore the name passed parent::__construct ( 'user' ); $this->add ( array ( 'name' => 'username', 'type' => 'Text', 'options' => array ( 'label' => 'Username' ), 'attributes' => array( 'class' => 'form-control', 'required' => true, ), ) ); $this->add ( array ( 'name' => 'password', 'type' => 'Password', 'options' => array ( 'label' => 'Password' ), 'attributes' => array( 'class' => 'form-control', 'required' => true, ), ) ); $this->add ( array ( 'name' => 'submit', 'type' => 'Submit', 'attributes' => array ( 'value' => 'Login', 'id' => 'submitbutton', 'class' => 'btn btn-primary', ) ) ); } }
<?php namespace SanAuth\Model; use Zend\Form\Form; class User extends Form { public function __construct($name = null) { // we want to ignore the name passed parent::__construct ( 'user' ); $this->add ( array ( 'name' => 'username', 'type' => 'Text', 'options' => array ( 'label' => 'Username' ), 'attributes' => array( 'class' => 'form-control', 'required' => true, ), ) ); $this->add ( array ( 'name' => 'password', 'type' => 'Text', 'options' => array ( 'label' => 'Password' ), 'attributes' => array( 'class' => 'form-control', 'required' => true, ), ) ); $this->add ( array ( 'name' => 'submit', 'type' => 'Submit', 'attributes' => array ( 'value' => 'Login', 'id' => 'submitbutton', 'class' => 'btn btn-primary', ) ) ); } }
Add documentation string for cosntants module
"""Constants for use by the bolometric correction routine """ # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
# Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
Make OC_Avatar unit tests independent of currently loggedin user
<?php /** * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ class Test_Avatar extends PHPUnit_Framework_TestCase { private $user; public function setUp() { $this->user = uniqid(); $storage = new \OC\Files\Storage\Temporary(array()); \OC\Files\Filesystem::mount($storage, array(), '/' . $this->user . '/'); } public function testAvatar() { $avatar = new \OC_Avatar($this->user); $this->assertEquals(false, $avatar->get()); $expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $expected->resize(64); $avatar->set($expected->data()); $this->assertEquals($expected->data(), $avatar->get()->data()); $avatar->remove(); $this->assertEquals(false, $avatar->get()); } public function testAvatarApi() { $avatarManager = \OC::$server->getAvatarManager(); $avatar = $avatarManager->getAvatar($this->user); $this->assertEquals(false, $avatar->get()); $expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $expected->resize(64); $avatar->set($expected->data()); $this->assertEquals($expected->data(), $avatar->get()->data()); $avatar->remove(); $this->assertEquals(false, $avatar->get()); } }
<?php /** * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ class Test_Avatar extends PHPUnit_Framework_TestCase { public function testAvatar() { $avatar = new \OC_Avatar(\OC_User::getUser()); $this->assertEquals(false, $avatar->get()); $expected = new OC_Image(\OC::$SERVERROOT.'/tests/data/testavatar.png'); $expected->resize(64); $avatar->set($expected->data()); $this->assertEquals($expected->data(), $avatar->get()->data()); $avatar->remove(); $this->assertEquals(false, $avatar->get()); } public function testAvatarApi() { $avatarManager = \OC::$server->getAvatarManager(); $avatar = $avatarManager->getAvatar(\OC_User::getUser()); $this->assertEquals(false, $avatar->get()); $expected = new OC_Image(\OC::$SERVERROOT.'/tests/data/testavatar.png'); $expected->resize(64); $avatar->set($expected->data()); $this->assertEquals($expected->data(), $avatar->get()->data()); $avatar->remove(); $this->assertEquals(false, $avatar->get()); } }
Fix bug when sometimes online event was reported twice
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online': logger.info('network state change: online' ) detector.emit('up') elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online
Change RSA public key to 65537 (thanks Lmctruck).
package org.apollo.tools; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; /** * An RSA key generator. * * @author Graham * @author Major */ public final class RsaKeyGenerator { /** * The bit count. <strong>Strongly</strong> recommended to be at least 2,048. */ private static final int BIT_COUNT = 2_048; /** * The entry point of the RsaKeyGenerator. * * @param args The application arguments. */ public static void main(String[] args) { Random random = new SecureRandom(); BigInteger publicKey = BigInteger.valueOf(65_537); BigInteger p, q, phi, modulus, privateKey; do { p = BigInteger.probablePrime(BIT_COUNT / 2, random); q = BigInteger.probablePrime(BIT_COUNT / 2, random); phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); modulus = p.multiply(q); privateKey = publicKey.modInverse(phi); } while (modulus.bitLength() != BIT_COUNT || privateKey.bitLength() != BIT_COUNT || !phi.gcd(publicKey).equals(BigInteger.ONE)); System.out.println("modulus: " + modulus); System.out.println("public key: " + publicKey); System.out.println("private key: " + privateKey); } }
package org.apollo.tools; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; /** * An RSA key generator. * * @author Graham * @author Major */ public final class RsaKeyGenerator { /** * The bit count. <strong>Strongly</strong> recommended to be at least 2,048. */ private static final int BIT_COUNT = 2_048; /** * The entry point of the RsaKeyGenerator. * * @param args The application arguments. */ public static void main(String[] args) { Random random = new SecureRandom(); BigInteger publicKey = BigInteger.valueOf(65535); BigInteger p, q, phi, modulus, privateKey; do { p = BigInteger.probablePrime(BIT_COUNT / 2, random); q = BigInteger.probablePrime(BIT_COUNT / 2, random); phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); modulus = p.multiply(q); privateKey = publicKey.modInverse(phi); } while (modulus.bitLength() != BIT_COUNT || privateKey.bitLength() != BIT_COUNT || !phi.gcd(publicKey).equals(BigInteger.ONE)); System.out.println("modulus: " + modulus); System.out.println("public key: " + publicKey); System.out.println("private key: " + privateKey); } }
Add other response field to response model
package org.adaptlab.chpir.android.survey.Models; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; @Table(name = "Responses") public class Response extends Model { @Column(name = "Question") private Question mQuestion; @Column(name = "Response") private String mResponse; @Column(name = "Survey") private Survey mSurvey; @Column(name = "Other_Response") private String mOtherResponse; public Response() { super(); } public Question getQuestion() { return mQuestion; } public void setQuestion(Question question) { mQuestion = question; } public String getResponse() { return mResponse; } public void setResponse(String response) { mResponse = response; } public void setSurvey(Survey survey) { mSurvey = survey; } public Survey getSurvey() { return mSurvey; } public void setOtherResponse(String otherResponse) { mOtherResponse = otherResponse; } public String getOtherResponse() { return mOtherResponse; } }
package org.adaptlab.chpir.android.survey.Models; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; @Table(name = "Responses") public class Response extends Model { @Column(name = "Question") private Question mQuestion; @Column(name = "Response") private String mResponse; @Column(name = "Survey") private Survey mSurvey; public Response() { super(); } public Question getQuestion() { return mQuestion; } public void setQuestion(Question question) { mQuestion = question; } public String getResponse() { return mResponse; } public void setResponse(String response) { mResponse = response; } public void setSurvey(Survey survey) { mSurvey = survey; } public Survey getSurvey() { return mSurvey; } }
Use addEventListener instead of onload
(function() { // wait for polyfill to be loaded if (document.readyState == "complete") { init(); } else { window.addEventListener('load', init); } var loggedIn = false; function init() { if (!navigator.id) return; sendToContent({ type: "init" }); window.addEventListener('browserid-exec', onMessage); navigator.id.watch({ onlogin: onLogin, onlogout: onLogout }); } function onLogin(assertion) { console.log('onLogin'); loggedIn = true; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onLogout() { console.log('onLogout'); loggedIn = false; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onMessage(event) { console.log('message received in agent'); console.log(event.detail); var data = event.detail; if (data.type == 'request-login') { navigator.id.request(); } else if (data.type == 'request-logout') { navigator.id.logout(); } } function sendToContent(message) { window.postMessage(message, "*"); } })();
(function() { // wait for polyfill to be loaded if (document.readyState == "complete") { init(); } else { window.onload = init; } var loggedIn = false; function init() { if (!navigator.id) return; sendToContent({ type: "init" }); window.addEventListener('browserid-exec', onMessage); navigator.id.watch({ onlogin: onLogin, onlogout: onLogout }); } function onLogin(assertion) { console.log('onLogin'); loggedIn = true; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onLogout() { console.log('onLogout'); loggedIn = false; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onMessage(event) { console.log('message received in agent'); console.log(event.detail); var data = event.detail; if (data.type == 'request-login') { navigator.id.request(); } else if (data.type == 'request-logout') { navigator.id.logout(); } } function sendToContent(message) { window.postMessage(message, "*"); } })();
Fix mistake in form element errors test.
import Ember from 'ember'; import { moduleForComponent } from 'ember-qunit'; import { formFeedbackClass, test } from '../../../../helpers/bootstrap-test'; import hbs from 'htmlbars-inline-precompile'; const { A } = Ember; moduleForComponent('bs-form/element/errors', 'Integration | Component | bs form/element/errors', { integration: true }); test('is empty by default', function(assert) { this.set('messages', ['foo', 'bar']); this.render(hbs`{{bs-form/element/errors show=false messages=messages}}`); assert.equal(this.$(`.${formFeedbackClass()}`).length, 0); }); test('shows first message', function(assert) { this.set('messages', A(['foo', 'bar'])); this.render(hbs`{{bs-form/element/errors show=true messages=messages}}`); assert.equal(this.$(`.${formFeedbackClass()}`).length, 1); assert.equal(this.$(`.${formFeedbackClass()}`).text().trim(), 'foo'); });
import Ember from 'ember'; import { moduleForComponent } from 'ember-qunit'; import { formFeedbackClass, test } from '../../../../helpers/bootstrap-test'; import hbs from 'htmlbars-inline-precompile'; const { A } = Ember; moduleForComponent('bs-form/element/errors', 'Integration | Component | bs form/element/errors', { integration: true }); test('is empty by default', function(assert) { this.set('messages', ['foo', 'bar']); this.render(hbs`{{bs-form/element/errors show=false messages=messages}}`); assert.equal(this.$(formFeedbackClass()).length, 0); }); test('shows first message', function(assert) { this.set('messages', A(['foo', 'bar'])); this.render(hbs`{{bs-form/element/errors show=true messages=messages}}`); assert.equal(this.$(formFeedbackClass()).length, 1); assert.equal(this.$(formFeedbackClass()).text().trim(), 'foo'); });
Restructure app and display commit count as a disabled menu item
# Github Tray App import rumps import config import contribs class GithubTrayApp(rumps.App): def __init__(self): super(GithubTrayApp, self).__init__('Github') self.count = rumps.MenuItem('commits') self.username = config.get_username() self.icon = 'github.png' self.menu = [ self.count, 'Update Now', 'Change Frequency', 'Change Username' ] self.update() def update(self): num = contribs.get_contribs(self.username) self.count.title = str(num) + ' commits' self.title = str(num) @rumps.timer(60*5) def timer(self, _): print('Running timer') self.update() @rumps.clicked('Update Now') def update_now(self, _): self.update() @rumps.clicked('Change Frequency') def change_frequency(_): rumps.alert('jk! not ready yet!') @rumps.clicked('Change Username') def change_username(_): rumps.alert('jk! not ready yet!') if __name__ == '__main__': GithubTrayApp().run()
# Github Tray App import rumps import config import contribs username = config.get_username() class GithubTrayApp(rumps.App): @rumps.timer(60*5) def timer(self, sender): count = contribs.get_contribs(username) self.title = str(count) @rumps.clicked('Update') def onoff(self, sender): count = contribs.get_contribs(username) self.title = str(count) @rumps.clicked('Change Frequency') def onoff(self, sender): rumps.alert('jk! not ready yet!') @rumps.clicked('Change Username') def prefs(self, _): rumps.alert('jk! not ready yet!') if __name__ == "__main__": count = contribs.get_contribs(username) GithubTrayApp('Github', icon='github.png', title=str(count)).run()
Remove attributes and defaults in favor of init implementation
import Ember from 'ember'; import { createAttributesObject } from 'ui-library/utils/create-attributes-object'; const { Mixin, get, setProperties } = Ember; export default Mixin.create({ classNames: ['r-btn'], classNameBindings: [ // types 'primary:r-btn-primary', 'secondary:r-btn-secondary', 'cancel:r-btn-cancel', // states 'loading:r-btn-loading', // sizes 'big:r-btn-large', 'small:r-btn-small' ], init() { this._super(...arguments); this.allowedAttributes = { variant: ['primary', 'secondary', 'cancel'], size: ['small', 'big'] }; this.defaults = { variant: 'secondary', size: 'small' }; const allowedAttributes = get(this, 'allowedAttributes'); const defaults = get(this, 'defaults'); const suppliedAttrs = get(this, 'attrs'); const attrObj = createAttributesObject(allowedAttributes, defaults, suppliedAttrs); setProperties(this, attrObj); } });
import Ember from 'ember'; import { createAttributesObject } from 'ui-library/utils/create-attributes-object'; const { Mixin, get, setProperties } = Ember; export default Mixin.create({ classNames: ['r-btn'], classNameBindings: [ // types 'primary:r-btn-primary', 'secondary:r-btn-secondary', 'cancel:r-btn-cancel', // states 'loading:r-btn-loading', // sizes 'big:r-btn-large', 'small:r-btn-small' ], attributes: { variant: ['primary', 'secondary', 'cancel'], size: ['small', 'big'] }, defaults: { variant: 'secondary', size: 'small' }, init() { this._super(...arguments); this.allowedAttributes = { variant: ['primary', 'secondary', 'cancel'], size: ['small', 'big'] }; this.defaults = { variant: 'secondary', size: 'small' }; const allowedAttributes = get(this, 'allowedAttributes'); const defaults = get(this, 'defaults'); const suppliedAttrs = get(this, 'attrs'); const attrObj = createAttributesObject(allowedAttributes, defaults, suppliedAttrs); setProperties(this, attrObj); } });
Fix unicode issues at url translation
# coding: utf-8 import re from django.core.urlresolvers import reverse from django.conf import settings def reverse_no_i18n(viewname, *args, **kwargs): result = reverse(viewname, *args, **kwargs) m = re.match(r'(/[^/]*)(/.*$)', result) return m.groups()[1] def change_url_language(url, language): if hasattr(settings, 'LANGUAGES'): languages = [lang[0] for lang in settings.LANGUAGES] m = re.match(r'/([^/]*)(/.*$)', url) if m and m.groups()[0] in languages: return u"/{lang}{url}".format( lang=language, url=m.groups()[1]) return u"/{lang}{url}".format( lang=language, url=url) return url
# coding: utf-8 import re from django.core.urlresolvers import reverse from django.conf import settings def reverse_no_i18n(viewname, *args, **kwargs): result = reverse(viewname, *args, **kwargs) m = re.match(r'(/[^/]*)(/.*$)', result) return m.groups()[1] def change_url_language(url, language): if hasattr(settings, 'LANGUAGES'): languages = [lang[0] for lang in settings.LANGUAGES] m = re.match(r'/([^/]*)(/.*$)', url) if m and m.groups()[0] in languages: return "/{lang}{url}".format( lang=language, url=m.groups()[1]) return "/{lang}{url}".format( lang=language, url=url) return url
Fix error on date save
# This file is part of e-Giełda. # Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński # # e-Giełda 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. # # You should have received a copy of the GNU Affero General Public License # along with e-Giełda. If not, see <http://www.gnu.org/licenses/>. from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(date): return date.strftime(DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
# This file is part of e-Giełda. # Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński # # e-Giełda 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. # # You should have received a copy of the GNU Affero General Public License # along with e-Giełda. If not, see <http://www.gnu.org/licenses/>. from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(datetime): return datetime.strftime(datetime, DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
Edit link function. Add controller
// js/directives/nw-category-select.directive (function() { "use strict"; angular.module("NoteWrangler") .directive("nwCategorySelect", nwCategorySelectDirective); nwCategorySelectDirective.$inject = ["Category"]; function nwCategorySelectDirective(Category) { return { replace: true, restrict: "E", templateUrl: "../templates/directives/nw-category-select.directive.html", link: function (scope, element, attrs) { scope.categories = Category.query(); }, // need refactoring controller: function ($scope) { this.getActiveCategory = function() { return $scope.activeCategory; }; this.setActiveCategory = function(newCategory) { $scope.activeCategory = newCategory.name; }; return this; } /*controller: "nwCategorySelectController", controllerAs: "nwCategorySelectCtrl"*/ }; } })();
// js/directives/nw-category-select.directive (function() { "use strict"; angular.module("NoteWrangler") .directive("nwCategorySelect", nwCategorySelectDirective); nwCategorySelectDirective.$inject = ["Category"]; function nwCategorySelectDirective(Category) { return { replace: true, restrict: "E", templateUrl: "../templates/directives/nw-category-select.directive.html", link: (scope, element, attrs) => { scope.categories = Category.query(); }, // need refactoring /*controller: ($scope) => { this.activeCategory = () => { return $scope.activeCategory; }; this.setActiveCategory = (category) => { $scope.activeCategory = category; }; return this; },*/ controller: "nwCategorySelectController", controllerAs: "nwCategorySelectCtrl" }; } })();
Fix a test that broke with the internal queue changes.
package net.spy.memcached; import junit.framework.TestCase; /** * Test connection factory variations. */ public class ConnectionFactoryTest extends TestCase { // These tests are a little lame. They don't verify anything other than // that the code executes without failure. public void testBinaryEmptyCons() { new BinaryConnectionFactory(); } public void testBinaryTwoIntCons() { new BinaryConnectionFactory(5, 5); } public void testBinaryAnIntAnotherIntAndAHashAlgorithmCons() { new BinaryConnectionFactory(5, 5, HashAlgorithm.FNV1_64_HASH); } public void testQueueSizes() { ConnectionFactory cf=new DefaultConnectionFactory(100, 1024); assertEquals(100, cf.createOperationQueue().remainingCapacity()); assertEquals(Integer.MAX_VALUE, cf.createWriteOperationQueue().remainingCapacity()); assertEquals(Integer.MAX_VALUE, cf.createReadOperationQueue().remainingCapacity()); } }
package net.spy.memcached; import junit.framework.TestCase; /** * Test connection factory variations. */ public class ConnectionFactoryTest extends TestCase { // These tests are a little lame. They don't verify anything other than // that the code executes without failure. public void testBinaryEmptyCons() { new BinaryConnectionFactory(); } public void testBinaryTwoIntCons() { new BinaryConnectionFactory(5, 5); } public void testBinaryAnIntAnotherIntAndAHashAlgorithmCons() { new BinaryConnectionFactory(5, 5, HashAlgorithm.FNV1_64_HASH); } public void testQueueSizes() { ConnectionFactory cf=new DefaultConnectionFactory(100, 1024); assertEquals(100, cf.createOperationQueue().remainingCapacity()); assertEquals(100, cf.createWriteOperationQueue().remainingCapacity()); assertEquals(110, cf.createReadOperationQueue().remainingCapacity()); } }
Fix a bug in this SVG test harness. Make sure it uses document.documentElement instead of document.firstChild. git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@30427 bbb929c8-8fbe-4397-9dbb-9b2b20218538
var svgNS = "http://www.w3.org/2000/svg"; var xlinkNS = "http://www.w3.org/1999/xlink"; var rootSVGElement; function createSVGElement(name) { return document.createElementNS(svgNS, "svg:" + name); } function createSVGTestCase() { if (window.layoutTestController) layoutTestController.waitUntilDone(); rootSVGElement = createSVGElement("svg"); rootSVGElement.setAttribute("width", "300"); rootSVGElement.setAttribute("height", "300"); var bodyElement = document.documentElement.lastChild; bodyElement.insertBefore(rootSVGElement, document.getElementById("description")); } function sendMouseEvent() { if (window.eventSender) { eventSender.mouseMoveTo(150, 200); eventSender.mouseDown(); eventSender.mouseUp(); } } function triggerUpdate() { window.setTimeout("sendMouseEvent()", 0); } function waitForClickEvent(obj) { if (window.layoutTestController) obj.setAttribute("onclick", "layoutTestController.notifyDone()"); }
var svgNS = "http://www.w3.org/2000/svg"; var xlinkNS = "http://www.w3.org/1999/xlink"; var rootSVGElement; function createSVGElement(name) { return document.createElementNS(svgNS, "svg:" + name); } function createSVGTestCase() { if (window.layoutTestController) layoutTestController.waitUntilDone(); rootSVGElement = createSVGElement("svg"); rootSVGElement.setAttribute("width", "300"); rootSVGElement.setAttribute("height", "300"); var bodyElement = document.firstChild.lastChild; bodyElement.insertBefore(rootSVGElement, document.getElementById("description")); } function sendMouseEvent() { if (window.eventSender) { eventSender.mouseMoveTo(150, 200); eventSender.mouseDown(); eventSender.mouseUp(); } } function triggerUpdate() { window.setTimeout("sendMouseEvent()", 0); } function waitForClickEvent(obj) { if (window.layoutTestController) obj.setAttribute("onclick", "layoutTestController.notifyDone()"); }
Fix bug in SDC configuration. Initial running version.
package org.opencds.cqf.ruler.plugin.sdc; import ca.uhn.fhir.jpa.starter.annotations.OnDSTU3Condition; import ca.uhn.fhir.jpa.starter.annotations.OnR4Condition; import org.opencds.cqf.ruler.api.OperationProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnProperty(prefix = "hapi.fhir.sdc", name ="enabled", havingValue = "true") public class SDCConfig { @Bean public SDCProperties SDCProperties() { return new SDCProperties(); } @Bean @Conditional(OnR4Condition.class) public OperationProvider r4ExtractProvider() { return new org.opencds.cqf.ruler.plugin.sdc.r4.ExtractProvider(); } @Bean @Conditional(OnDSTU3Condition.class) public OperationProvider dstu3ExtractProvider() { return new org.opencds.cqf.ruler.plugin.sdc.dstu3.ExtractProvider(); } // TODO: OAuth meta-data extenders }
package org.opencds.cqf.ruler.plugin.sdc; import ca.uhn.fhir.jpa.starter.annotations.OnDSTU3Condition; import ca.uhn.fhir.jpa.starter.annotations.OnR4Condition; import org.opencds.cqf.ruler.api.OperationProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnProperty(prefix = "hapi.fhir.sdc", name ="enabled", havingValue = "true") public class SDCConfig { @Bean public SDCProperties sdcProperties() { return new SDCProperties(); } @Bean @Conditional(OnR4Condition.class) public OperationProvider r4ExtractProvider() { return new org.opencds.cqf.ruler.plugin.sdc.r4.ExtractProvider(); } @Bean @Conditional(OnDSTU3Condition.class) public OperationProvider dstu3ExtractProvider() { return new org.opencds.cqf.ruler.plugin.sdc.dstu3.ExtractProvider(); } // TODO: OAuth meta-data extenders }
Update cluster config map key format
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from django.conf import settings JOB_NAME = 'plxjob-{task_type}{task_idx}-{experiment_uuid}' DEFAULT_PORT = 2222 ENV_VAR_TEMPLATE = '{name: "{var_name}", value: "{var_value}"}' VOLUME_NAME = 'pv-{vol_name}' VOLUME_CLAIM_NAME = 'pvc-{vol_name}' CLUSTER_CONFIG_MAP_NAME = 'plxcluster-{experiment_uuid}' CLUSTER_CONFIG_MAP_KEY_NAME = 'plxcluster_{task_type}' POD_CONTAINER_PROJECT_NAME = 'plxproject-{project_uuid}-{name}' DEPLOYMENT_NAME = 'plxproject-{project_uuid}-{name}' def SIDECAR_ARGS_FN(pod_id): return ["python3", "api/manage.py", "start_sidecar", pod_id, "--log_sleep_interval={}".format(settings.JOB_SIDECAR_LOG_SLEEP_INTERVAL), "--persist={}".format(settings.JOB_SIDECAR_PERSIST)] DATA_VOLUME = 'data' OUTPUTS_VOLUME = 'outputs'
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from django.conf import settings JOB_NAME = 'plxjob-{task_type}{task_idx}-{experiment_uuid}' DEFAULT_PORT = 2222 ENV_VAR_TEMPLATE = '{name: "{var_name}", value: "{var_value}"}' VOLUME_NAME = 'pv-{vol_name}' VOLUME_CLAIM_NAME = 'pvc-{vol_name}' CLUSTER_CONFIG_MAP_NAME = 'plxcluster-{experiment_uuid}' CLUSTER_CONFIG_MAP_KEY_NAME = 'plxcluster_{experiment_uuid}_{task_type}' POD_CONTAINER_PROJECT_NAME = 'plxproject-{project_uuid}-{name}' DEPLOYMENT_NAME = 'plxproject-{project_uuid}-{name}' def SIDECAR_ARGS_FN(pod_id): return ["python3", "api/manage.py", "start_sidecar", pod_id, "--log_sleep_interval={}".format(settings.JOB_SIDECAR_LOG_SLEEP_INTERVAL), "--persist={}".format(settings.JOB_SIDECAR_PERSIST)] DATA_VOLUME = 'data' OUTPUTS_VOLUME = 'outputs'
Use proper cache directory in error view Fixes #1254 Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
from ubuntui.frame import Frame # noqa from ubuntui.views import ErrorView from conjureup import async from conjureup.app_config import app from conjureup.ui.views.shutdown import ShutdownView from ubuntui.ev import EventLoop from pathlib import Path class ConjureUI(Frame): def show_exception_message(self, ex): _cache_dir = Path(app.argv.cache_dir) / 'conjure-up.log' errmsg = str(ex) errmsg += ( "\n\n Review log messages at {} " "If appropriate, please submit a bug here: " "https://github.com/conjure-up/conjure-up/issues/new".format( _cache_dir)) async.shutdown() EventLoop.remove_alarms() self.frame.body = ErrorView(errmsg) app.log.debug("Showing dialog for exception: {}".format(ex)) def show_error_message(self, msg): self.frame.body = ErrorView(msg) def show_shutdown_message(self): self.frame.body = ShutdownView()
from ubuntui.frame import Frame # noqa from ubuntui.views import ErrorView from conjureup import async from conjureup.app_config import app from conjureup.ui.views.shutdown import ShutdownView from ubuntui.ev import EventLoop class ConjureUI(Frame): def show_exception_message(self, ex): errmsg = str(ex) errmsg += ("\n\n" "Review log messages at ~/.cache/conjure-up/conjure-up.log " "If appropriate, please submit a bug here: " "https://github.com/conjure-up/conjure-up/issues/new") async.shutdown() EventLoop.remove_alarms() self.frame.body = ErrorView(errmsg) app.log.debug("Showing dialog for exception: {}".format(ex)) def show_error_message(self, msg): self.frame.body = ErrorView(msg) def show_shutdown_message(self): self.frame.body = ShutdownView()
Revert "fix(route): don't default to creating a new module"
'use strict'; var path = require('path'); var util = require('util'); var ngUtil = require('../util'); var ScriptBase = require('../script-base.js'); var Generator = module.exports = function Generator() { ScriptBase.apply(this, arguments); }; util.inherits(Generator, ScriptBase); Generator.prototype.prompting = function askFor() { var self = this; var name = this.name; var prompts = [{ name: 'moduleName', message: 'What module name would you like to use?', default: self.scriptAppName + '.' + self.name, when: function() {return self.config.get('modulePrompt');} }, { name: 'dir', message: 'Where would you like to create this route?', default: self.config.get('routeDirectory') }, { name: 'route', message: 'What will the url of your route be?', default: '/' + name }]; return this.prompt(prompts).then(function (props) { self.scriptAppName = props.moduleName || self.scriptAppName; self.route = props.route; self.dir = path.join(props.dir, self.name); }); }; Generator.prototype.writing = function createFiles() { var basePath = this.config.get('basePath') || ''; this.htmlUrl = ngUtil.relativeUrl(basePath, path.join(this.dir, this.name + '.html')); ngUtil.copyTemplates(this, 'route'); };
'use strict'; var path = require('path'); var util = require('util'); var ngUtil = require('../util'); var ScriptBase = require('../script-base.js'); var Generator = module.exports = function Generator() { ScriptBase.apply(this, arguments); }; util.inherits(Generator, ScriptBase); Generator.prototype.prompting = function askFor() { var self = this; var name = this.name; var prompts = [{ name: 'moduleName', message: 'What module name would you like to use?', default: self.scriptAppName, when: function() {return self.config.get('modulePrompt');} }, { name: 'dir', message: 'Where would you like to create this route?', default: self.config.get('routeDirectory') }, { name: 'route', message: 'What will the url of your route be?', default: '/' + name }]; return this.prompt(prompts).then(function (props) { self.scriptAppName = props.moduleName || self.scriptAppName; self.route = props.route; self.dir = path.join(props.dir, self.name); }); }; Generator.prototype.writing = function createFiles() { var basePath = this.config.get('basePath') || ''; this.htmlUrl = ngUtil.relativeUrl(basePath, path.join(this.dir, this.name + '.html')); ngUtil.copyTemplates(this, 'route'); };
Fix a bug when width was not inherited from document (because it was not assigned from the start)
/* --- script: Resizable.js description: Document that redraws children when window gets resized. license: Public domain (http://unlicense.org). authors: Yaroslaff Fedin requires: - LSD.Document - LSD.Widget.Module.Layout - Base/Widget.Module.Events - Base/Widget.Module.Attributes provides: - LSD.Document.Resizable ... */ LSD.Document.Resizable = new Class({ Includes: [ LSD.Document, LSD.Widget.Module.Layout, Widget.Module.Events, Widget.Module.Attributes ], options: { events: { window: { resize: 'onResize' } }, root: true }, initialize: function() { this.style = { current: {} }; this.parent.apply(this, arguments); this.attach(); this.onResize(); this.element.set('userSelect', false) }, attach: $lambda(true), detach: $lambda(true), onResize: function() { Object.append(this.style.current, document.getCoordinates()); this.render() }, render: function() { this.childNodes.each(function(child){ child.refresh(); }); } });
/* --- script: Resizable.js description: Document that redraws children when window gets resized. license: Public domain (http://unlicense.org). authors: Yaroslaff Fedin requires: - LSD.Document - LSD.Widget.Module.Layout - Base/Widget.Module.Events - Base/Widget.Module.Attributes provides: - LSD.Document.Resizable ... */ LSD.Document.Resizable = new Class({ Includes: [ LSD.Document, LSD.Widget.Module.Layout, Widget.Module.Events, Widget.Module.Attributes ], options: { events: { window: { resize: 'onResize' } }, root: true }, initialize: function() { this.style = { current: {} }; this.parent.apply(this, arguments); this.attach(); // this.onResize(); this.element.set('userSelect', false) }, attach: $lambda(true), detach: $lambda(true), onResize: function() { Object.append(this.style.current, document.getCoordinates()); this.render() }, render: function() { this.childNodes.each(function(child){ child.refresh(); }); } });
Allow editing if title description is undefined Change-Id: I908fd3380d81446f79485ad5ea286ef4861ae897
'use strict'; const EditTransform = require('wikimedia-page-library').EditTransform; const addHrefToEditButton = require('./addHrefToEditButton'); const domUtil = require('../../domUtil'); /** * Adds a page header with title, lead section edit button, and optional description and * button for the title pronunciation. * @param {!Document} doc Parsoid DOM document * @param {!object} meta meta object with the following properties: * {!string} displayTitle the title of the page as displayed * {!string} linkTitle the title of the page that can be used to link to it * {boolean} descriptionEditable * {?string} description * {?boolean} hasPronunciation */ module.exports = (doc, meta) => { const body = doc.body; const headerElement = doc.createElement('header'); body.insertBefore(headerElement, body.firstChild); const pronunciationUrl = meta.parsoid.meta.pronunciation && meta.parsoid.meta.pronunciation.url; const content = EditTransform.newEditLeadSectionHeader(doc, meta.mw.displaytitle, meta.mw.description, 'Add a description', meta.mw.description === undefined || meta.mw.description_source === 'central', true, pronunciationUrl); headerElement.appendChild(content); addHrefToEditButton(headerElement, 0, domUtil.getParsoidLinkTitle(doc)); };
'use strict'; const EditTransform = require('wikimedia-page-library').EditTransform; const addHrefToEditButton = require('./addHrefToEditButton'); const domUtil = require('../../domUtil'); /** * Adds a page header with title, lead section edit button, and optional description and * button for the title pronunciation. * @param {!Document} doc Parsoid DOM document * @param {!object} meta meta object with the following properties: * {!string} displayTitle the title of the page as displayed * {!string} linkTitle the title of the page that can be used to link to it * {boolean} descriptionEditable * {?string} description * {?boolean} hasPronunciation */ module.exports = (doc, meta) => { const body = doc.body; const headerElement = doc.createElement('header'); body.insertBefore(headerElement, body.firstChild); const pronunciationUrl = meta.parsoid.meta.pronunciation && meta.parsoid.meta.pronunciation.url; const content = EditTransform.newEditLeadSectionHeader(doc, meta.mw.displaytitle, meta.mw.description, 'Add a description', meta.mw.description_source === 'central', true, pronunciationUrl); headerElement.appendChild(content); addHrefToEditButton(headerElement, 0, domUtil.getParsoidLinkTitle(doc)); };
Add publicKeyExists implementation in staticAccessController
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <cogo@starzinger.net> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ use Imbo\Auth\AccessControl\Adapter\AdapterInterface, Imbo\Auth\AccessControl\Adapter\AbstractAdapter, Imbo\Auth\AccessControl\UserQuery, Imbo\Auth\AccessControl\GroupQuery; /** * Use a custom user lookup implementation */ class StaticAccessControl extends AbstractAdapter implements AdapterInterface { public function hasAccess($publicKey, $resource, $user = null) { return $publicKey === 'public'; } public function getPrivateKey($publicKey) { return 'private'; } public function getUsers(UserQuery $query = null) { return ['public']; } public function getGroups(GroupQuery $query = null) { return []; } public function getGroup($groupName) { return false; } public function userExists($publicKey) { return $publicKey === 'public'; } public function publicKeyExists($publicKey) { return $publicKey === 'public'; } } return [ 'accessControl' => new StaticAccessControl(), ];
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <cogo@starzinger.net> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ use Imbo\Auth\AccessControl\Adapter\AdapterInterface, Imbo\Auth\AccessControl\Adapter\AbstractAdapter, Imbo\Auth\AccessControl\UserQuery, Imbo\Auth\AccessControl\GroupQuery; /** * Use a custom user lookup implementation */ class StaticAccessControl extends AbstractAdapter implements AdapterInterface { public function hasAccess($publicKey, $resource, $user = null) { return $publicKey === 'public'; } public function getPrivateKey($publicKey) { return 'private'; } public function getUsers(UserQuery $query = null) { return ['public']; } public function getGroups(GroupQuery $query = null) { return []; } public function getGroup($groupName) { return false; } public function userExists($publicKey) { return $publicKey === 'public'; } } return [ 'accessControl' => new StaticAccessControl(), ];
Add surname in the registration
<?php namespace Project\AppBundle\Form\Type; use Symfony\Component\Form\FormBuilderInterface; use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType; class RegistrationFormType extends BaseType { public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder ->add('username', null, array(/*'label' => 'form.username',*/ 'translation_domain' => 'FOSUserBundle')) ->add('email', 'email', array(/*'label' => 'form.email',*/ 'translation_domain' => 'FOSUserBundle')) ->add('plainPassword', 'repeated', array( 'type' => 'password', 'options' => array('translation_domain' => 'FOSUserBundle'), 'first_options' => array('label' => 'Password'), 'second_options' => array('label' => 'Password confirmation'), 'invalid_message' => 'fos_user.password.mismatch', )) ->add('surname', null) ; } public function getName() { return 'override_fosuser_registration'; } }
<?php namespace Project\AppBundle\Form\Type; use Symfony\Component\Form\FormBuilderInterface; use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType; class RegistrationFormType extends BaseType { public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder ->add('username', null, array(/*'label' => 'form.username',*/ 'translation_domain' => 'FOSUserBundle')) ->add('email', 'email', array(/*'label' => 'form.email',*/ 'translation_domain' => 'FOSUserBundle')) ->add('plainPassword', 'repeated', array( 'type' => 'password', 'options' => array('translation_domain' => 'FOSUserBundle'), 'first_options' => array('label' => 'Password'), 'second_options' => array('label' => 'Password confirmation'), 'invalid_message' => 'fos_user.password.mismatch', )) ; } public function getName() { return 'override_fosuser_registration'; } }
Add FLAG_ELSE LightnCandy compiler option to provide "{{ else }}" and "{{ else if foo }}" to templates.
<?php namespace Droid\Transform\Render; use LightnCandy\LightnCandy; class LightnCandyRenderer implements RendererInterface { public function render($value, $context = array()) { $compiled = $this->compile($value); if ($compiled === false) { throw new RendererException('Failure to compile!'); } $renderer = $this->prepare($compiled); if ($renderer === false) { throw new RendererException('Failure to prepare compiled template content.'); } return $renderer($context); } protected function compile($templateContent) { return LightnCandy::compile( $templateContent, array('flags' => self::compilerFlags()) ); } protected function prepare($compiledTemplateContent) { return LightnCandy::prepare( $compiledTemplateContent ); } private static function compilerFlags() { return LightnCandy::FLAG_INSTANCE | LightnCandy::FLAG_BESTPERFORMANCE | LightnCandy::FLAG_ELSE ; } }
<?php namespace Droid\Transform\Render; use LightnCandy\LightnCandy; class LightnCandyRenderer implements RendererInterface { public function render($value, $context = array()) { $compiled = $this->compile($value); if ($compiled === false) { throw new RendererException('Failure to compile!'); } $renderer = $this->prepare($compiled); if ($renderer === false) { throw new RendererException('Failure to prepare compiled template content.'); } return $renderer($context); } protected function compile($templateContent) { return LightnCandy::compile( $templateContent, array('flags' => self::compilerFlags()) ); } protected function prepare($compiledTemplateContent) { return LightnCandy::prepare( $compiledTemplateContent ); } private static function compilerFlags() { return LightnCandy::FLAG_INSTANCE | LightnCandy::FLAG_BESTPERFORMANCE ; } }
Fix typo in HTML page.
package termite import ( "fmt" "http" "sync" "sync/atomic" "time" ) type masterStats struct { counterMutex sync.Mutex received *MultiResolutionCounter running int32 } func newMasterStats() *masterStats { return &masterStats{ received: NewMultiResolutionCounter(1, time.Seconds(), []int{60, 10}), } } func (me *masterStats) MarkReceive() { me.counterMutex.Lock() defer me.counterMutex.Unlock() me.received.Add(time.Seconds(), 1) atomic.AddInt32(&me.running, 1) } func (me *masterStats) MarkReturn() { atomic.AddInt32(&me.running, -1) } func (me *masterStats) writeHttp(w http.ResponseWriter) { me.counterMutex.Lock() defer me.counterMutex.Unlock() me.received.Add(time.Seconds(), 0) fmt.Fprintf(w, "<p>Received (sec/min/10min): %v", me.received.Read()) r := atomic.AddInt32(&me.running, 0) fmt.Fprintf(w, "<p>Jobs in receive status: %d "+ "(parallelism of the job)", r) }
package termite import ( "fmt" "http" "sync" "sync/atomic" "time" ) type masterStats struct { counterMutex sync.Mutex received *MultiResolutionCounter running int32 } func newMasterStats() *masterStats { return &masterStats{ received: NewMultiResolutionCounter(1, time.Seconds(), []int{60, 10}), } } func (me *masterStats) MarkReceive() { me.counterMutex.Lock() defer me.counterMutex.Unlock() me.received.Add(time.Seconds(), 1) atomic.AddInt32(&me.running, 1) } func (me *masterStats) MarkReturn() { atomic.AddInt32(&me.running, -1) } func (me *masterStats) writeHttp(w http.ResponseWriter) { me.counterMutex.Lock() defer me.counterMutex.Unlock() me.received.Add(time.Seconds(), 0) fmt.Fprintf(w, "<p>Received (sec/min/10min): %v", me.received.Read()) r := atomic.AddInt32(&me.running, 0) fmt.Fprintf(w, "<p>Jobs in receive status: %d "+ "(measure the maximum parallelism of the job", r) }
Fix typo in class name.
""" sentry.plugins.sentry_urls.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import sentry from django.utils.translation import ugettext_lazy as _ from sentry.plugins import register from sentry.plugins.bases.tag import TagPlugin class UrlsPlugin(TagPlugin): """ Automatically adds the 'url' tag from events containing interface data from ``sentry.interfaces.Http``. """ slug = 'urls' title = _('Auto Tag: URLs') version = sentry.VERSION author = "Sentry Team" author_url = "https://github.com/getsentry/sentry" tag = 'url' tag_label = _('URL') project_default_enabled = True def get_tag_values(self, event): http = event.interfaces.get('sentry.interfaces.Http') if not http: return [] if not http.url: return [] return [http.url] register(UrlsPlugin)
""" sentry.plugins.sentry_urls.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import sentry from django.utils.translation import ugettext_lazy as _ from sentry.plugins import register from sentry.plugins.bases.tag import TagPlugin class UrlsPlugin(TagPlugin): """ Automatically adds the 'url' tag from events containing interface data from ``sentry.interfaes.Http``. """ slug = 'urls' title = _('Auto Tag: URLs') version = sentry.VERSION author = "Sentry Team" author_url = "https://github.com/getsentry/sentry" tag = 'url' tag_label = _('URL') project_default_enabled = True def get_tag_values(self, event): http = event.interfaces.get('sentry.interfaces.Http') if not http: return [] if not http.url: return [] return [http.url] register(UrlsPlugin)
Configure web-fonts to swap after being loaded
import './assets/style/main.scss'; const resources = { manifest: '/application.webmanifest', fonts: 'https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700%7cRoboto+Slab:300,400&display=swap', icon: 'https://gravatar.com/avatar/39263d15a3b0838a938aaaa59dde5c06?s=256', }; export default (Vue, { head, }) => { head.link.push({ rel: 'manifest', href: resources.manifest, }); head.link.push({ rel: 'preload', href: resources.fonts, as: 'style', crossorigin: 'anonymous', }); head.link.push({ rel: 'stylesheet', href: resources.fonts, }); head.link.push({ rel: 'icon', href: resources.icon, }); if (process.isClient) { window.addEventListener('load', () => import('pwacompat')); } };
import './assets/style/main.scss'; const resources = { manifest: '/application.webmanifest', fonts: 'https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700%7cRoboto+Slab:300,400', icon: 'https://gravatar.com/avatar/39263d15a3b0838a938aaaa59dde5c06?s=256', }; export default (Vue, { head, }) => { head.link.push({ rel: 'manifest', href: resources.manifest, }); head.link.push({ rel: 'preload', href: resources.fonts, as: 'style', crossorigin: 'anonymous', }); head.link.push({ rel: 'stylesheet', href: resources.fonts, }); head.link.push({ rel: 'icon', href: resources.icon, }); if (process.isClient) { window.addEventListener('load', () => import('pwacompat')); } };
Add red warning at top to stop people who don't read.
<div class="alert alert-danger"> <strong>WARNING:</strong> Do not run this version on a live environment! There are known security holes that we are working on getting patched. This is extremely beta software and this version is to get the features in place while we work on security enhancements. </div> <div class="navbar navbar-default"> <div class="navbar-header"> <a class="navbar-brand" href="#"><?php echo $core->framework->settings->get('company_name'); ?></a> </div> <div class="navbar-collapse navbar-responsive-collapse collapse" style="height: 1px;"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Account <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="<?php echo $core->framework->settings->get('master_url'); ?>logout.php">Logout</a></li> <?php if($core->framework->user->getData('root_admin') == 1){ echo '<li><a href="'.$core->framework->settings->get('master_url').'admin/index.php">Admin CP</a></li>'; } ?> </ul> </li> </ul> </div> </div>
<div class="navbar navbar-default"> <div class="navbar-header"> <a class="navbar-brand" href="#"><?php echo $core->framework->settings->get('company_name'); ?></a> </div> <div class="navbar-collapse navbar-responsive-collapse collapse" style="height: 1px;"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Account <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="<?php echo $core->framework->settings->get('master_url'); ?>logout.php">Logout</a></li> <?php if($core->framework->user->getData('root_admin') == 1){ echo '<li><a href="'.$core->framework->settings->get('master_url').'admin/index.php">Admin CP</a></li>'; } ?> </ul> </li> </ul> </div> </div>
Add innerRef prop to Input component
import React from 'react'; import {Icon} from '../iconography'; import classnames from 'classnames'; import PropTypes from 'prop-types'; export class Input extends React.Component { static propTypes = { size: PropTypes.string, icon: PropTypes.string, innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]) }; componentDidMount() { require('../../css/inputs'); } render() { const {size, icon, innerRef, ...props} = this.props; const input = (<input {...{ ...props, ref: innerRef, className: classnames(props.className, { 'input-sm': ['sm', 'small'].indexOf(size) !== -1, 'input-lg': ['lg', 'large'].indexOf(size) !== -1 }) }} />); if (!icon) return input; return ( <div className="input-icon-container"> {input} <Icon {...{src: icon}}/> </div> ); } }
import React from 'react'; import {Icon} from '../iconography'; import classnames from 'classnames'; import PropTypes from 'prop-types'; export class Input extends React.Component { static propTypes = { size: PropTypes.string, icon: PropTypes.string }; componentDidMount() { require('../../css/inputs'); } render() { const {size, icon, ...props} = this.props; const input = (<input {...{ ...props, className: classnames(props.className, { 'input-sm': ['sm', 'small'].indexOf(size) !== -1, 'input-lg': ['lg', 'large'].indexOf(size) !== -1 }) }} />); if (!icon) return input; return ( <div className="input-icon-container"> {input} <Icon {...{src: icon}}/> </div> ); } }
Add padding space between table name and loaded data
function Translator(domain) { this.domain = domain; this.init(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, init: function() { this.table = this.getTableName(this.domain); }, getTableName: function(domain) { return domain; }, translate: function(batch) { }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[field] = batch.fields[field]; } var command = 'load --table ' + this.table + ' ' + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
function Translator(domain) { this.domain = domain; this.init(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, init: function() { this.table = this.getTableName(this.domain); }, getTableName: function(domain) { return domain; }, translate: function(batch) { }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[field] = batch.fields[field]; } var command = 'load --table ' + this.table + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
chore: Update init sample to import inside of function. PiperOrigin-RevId: 485079470
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from google.auth import credentials as auth_credentials # [START aiplatform_sdk_init_sample] def init_sample( project: Optional[str] = None, location: Optional[str] = None, experiment: Optional[str] = None, staging_bucket: Optional[str] = None, credentials: Optional[auth_credentials.Credentials] = None, encryption_spec_key_name: Optional[str] = None, ): from google.cloud import aiplatform aiplatform.init( project=project, location=location, experiment=experiment, staging_bucket=staging_bucket, credentials=credentials, encryption_spec_key_name=encryption_spec_key_name, ) # [END aiplatform_sdk_init_sample]
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from google.auth import credentials as auth_credentials from google.cloud import aiplatform # [START aiplatform_sdk_init_sample] def init_sample( project: Optional[str] = None, location: Optional[str] = None, experiment: Optional[str] = None, staging_bucket: Optional[str] = None, credentials: Optional[auth_credentials.Credentials] = None, encryption_spec_key_name: Optional[str] = None, ): aiplatform.init( project=project, location=location, experiment=experiment, staging_bucket=staging_bucket, credentials=credentials, encryption_spec_key_name=encryption_spec_key_name, ) # [END aiplatform_sdk_init_sample]
Fix an issue with the map being empty on a page transition
import Ember from 'ember'; import Map from '../map'; export default Ember.Component.extend({ setupMap: Ember.on('init', function() { this.map = new Map(); this.map.set('owner', this); }), setupMapElement: Ember.on('didInsertElement', function() { this.map.initializeOptions(); // Checking for the availability of Google Maps JavaScript SDK, the hero Ember.run.later(() => { if (window.google) { this.set('mapElement', this.map.createMapElement()); this.updateMapOptions(); this.updateShapes(); } else { console.error('Please include the Google Maps JavaScript SDK.'); } }); }), updateMapOptionsObserver: Ember.observer('mapOptions', function() { this.updateMapOptions(); }), updateShapesObserver: Ember.observer('markers', 'circles', 'rectangles', 'polygons', function() { Ember.run.once(this, "updateShapes"); }), updateMapOptions() { if (this.get('mapElement')) { this.map.initializeMouseEventCallbacks(); } }, updateShapes() { if (this.get('mapElement')) { this.map.drawAllShapes(); } } });
import Ember from 'ember'; import Map from '../map'; export default Ember.Component.extend({ setupMap: Ember.on('init', function() { this.map = new Map(); this.map.set('owner', this); }), setupMapElement: Ember.on('willInsertElement', function() { this.map.initializeOptions(); // Checking for the availability of Google Maps JavaScript SDK, the hero if (window.google) { this.set('mapElement', this.map.createMapElement()); this.updateMapOptions(); this.updateShapes(); } else { console.error('Please include the Google Maps JavaScript SDK.'); } }), updateMapOptionsObserver: Ember.observer('mapOptions', function() { this.updateMapOptions(); }), updateShapesObserver: Ember.observer('markers', 'circles', 'rectangles', 'polygons', function() { Ember.run.once(this, "updateShapes"); }), updateMapOptions() { if (this.get('mapElement')) { this.map.initializeMouseEventCallbacks(); } }, updateShapes() { if (this.get('mapElement')) { this.map.drawAllShapes(); } } });
Order based on name used in assurance case
package com.rockwellcollins.atc.resolute.analysis.execution; import java.util.Comparator; import org.osate.aadl2.NamedElement; import com.rockwellcollins.atc.resolute.analysis.values.NamedElementValue; public class NamedElementComparator implements Comparator<NamedElement> { @Override public int compare(NamedElement arg0, NamedElement arg1) { if (arg0 == arg1) { return 0; } String text0 = new NamedElementValue(arg0).toString(); String text1 = new NamedElementValue(arg1).toString(); int r = text0.compareToIgnoreCase(text1); if (r != 0) { return r; } r = Integer.compare(arg0.hashCode(), arg1.hashCode()); if (r == 0) { throw new IllegalArgumentException("Unable to order distinct objects via hashcode"); } return r; } }
package com.rockwellcollins.atc.resolute.analysis.execution; import java.util.Comparator; import org.osate.aadl2.NamedElement; public class NamedElementComparator implements Comparator<NamedElement> { @Override public int compare(NamedElement arg0, NamedElement arg1) { if (arg0 == arg1) { return 0; } int r = arg0.getName().compareToIgnoreCase(arg1.getName()); if (r != 0) { return r; } r = Integer.compare(arg0.hashCode(), arg1.hashCode()); if (r == 0) { throw new IllegalArgumentException("Unable to order distinct objects via hashcode"); } return r; } }
Create docs response with correct content type header
<?php namespace Korobi\WebBundle\Controller; use Korobi\WebBundle\Exception\NotImplementedException; use Michelf\Markdown; use Symfony\Component\HttpFoundation\Response; class DocsController extends BaseController { public function renderAction($file) { if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) { throw $this->createNotFoundException("Invalid doc"); } $fn = $this->get('kernel')->getRootDir() . "/../docs/" . $file . ".md"; if (!file_exists($fn) || $file === "README") { throw $this->createNotFoundException("Doc does not exist, " . $fn); } $parser = new Markdown; $parser->no_entities = true; $parser->no_markup = true; return new Response($parser->transform(file_get_contents($fn)), 200, ["Content-Type" => "text/html-sandboxed"]); } public function indexAction() { return $this->render('KorobiWebBundle::docs.html.twig'); } }
<?php namespace Korobi\WebBundle\Controller; use Korobi\WebBundle\Exception\NotImplementedException; use Michelf\Markdown; use Symfony\Component\HttpFoundation\Response; class DocsController extends BaseController { public function renderAction($file) { if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) { throw $this->createNotFoundException("Invalid doc"); } $fn = $this->get('kernel')->getRootDir() . "/../docs/" . $file . ".md"; if (!file_exists($fn) || $file === "README") { throw $this->createNotFoundException("Doc does not exist, " . $fn); } $parser = new Markdown; $parser->no_entities = true; $parser->no_markup = true; return new Response($parser->transform(file_get_contents($fn))); } public function indexAction() { return $this->render('KorobiWebBundle::docs.html.twig'); } }
Add slack integration to logs
<?php trait logTrait { public function fetchLogs() { $this->a_log = Log::getAll(true, array('o_class' => 'CST:'.get_class(), 'fk_what' => 'CST:'.$this->id), array('DESC:t_add')); } public function addLog($msg, $when = -1) { $lm = LoginCM::getInstance(); $lo = new Log(); if ($lm->o_login) { $lo->fk_login = $lm->o_login->id; } else { $lo->fk_login = -1; /* system log */ } $lo->msg = $msg; $lo->o_class = get_class($this); $lo->fk_what = $this->id; $lo->t_add = $when; $lo->insert(); SlackMSG::sendMessage('('.$lo->o_class.')['.$this.']: '.$msg); } }
<?php trait logTrait { public function fetchLogs() { $this->a_log = Log::getAll(true, array('o_class' => 'CST:'.get_class(), 'fk_what' => 'CST:'.$this->id), array('DESC:t_add')); } public function addLog($msg, $when = -1) { $lm = LoginCM::getInstance(); $lo = new Log(); if ($lm->o_login) { $lo->fk_login = $lm->o_login->id; } else { $lo->fk_login = -1; /* system log */ } $lo->msg = $msg; $lo->o_class = get_class($this); $lo->fk_what = $this->id; $lo->t_add = $when; $lo->insert(); } }
Fix ptsname() for big-endian architectures
package termios import ( "fmt" "unsafe" "golang.org/x/sys/unix" ) func open_pty_master() (uintptr, error) { return open_device("/dev/ptmx") } func Ptsname(fd uintptr) (string, error) { var n uint32 err := ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))) if err != nil { return "", err } return fmt.Sprintf("/dev/pts/%d", n), nil } func grantpt(fd uintptr) error { var n uintptr return ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))) } func unlockpt(fd uintptr) error { var n uintptr return ioctl(fd, unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&n))) }
package termios import ( "fmt" "unsafe" "golang.org/x/sys/unix" ) func open_pty_master() (uintptr, error) { return open_device("/dev/ptmx") } func Ptsname(fd uintptr) (string, error) { var n uintptr err := ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))) if err != nil { return "", err } return fmt.Sprintf("/dev/pts/%d", n), nil } func grantpt(fd uintptr) error { var n uintptr return ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))) } func unlockpt(fd uintptr) error { var n uintptr return ioctl(fd, unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&n))) }
Remove gulp html task; done by webpack
var gulp = require('gulp'); var webpack = require('webpack'); var clientConfig = require('./config/webpack.prod.client.js') var serverConfig = require('./config/webpack.prod.server.js') gulp.task('bundle-client', function(done) { webpack( clientConfig ).run(onBundle(done)) }); gulp.task('bundle-server', function(done) { webpack( serverConfig ).run(onBundle(done)) }); gulp.task('move-assets', function() { gulp.src('./src/assets/**/*', {base: './src'}).pipe(gulp.dest('./app/')) }); gulp.task('bundle', ['bundle-client', 'bundle-server']); gulp.task('build', ['bundle', 'move-assets']) // TODO - elctron build function onBundle(done) { return function(err, stats) { if (err) console.log('Error', err); else console.log(stats.toString()); done() } }
var gulp = require('gulp'); var webpack = require('webpack'); var clientConfig = require('./config/webpack.prod.client.js') var serverConfig = require('./config/webpack.prod.server.js') gulp.task('bundle-client', function(done) { webpack( clientConfig ).run(onBundle(done)) }); gulp.task('bundle-server', function(done) { webpack( serverConfig ).run(onBundle(done)) }); gulp.task('move-index', function() { gulp.src('./src/index.html').pipe(gulp.dest('./app')) }); gulp.task('move-assets', ['move-index'], function() { gulp.src('./src/assets/**/*', {base: './src'}).pipe(gulp.dest('./app/')) }); gulp.task('bundle', ['bundle-client', 'bundle-server']); gulp.task('build', ['bundle', 'move-assets']) function onBundle(done) { return function(err, stats) { if (err) console.log('Error', err); else console.log(stats.toString()); done() } }
Adjust TMDB import page URL
import time from RatS.base.base_ratings_uploader import RatingsUploader from RatS.tmdb.tmdb_site import TMDB class TMDBRatingsInserter(RatingsUploader): def __init__(self, args): super(TMDBRatingsInserter, self).__init__(TMDB(args), args) self.url_for_csv_file_upload = self._get_url_for_csv_upload() self.css_id_of_file_input_element = 'csv_file' self.xpath_selector_for_submit_button = "//form[@name='import_csv']//input[@type='submit']" def _get_url_for_csv_upload(self): return 'https://www.themoviedb.org/settings/import-list' def pre_upload_action(self): cookie_accept_button = self.site.browser.find_element_by_id('cookie_notice')\ .find_elements_by_class_name('accept') if cookie_accept_button is not None and len(cookie_accept_button) > 0: cookie_accept_button[0].click() time.sleep(1)
import time from RatS.base.base_ratings_uploader import RatingsUploader from RatS.tmdb.tmdb_site import TMDB class TMDBRatingsInserter(RatingsUploader): def __init__(self, args): super(TMDBRatingsInserter, self).__init__(TMDB(args), args) self.url_for_csv_file_upload = self._get_url_for_csv_upload() self.css_id_of_file_input_element = 'csv_file' self.xpath_selector_for_submit_button = "//form[@name='import_csv']//input[@type='submit']" def _get_url_for_csv_upload(self): return 'https://www.themoviedb.org/account/{username}/import'.format( username=self.site.USERNAME ) def pre_upload_action(self): cookie_accept_button = self.site.browser.find_element_by_id('cookie_notice')\ .find_elements_by_class_name('accept') if cookie_accept_button is not None and len(cookie_accept_button) > 0: cookie_accept_button[0].click() time.sleep(1)
Add useful libs and bump version to 0.1.1
# -*- coding: utf-8 -*- from setuptools import setup, find_packages console_scripts = [ 'makiki = makiki.cli:main_parser', ] requires = [ 'blinker>=1.4', 'gevent==1.1.2', 'gunicorn>=19.0', 'Jinja2>=2.8.1', 'psycogreen>=1.0.0', 'psycopg2>=2.6.2', 'hug>=2.1.2', ] setup( name='makiki', version='0.1.1', description='Web service utils and generator.', long_description='', author='Wang Yanqing', author_email='me@oreki.moe', packages=find_packages(), url='http://github.com/faith0811/makiki', include_package_data=True, entry_points={ 'console_scripts': console_scripts, }, zip_safe=False, install_requires=requires, )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages console_scripts = [ 'makiki = makiki.cli:main_parser', ] requires = [ 'blinker>=1.4', 'gevent>=1.1', 'gunicorn>=19.0', 'Jinja2>=2.8.1', ] setup( name='makiki', version='0.1.0', description='Web service utils and generator.', long_description='', author='Wang Yanqing', author_email='me@oreki.moe', packages=find_packages(), url='http://github.com/faith0811/makiki', include_package_data=True, entry_points={ 'console_scripts': console_scripts, }, zip_safe=False, install_requires=requires, )
Sort registrations. Separate classes of imports. Add API key display.
from django.contrib import admin from server.models import * class ApiKeyAdmin(admin.ModelAdmin): list_display = ('name', 'public_key', 'private_key') class MachineAdmin(admin.ModelAdmin): list_display = ('hostname', 'serial') class MachineGroupAdmin(admin.ModelAdmin): readonly_fields = ('key',) admin.site.register(ApiKey, ApiKeyAdmin) admin.site.register(BusinessUnit) admin.site.register(Condition) admin.site.register(Fact) admin.site.register(HistoricalFact) admin.site.register(InstalledUpdate) admin.site.register(Machine, MachineAdmin) admin.site.register(MachineDetailPlugin) admin.site.register(MachineGroup, MachineGroupAdmin) # admin.site.register(OSQueryColumn) # admin.site.register(OSQueryResult) admin.site.register(PendingAppleUpdate) admin.site.register(PendingUpdate) admin.site.register(Plugin) admin.site.register(PluginScriptRow) admin.site.register(PluginScriptSubmission) admin.site.register(Report) admin.site.register(SalSetting) admin.site.register(UpdateHistory) admin.site.register(UpdateHistoryItem) admin.site.register(UserProfile)
from django.contrib import admin from server.models import * class MachineGroupAdmin(admin.ModelAdmin): readonly_fields = ('key',) class MachineAdmin(admin.ModelAdmin): list_display = ('hostname', 'serial') admin.site.register(UserProfile) admin.site.register(BusinessUnit) admin.site.register(MachineGroup, MachineGroupAdmin) admin.site.register(Machine, MachineAdmin) admin.site.register(Fact) admin.site.register(PluginScriptSubmission) admin.site.register(PluginScriptRow) admin.site.register(HistoricalFact) admin.site.register(Condition) admin.site.register(PendingUpdate) admin.site.register(InstalledUpdate) admin.site.register(PendingAppleUpdate) admin.site.register(ApiKey) admin.site.register(Plugin) admin.site.register(Report) # admin.site.register(OSQueryResult) # admin.site.register(OSQueryColumn) admin.site.register(SalSetting) admin.site.register(UpdateHistory) admin.site.register(UpdateHistoryItem) admin.site.register(MachineDetailPlugin)
Allow specifying which project to udpate with the management command
import datetime from django.core.management.base import BaseCommand, CommandError from pontoon.administration.utils.files import ( update_from_repository, extract_to_database, ) from pontoon.base.models import Project class Command(BaseCommand): args = '<project_id project_id ...>' help = 'Update projects from repositories and store changes to database' def handle(self, *args, **options): projects = Project.objects.all() if args: projects = projects.filter(pk__in=args) for project in projects: try: update_from_repository(project) extract_to_database(project) now = datetime.datetime.now() self.stdout.write( '[%s]: Successfully updated project "%s"\n' % (now, project)) except Exception as e: now = datetime.datetime.now() raise CommandError( '[%s]: UpdateProjectsFromRepositoryError: %s\n' % (now, unicode(e)))
import datetime from django.core.management.base import BaseCommand, CommandError from pontoon.administration.utils.files import ( update_from_repository, extract_to_database, ) from pontoon.base.models import Project class Command(BaseCommand): help = 'Update all projects from their repositories and store changes \ to the database' def handle(self, *args, **options): for project in Project.objects.all(): try: update_from_repository(project) extract_to_database(project) now = datetime.datetime.now() self.stdout.write( '[%s]: Successfully updated project "%s"\n' % (now, project)) except Exception as e: now = datetime.datetime.now() raise CommandError( '[%s]: UpdateProjectsFromRepositoryError: %s\n' % (now, unicode(e)))
Add version dependent inclusion of argparse as a install requirement. For versions prior to 2.7 argparse must be installed manually before mpyq can be installed. By checking the current python version we can make sure to only require the argparse module for versions of python < 2.7. (Patch slightly modified.) Signed-off-by: Aku Kotkavuo <22220c18caede9806cb42c8e2b41136d711673bf@hibana.net>
#!/usr/bin/env python import sys from setuptools import setup from mpyq import __version__ as version setup(name='mpyq', version=version, author='Aku Kotkavuo', author_email='aku@hibana.net', url='http://github.com/arkx/mpyq/', description='A Python library for extracting MPQ (MoPaQ) files.', py_modules=['mpyq'], entry_points={ 'console_scripts': ['mpyq = mpyq:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Games/Entertainment :: Real Time Strategy', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Archiving', ], install_requires=['argparse'] if float(sys.version[:3]) < 2.7 else [], )
#!/usr/bin/env python from mpyq import __version__ as version from setuptools import setup setup(name='mpyq', version=version, author='Aku Kotkavuo', author_email='aku@hibana.net', url='http://github.com/arkx/mpyq/', description='A Python library for extracting MPQ (MoPaQ) files.', py_modules=['mpyq'], entry_points={ 'console_scripts': ['mpyq = mpyq:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Games/Entertainment :: Real Time Strategy', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Archiving', ], )
Fix collection URL. Used the wrong one testing
/*jshint -W106*/ /*global define*/ define(['underscore', 'backbone', 'models/application-model'], function(_, Backbone, models) { 'use strict'; var OSDCollection = Backbone.Collection.extend({ cluster: 1, epoch: 1, added_ms: 0, url: function() { return '/api/v1/cluster/' + this.cluster + '/osd'; }, parse: function(response) { this.epoch = response.epoch; this.added_ms = response.added_ms; return response.osds; }, model: models.OSDModel }); return OSDCollection; });
/*jshint -W106*/ /*global define*/ define(['underscore', 'backbone', 'models/application-model'], function(_, Backbone, models) { 'use strict'; var OSDCollection = Backbone.Collection.extend({ cluster: 1, epoch: 1, added_ms: 0, url: function() { return '/api/v1/cluster/' + this.cluster + '/osds'; }, parse: function(response) { this.epoch = response.epoch; this.added_ms = response.added_ms; return response.osds; }, model: models.OSDModel }); return OSDCollection; });
Use bugsnag key in ENV var
'use strict'; var express = require('express'); var bodyParser = require('body-parser'); var bugsnag = require('bugsnag'); var debug = require('debug')('librarian'); var repoInfoV2 = require('./lib/router/repo-info-v2') var app = express(); var isProduction = app.get('env') === 'production'; var port = process.env.PORT || 5000; // Middlewares if (isProduction) { bugsnag.register(process.env.BUGSNAG); app.use(bugsnag.requestHandler); } app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.get('/v2/repos/:owner/:repo', repoInfoV2); // Error handling if (isProduction) app.use(bugsnag.errorHandler); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
'use strict'; var express = require('express'); var bodyParser = require('body-parser'); var bugsnag = require('bugsnag'); var debug = require('debug')('librarian'); var repoInfoV2 = require('./lib/router/repo-info-v2') var app = express(); var isProduction = app.get('env') === 'production'; var port = process.env.PORT || 5000; // Middlewares if (isProduction) { bugsnag.register("b9d5d0c5b9ecdcf14731645900d4f5be"); app.use(bugsnag.requestHandler); } app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.get('/v2/repos/:owner/:repo', repoInfoV2); // Error handling if (isProduction) app.use(bugsnag.errorHandler); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
Add options support to credentials.
function PluggableCredentialStore() { this._stores = []; } PluggableCredentialStore.prototype.use = function(store) { this._stores.push(store); } PluggableCredentialStore.prototype.get = function(hostname, options, cb) { console.log('GET CREDENTIAL!'); console.log(hostname); if (typeof hostname == 'function') { options = hostname; hostname = undefined; } if (typeof options == 'function') { cb = options; options = undefined; } var self = this , i = 0, e; function next(err, result) { if (!err && result) { return cb(null, result); } e = e || err; // preserve first error var store = self._stores[i++]; if (!store) { return cb(e || new Error('No credential found: ' + hostname)); } store.get(hostname, next); } next(); } module.exports = PluggableCredentialStore;
function PluggableCredentialStore() { this._stores = []; } PluggableCredentialStore.prototype.use = function(store) { this._stores.push(store); } PluggableCredentialStore.prototype.get = function(hostname, cb) { if (typeof hostname == 'function') { cb = hostname; hostname = undefined; } var self = this , i = 0, e; function next(err, result) { if (!err && result) { return cb(null, result); } e = e || err; // preserve first error var store = self._stores[i++]; if (!store) { return cb(e || new Error('No credential found: ' + hostname)); } store.get(hostname, next); } next(); } module.exports = PluggableCredentialStore;
Change syutil dependency link to point at github.
import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="SynapseHomeServer", version="0.1", packages=find_packages(exclude=["tests"]), description="Reference Synapse Home Server", install_requires=[ "syutil==0.0.1", "Twisted>=14.0.0", "service_identity>=1.0.0", "pyasn1", "pynacl", "daemonize", "py-bcrypt", ], dependency_links=[ "git+ssh://git@github.com:matrix-org/syutil.git#egg=syutil-0.0.1", ], setup_requires=[ "setuptools_trial", "setuptools>=1.0.0", # Needs setuptools that supports git+ssh. It's not obvious when support for this was introduced. "mock" ], include_package_data=True, long_description=read("README.rst"), entry_points=""" [console_scripts] synapse-homeserver=synapse.app.homeserver:run """ )
import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="SynapseHomeServer", version="0.1", packages=find_packages(exclude=["tests"]), description="Reference Synapse Home Server", install_requires=[ "syutil==0.0.1", "Twisted>=14.0.0", "service_identity>=1.0.0", "pyasn1", "pynacl", "daemonize", "py-bcrypt", ], dependency_links=[ "git+ssh://git@git.openmarket.com/tng/syutil.git#egg=syutil-0.0.1", ], setup_requires=[ "setuptools_trial", "setuptools>=1.0.0", # Needs setuptools that supports git+ssh. It's not obvious when support for this was introduced. "mock" ], include_package_data=True, long_description=read("README.rst"), entry_points=""" [console_scripts] synapse-homeserver=synapse.app.homeserver:run """ )
Tweak to limit to charge
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Device Schema */ var DeviceSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Device name', trim: true }, created: { type: Date, default: Date.now }, biller: { type: Schema.ObjectId, ref: 'User' }, status: { type: String, default: 'OK', enum: ['OK', 'Breach'] }, customer: { type: Schema.ObjectId, ref: 'User' }, totalCharges: { type: Number, default: 0 }, config: { dataPeriod: { type: Number, default: 1 }, configPeriod: { type: Number, default: 5 }, thresholdWarn: { type: Number, default: 65 }, thresholdLimit: { type: Number, default: 4 } } }); mongoose.model('Device', DeviceSchema);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Device Schema */ var DeviceSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Device name', trim: true }, created: { type: Date, default: Date.now }, biller: { type: Schema.ObjectId, ref: 'User' }, status: { type: String, default: 'OK', enum: ['OK', 'Breach'] }, customer: { type: Schema.ObjectId, ref: 'User' }, totalCharges: { type: Number, default: 0 }, config: { dataPeriod: { type: Number, default: 1 }, configPeriod: { type: Number, default: 5 }, thresholdWarn: { type: Number, default: 65 }, thresholdLimit: { type: Number, default: 75 } } }); mongoose.model('Device', DeviceSchema);
Add crack test to test runner.
#! /usr/bin/env python # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program 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 General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ====================================================================== import unittest from cubic_crystal_crack import * from cubic_elastic_moduli import * ### unittest.main()
#! /usr/bin/env python # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program 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 General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ====================================================================== import unittest from cubic_elastic_moduli import * ### unittest.main()
Add docs / Throw exception for wrong userId
package com.sangdol.experiment.portableDb; import javax.ws.rs.WebApplicationException; import java.util.ArrayList; import java.util.List; /** * Manage horizontally split table names. * * @author hugh */ public class ViewTable { public static final String TABLE_PREFIX = "true_view"; private static final int TABLE_COUNT = 100; private static final List<String> names = new ArrayList<>(); static { for (int i = 0; i < TABLE_COUNT; i++) { names.add(TABLE_PREFIX + i); } } /** * Returns all table names with designated TABLE_PREFIX and TABLE_COUNT. */ public List<String> getAll() { return names; } /** * Returns the allocated table name to the userId. * The index of table name is 0-based, e.g. true_view0, true_view1... */ public String get(int userId) { final int HOST_COUNT_IN_TABLE = 100; int tableNumber = (userId - 1) / HOST_COUNT_IN_TABLE; if (tableNumber >= TABLE_COUNT) throw new WebApplicationException(404); return TABLE_PREFIX + tableNumber; } }
package com.sangdol.experiment.portableDb; import java.util.ArrayList; import java.util.List; /** * @author hugh */ public class ViewTable { public static final String TABLE_PREFIX = "true_view"; private static final int TABLE_COUNT = 100; private static final List<String> names = new ArrayList<>(); static { for (int i = 0; i < TABLE_COUNT; i++) { names.add(TABLE_PREFIX + i); } } public List<String> getAll() { return names; } // TODO throw exception when trying to get a not existing table public String get(int userId) { final int HOST_COUNT_IN_TABLE = 100; int tableNumber = (userId - 1) / HOST_COUNT_IN_TABLE; return TABLE_PREFIX + tableNumber; } }
Add extra logging for node promises
import 'intl'; import 'intl/locale-data/jsonp/en.js'; import * as Aphrodite from 'aphrodite'; import * as AphroditeNoImportant from 'aphrodite/no-important'; import Vue from 'vue'; import VueMeta from 'vue-meta'; import VueRouter from 'vue-router'; import Vuex from 'vuex'; import { i18nSetup } from 'kolibri.utils.i18n'; import KThemePlugin from 'kolibri-components/src/KThemePlugin'; import KContentPlugin from 'kolibri-components/src/content/KContentPlugin'; Aphrodite.StyleSheetTestUtils.suppressStyleInjection(); AphroditeNoImportant.StyleSheetTestUtils.suppressStyleInjection(); // Register Vue plugins and components Vue.use(Vuex); Vue.use(VueRouter); Vue.use(VueMeta); Vue.use(KThemePlugin); Vue.use(KContentPlugin); Vue.config.silent = true; Vue.config.devtools = false; Vue.config.productionTip = false; i18nSetup(true); const csrf = global.document.createElement('input'); csrf.name = 'csrfmiddlewaretoken'; csrf.value = 'csrfmiddlewaretoken'; global.document.body.append(csrf); Object.defineProperty(window, 'scrollTo', { value: () => {}, writable: true }); // Uncomment to see better errors from Node process.on('unhandledRejection', (reason, p) => { console.log('Unhandled Rejection at: Promise', p, 'reason:', reason); console.log(reason.stack); });
import 'intl'; import 'intl/locale-data/jsonp/en.js'; import * as Aphrodite from 'aphrodite'; import * as AphroditeNoImportant from 'aphrodite/no-important'; import Vue from 'vue'; import VueMeta from 'vue-meta'; import VueRouter from 'vue-router'; import Vuex from 'vuex'; import { i18nSetup } from 'kolibri.utils.i18n'; import KThemePlugin from 'kolibri-components/src/KThemePlugin'; import KContentPlugin from 'kolibri-components/src/content/KContentPlugin'; Aphrodite.StyleSheetTestUtils.suppressStyleInjection(); AphroditeNoImportant.StyleSheetTestUtils.suppressStyleInjection(); // Register Vue plugins and components Vue.use(Vuex); Vue.use(VueRouter); Vue.use(VueMeta); Vue.use(KThemePlugin); Vue.use(KContentPlugin); Vue.config.silent = true; Vue.config.devtools = false; Vue.config.productionTip = false; i18nSetup(true); const csrf = global.document.createElement('input'); csrf.name = 'csrfmiddlewaretoken'; csrf.value = 'csrfmiddlewaretoken'; global.document.body.append(csrf); Object.defineProperty(window, 'scrollTo', { value: () => {}, writable: true });
Make report table more clear
// packages const moment = require('moment') const Table = require('cli-table2') // input 'HH:mm', output moment object const composeDateObject = (timeString) => { const hour = timeString.split(':')[0] const minutes = timeString.split(':')[1] return moment({ hour, minutes }) } const printSingleDayReport = (record) => { // instantiate var table = new Table() table.push( { 'Today you worekd:': record.dayReport }, { 'Start:': record.start }, { 'End:': record.end }, { 'Break duration:': record.breakDuration + ' minutes' }, { 'Date:': record.date } ) console.log('\n Today looks like this:\n') // renders the table console.log(table.toString()) console.log('Run moro --help if you need to edit your start, end or break duration for today \n') } // full report of all days const printAllDaysReport = (records) => { // instantiate beautiful table const table = new Table() records.forEach((record) => { const report = record.formattedWorkHours const formattedRecord = {} formattedRecord[record.date] = report table.push(formattedRecord) }) console.log('\n Full report of all days you used moro\n') console.log(table.toString()) } module.exports = { composeDateObject, printSingleDayReport, printAllDaysReport }
// packages const moment = require('moment') const Table = require('cli-table2') // input 'HH:mm', output moment object const composeDateObject = (timeString) => { const hour = timeString.split(':')[0] const minutes = timeString.split(':')[1] return moment({ hour, minutes }) } const printSingleDayReport = (record) => { // instantiate var table = new Table() table.push( { 'Today ': record.dayReport }, { 'Start ': record.start }, { 'End': record.end }, { 'Break duration': record.breakDuration + ' minutes' }, { 'Date': record.date } ) console.log('\n Today looks like this:\n') // renders the table console.log(table.toString()) console.log('Run moro --help if you need to edit your start, end or break duration for today \n') } // full report of all days const printAllDaysReport = (records) => { // instantiate beautiful table const table = new Table() records.forEach((record) => { const report = record.formattedWorkHours const formattedRecord = {} formattedRecord[record.date] = report table.push(formattedRecord) }) console.log('\n Full report of all days you used moro\n') console.log(table.toString()) } module.exports = { composeDateObject, printSingleDayReport, printAllDaysReport }
Remove some unneeded code, as StringHelper.readCommaSeperatedString already trims values
package com.khorn.terraincontrol.configuration.settingType; import com.khorn.terraincontrol.exception.InvalidConfigException; import com.khorn.terraincontrol.util.helpers.StringHelper; import java.util.Arrays; import java.util.List; /** * Reads and writes a list of strings. Strings are read using * {@link StringHelper#readCommaSeperatedString(String)}, and written with a * ", " between each string. * */ class StringListSetting extends Setting<List<String>> { private String[] defaultValue; StringListSetting(String name, String... defaultValue) { super(name); this.defaultValue = defaultValue; } @Override public List<String> getDefaultValue() { return Arrays.asList(defaultValue); } @Override public List<String> read(String string) throws InvalidConfigException { return Arrays.asList(StringHelper.readCommaSeperatedString(string)); } @Override public String write(List<String> value) { return StringHelper.join(value, ", "); } }
package com.khorn.terraincontrol.configuration.settingType; import com.khorn.terraincontrol.exception.InvalidConfigException; import com.khorn.terraincontrol.util.helpers.StringHelper; import java.util.Arrays; import java.util.List; /** * Reads and writes a list of strings. Strings are read using * {@link StringHelper#readCommaSeperatedString(String)}, and written with a * ", " between each string. * */ class StringListSetting extends Setting<List<String>> { private String[] defaultValue; StringListSetting(String name, String... defaultValue) { super(name); this.defaultValue = defaultValue; } @Override public List<String> getDefaultValue() { return Arrays.asList(defaultValue); } @Override public List<String> read(String string) throws InvalidConfigException { String[] split = StringHelper.readCommaSeperatedString(string); for (int i = 0; i < split.length; i++) { // Trimming the values allows "Value1, Value2" instead of // "Value1,Value2" split[i] = split[i]; } return Arrays.asList(split); } @Override public String write(List<String> value) { return StringHelper.join(value, ", "); } }
Load module hooks in global scope.
<?php if (Config::item('hooks.enable')) { Event::add('system.routing', 'arag_module_hooks'); } function arag_module_hooks() { $hooks = Array(); $modules = Config::item('config.hooks'); $modules = is_array($modules) ? array_merge($modules, Array(Router::$module)) : Array(Router::$module); $modules_path = $include_paths = Config::item('core.modules'); foreach ($modules as $module) { $modules_path[] = MODPATH.$module; } Config::set('core.modules', $modules_path); foreach ($modules as $module) { $hooks = array_unique(array_merge($hooks, Kohana::list_files('modules/'.$module.'/hooks', TRUE))); } // To validate the filename extension $ext = -(strlen(EXT)); foreach($hooks as $hook) { if (substr($hook, $ext) === EXT) { // Hook was found, include it include_once $hook; } else { // This should never happen Log::add('error', 'Hook not found: '.$hook); } } Config::set('core.modules', $include_paths); }
<?php if (Config::item('hooks.enable')) { Event::add('system.routing', 'arag_module_hooks'); } function arag_module_hooks() { // All of the hooks are enabled, so we use list_files $hooks = array_unique(Kohana::list_files('modules/'.Router::$module.'/hooks', TRUE)); // To validate the filename extension $ext = -(strlen(EXT)); foreach($hooks as $hook) { if (substr($hook, $ext) === EXT) { // Hook was found, include it include_once $hook; } else { // This should never happen Log::add('error', 'Hook not found: '.$hook); } } }
Fix the detection of JSqueeze in tests when using 2.0
<?php /* * This file is part of the Assetic package, an OpenSky project. * * (c) 2010-2014 OpenSky Project Inc * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Assetic\Test\Filter; use Assetic\Asset\FileAsset; use Assetic\Filter\JSqueezeFilter; /** * @group integration */ class JSqueezeFilterTest extends \PHPUnit_Framework_TestCase { protected function setUp() { if (!class_exists('JSqueeze') && !class_exists('Patchwork\JSqueeze')) { $this->markTestSkipped('JSqueeze is not installed.'); } } public function testRelativeSourceUrlImportImports() { $asset = new FileAsset(__DIR__.'/fixtures/jsmin/js.js'); $asset->load(); $filter = new JSqueezeFilter(); $filter->filterDump($asset); $this->assertEquals(";var a='abc',bbb='u';", $asset->getContent()); } }
<?php /* * This file is part of the Assetic package, an OpenSky project. * * (c) 2010-2014 OpenSky Project Inc * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Assetic\Test\Filter; use Assetic\Asset\FileAsset; use Assetic\Filter\JSqueezeFilter; /** * @group integration */ class JSqueezeFilterTest extends \PHPUnit_Framework_TestCase { protected function setUp() { if (!class_exists('JSqueeze')) { $this->markTestSkipped('JSqueeze is not installed.'); } } public function testRelativeSourceUrlImportImports() { $asset = new FileAsset(__DIR__.'/fixtures/jsmin/js.js'); $asset->load(); $filter = new JSqueezeFilter(); $filter->filterDump($asset); $this->assertEquals(";var a='abc',bbb='u';", $asset->getContent()); } }
Make EspressoConsole.interact conform to InteractiveConsole.interact
# -*- coding: utf-8 -*- from code import InteractiveConsole class EspressoConsole(InteractiveConsole, object): def interact(self, banner = None): banner = """███████╗███████╗██████╗ ██████╗ ███████╗███████╗███████╗ ██████╗ ██╔════╝██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝██╔═══██╗ █████╗ ███████╗██████╔╝██████╔╝█████╗ ███████╗███████╗██║ ██║ ██╔══╝ ╚════██║██╔═══╝ ██╔══██╗██╔══╝ ╚════██║╚════██║██║ ██║ ███████╗███████║██║ ██║ ██║███████╗███████║███████║╚██████╔╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═════╝ """ or banner super(EspressoConsole, self).interact(banner) def raw_input(self, prompt=''): prompt = '[=>]' return super(EspressoConsole, self).raw_input(prompt)
# -*- coding: utf-8 -*- from code import InteractiveConsole class EspressoConsole(InteractiveConsole, object): def interact(self): banner = """███████╗███████╗██████╗ ██████╗ ███████╗███████╗███████╗ ██████╗ ██╔════╝██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝██╔═══██╗ █████╗ ███████╗██████╔╝██████╔╝█████╗ ███████╗███████╗██║ ██║ ██╔══╝ ╚════██║██╔═══╝ ██╔══██╗██╔══╝ ╚════██║╚════██║██║ ██║ ███████╗███████║██║ ██║ ██║███████╗███████║███████║╚██████╔╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═════╝ """ super(EspressoConsole, self).interact(banner) def raw_input(self, prompt=''): prompt = '[=>]' return super(EspressoConsole, self).raw_input(prompt)
Remove setting of 'alert' property
<?php namespace TomIrons\Tuxedo\Mailables; use TomIrons\Tuxedo\Message; use TomIrons\Tuxedo\TuxedoMailable; class AlertMailable extends TuxedoMailable { use Message; /** * The view to use for the message. * * @var string */ public $view = 'tuxedo::templates.alert'; /** * The type of alert. * * @var string|null */ public $alertType = null; /** * The text of the alert. * * @var string|null */ public $alertText = null; /** * Set the alert type and text for the message. * * @param string $type * @param string $text * @return $this */ public function alert($type, $text) { $this->alertType = $type; $this->alertText = $text; return $this; } }
<?php namespace TomIrons\Tuxedo\Mailables; use TomIrons\Tuxedo\Message; use TomIrons\Tuxedo\TuxedoMailable; class AlertMailable extends TuxedoMailable { use Message; /** * The view to use for the message. * * @var string */ public $view = 'tuxedo::templates.alert'; /** * The type of alert. * * @var string|null */ public $alertType = null; /** * The text of the alert. * * @var string|null */ public $alertText = null; /** * Set the alert type and text for the message. * * @param string $type * @param string $text * @return $this */ public function alert($type, $text) { $this->alert = true; $this->alertType = $type; $this->alertText = $text; return $this; } }
Fix tests compile compatibility with 2017.1.2
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.plugins.hil.codeinsight; import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase; import org.intellij.plugins.hil.inspection.HILUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class AddVariableTest extends LightQuickFixTestCase { @NotNull @Override protected String getTestDataPath() { return "test-data/hil/codeinsight/add-variable/"; } @Override protected void setUp() throws Exception { super.setUp(); enableInspectionTools(new HILUnresolvedReferenceInspection()); } public void testSimpleVariable() throws Exception { doSingleTest(); } private void doSingleTest() { doSingleTest(getTestName(false) + ".tf"); } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.plugins.hil.codeinsight; import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase; import org.intellij.plugins.hil.inspection.HILUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class AddVariableTest extends LightQuickFixTestCase { @NotNull @Override protected String getTestDataPath() { return "test-data/hil/codeinsight/add-variable/"; } @Override protected void setUp() throws Exception { super.setUp(); enableInspectionTools(HILUnresolvedReferenceInspection.class); } public void testSimpleVariable() throws Exception { doSingleTest(); } private void doSingleTest() { doSingleTest(getTestName(false) + ".tf"); } }
Fix item list length bug when rendering tabless design
var express = require('express'); var router = express.Router(); var TaxonPresenter = require('./presenters/taxon-presenter.js'); router.get('/', function (req, res) { res.render('index'); }); router.get('/tabbed/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/mvp/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/tabless/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'base'); presenter.curatedContent = presenter.allContent.slice(0,3); presenter.latestContent = presenter.allContent.slice(-3).reverse(); res.render(presenter.viewTemplateName, presenter); }); module.exports = router;
var express = require('express'); var router = express.Router(); var TaxonPresenter = require('./presenters/taxon-presenter.js'); router.get('/', function (req, res) { res.render('index'); }); router.get('/tabbed/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/mvp/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/tabless/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'base'); presenter.curatedContent = presenter.allContent.slice(4); presenter.latestContent = presenter.allContent.slice(-3).reverse(); res.render(presenter.viewTemplateName, presenter); }); module.exports = router;
Fix bill table missed column
{ PDBConst.Name: "bill", PDBConst.Columns: [ { PDBConst.Name: "ID", PDBConst.Attributes: ["int", "not null", "auto_increment", "primary key"] }, { PDBConst.Name: "PID", PDBConst.Attributes: ["int", "not null"] }, { PDBConst.Name: "Datetime", PDBConst.Attributes: ["datetime", "not null"] }, { PDBConst.Name: "Amount", PDBConst.Attributes: ["double(12,2)", "not null"] }, { PDBConst.Name: "Currency", PDBConst.Attributes: ["tinyint", "not null", "default 1"] }, { PDBConst.Name: "Category", PDBConst.Attributes: ["tinyint"] }, { PDBConst.Name: "PaymentMode", PDBConst.Attributes: ["tinyint"] }, { PDBConst.Name: "Note", PDBConst.Attributes: ["varchar(255)"] }] }
{ PDBConst.Name: "bill", PDBConst.Columns: [ { PDBConst.Name: "ID", PDBConst.Attributes: ["int", "not null", "auto_increment", "primary key"] }, { PDBConst.Name: "Datetime", PDBConst.Attributes: ["datetime", "not null"] }, { PDBConst.Name: "Amount", PDBConst.Attributes: ["double(12,2)", "not null"] }, { PDBConst.Name: "Currency", PDBConst.Attributes: ["tinyint", "not null", "default 1"] }, { PDBConst.Name: "Category", PDBConst.Attributes: ["tinyint"] }, { PDBConst.Name: "PaymentMode", PDBConst.Attributes: ["tinyint"] }, { PDBConst.Name: "Note", PDBConst.Attributes: ["varchar(255)"] }] }
Fix issue with getState not bound to store properly
// Function taken from redux source // https://github.com/reactjs/redux/blob/master/src/compose.js function compose(...funcs) { if (funcs.length === 0) { return arg => arg; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce((a, b) => (...args) => a(b(...args))); } // Based on redux implementation of applyMiddleware to support all standard // redux middlewares export default function applyMiddleware(store, ...middlewares) { let dispatch = () => { throw new Error( 'Dispatching while constructing your middleware is not allowed. '+ 'Other middleware would not be applied to this dispatch.' ); }; const middlewareAPI = { getState: store.getState.bind(store), dispatch: (...args) => dispatch(...args) }; middlewares = (middlewares || []).map(middleware => middleware(middlewareAPI)); dispatch = compose(...middlewares)(store.dispatch); store.dispatch = dispatch; return store; }
// Function taken from redux source // https://github.com/reactjs/redux/blob/master/src/compose.js function compose(...funcs) { if (funcs.length === 0) { return arg => arg; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce((a, b) => (...args) => a(b(...args))); } // Based on redux implementation of applyMiddleware to support all standard // redux middlewares export default function applyMiddleware(store, ...middlewares) { let dispatch = () => { throw new Error( 'Dispatching while constructing your middleware is not allowed. '+ 'Other middleware would not be applied to this dispatch.' ); }; const middlewareAPI = { getState: store.getState, dispatch: (...args) => dispatch(...args) }; middlewares = (middlewares || []).map(middleware => middleware(middlewareAPI)); dispatch = compose(...middlewares)(store.dispatch); store.dispatch = dispatch; return store; }
Fix wrong path for package.json
#!/usr/bin/env node const UI = require('console-ui'); const cli = require('cli'); const Project = require('../models/project'); const CommandFactory = require('../commands/command-factory'); const discovery = require('../tasks/discover'); const pkg = require('../package.json'); let options = cli.parse({ environment: [ 'e', 'A configured deployment environment, i.e. "staging", "production".', 'string', 'production'], verbose: ['v', 'Toggle verbosity', 'bool', false], revision: ['r', '("activate" only) revision to activate', 'string', false], activate: ['a', '("deploy" only) directly activate the deployed revision', 'bool', false] }, ['deploy', 'list', 'activate']); let ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, writeLevel: 'INFO' }); ui.write('DeployJS CLI v' + pkg.version); let commandFactory = new CommandFactory(); discovery.list().then(function(dependencies) { let project = new Project(dependencies, ui); return commandFactory.run(cli.command, project, options); }).then(function() { ui.write('DeployJS done!'); }).catch(function(error) { console.log((error && error.message) ? '[ERROR] -- ' + error.message : error); process.exitCode = 1; });
#!/usr/bin/env node const UI = require('console-ui'); const cli = require('cli'); const Project = require('../models/project'); const CommandFactory = require('../commands/command-factory'); const discovery = require('../tasks/discover'); const pkg = require('./package.json'); let options = cli.parse({ environment: [ 'e', 'A configured deployment environment, i.e. "staging", "production".', 'string', 'production'], verbose: ['v', 'Toggle verbosity', 'bool', false], revision: ['r', '("activate" only) revision to activate', 'string', false], activate: ['a', '("deploy" only) directly activate the deployed revision', 'bool', false] }, ['deploy', 'list', 'activate']); let ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, writeLevel: 'INFO' }); ui.write('DeployJS CLI v' + pkg.version); let commandFactory = new CommandFactory(); discovery.list().then(function(dependencies) { let project = new Project(dependencies, ui); return commandFactory.run(cli.command, project, options); }).then(function() { ui.write('DeployJS done!'); }).catch(function(error) { console.log((error && error.message) ? '[ERROR] -- ' + error.message : error); process.exitCode = 1; });
Remove useless ternary operator over undefined
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import _ from 'lodash'; import { connect } from 'react-redux'; import { fetchMetersDetailsIfNeeded } from '../../actions/meters'; import { fetchGroupsDetailsIfNeeded, changeDisplayedGroups } from '../../actions/groups'; import GroupMainComponent from '../../components/groups/GroupMainComponent'; function mapStateToProps(state) { const sortedGroups = _.sortBy(_.values(state.groups.byGroupID).map(group => ({ id: group.id, name: group.name.trim() })), 'name'); const sortedMeters = _.sortBy(_.values(state.meters.byMeterID).map(meter => ({ id: meter.id, name: meter.name.trim() })), 'name'); const selectGroups = state.groups.selectedGroups; return { groups: sortedGroups, meters: sortedMeters, selectedGroups: selectGroups, displayMode: state.groups.displayMode }; } function mapDispatchToProps(dispatch) { return { selectGroups: newSelectedGroupIDs => dispatch(changeDisplayedGroups(newSelectedGroupIDs)), fetchGroupsDetailsIfNeeded: () => dispatch(fetchGroupsDetailsIfNeeded()), fetchMetersDetailsIfNeeded: () => dispatch(fetchMetersDetailsIfNeeded()), }; } export default connect(mapStateToProps, mapDispatchToProps)(GroupMainComponent);
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import _ from 'lodash'; import { connect } from 'react-redux'; import { fetchMetersDetailsIfNeeded } from '../../actions/meters'; import { fetchGroupsDetailsIfNeeded, changeDisplayedGroups } from '../../actions/groups'; import GroupMainComponent from '../../components/groups/GroupMainComponent'; function mapStateToProps(state) { const sortedGroups = _.sortBy(_.values(state.groups.byGroupID).map(group => ({ id: group.id, name: group.name.trim() })), 'name'); const sortedMeters = _.sortBy(_.values(state.meters.byMeterID).map(meter => ({ id: meter.id, name: meter.name.trim() })), 'name'); const selectGroups = undefined ? [] : state.groups.selectedGroups; return { groups: sortedGroups, meters: sortedMeters, selectedGroups: selectGroups, displayMode: state.groups.displayMode }; } function mapDispatchToProps(dispatch) { return { selectGroups: newSelectedGroupIDs => dispatch(changeDisplayedGroups(newSelectedGroupIDs)), fetchGroupsDetailsIfNeeded: () => dispatch(fetchGroupsDetailsIfNeeded()), fetchMetersDetailsIfNeeded: () => dispatch(fetchMetersDetailsIfNeeded()), }; } export default connect(mapStateToProps, mapDispatchToProps)(GroupMainComponent);
Fix the regex to match the license reported by licensee At least with licensee 9.2.1 there is no leading '\n' anymore. Fix the regex to match in any case.
// Copyright 2017 TODO Group. All rights reserved. // Licensed under the Apache License, Version 2.0. const isWindows = require('is-windows') const spawnSync = require('child_process').spawnSync module.exports = function (targetDir, options) { const expected = /License: ([^\n]+)/ const licenseeOutput = spawnSync(isWindows() ? 'licensee.bat' : 'licensee', [targetDir]).stdout if (licenseeOutput == null) { return { failures: [`Licensee is not installed`] } } const results = licenseeOutput.toString().match(expected) if (results != null) { // License: Apache License 2.0 const identified = results[1] return { passes: [`Licensee identified the license for project: ${identified}`] } } else { return { failures: ['Licensee did not identify a license for project'] } } }
// Copyright 2017 TODO Group. All rights reserved. // Licensed under the Apache License, Version 2.0. const isWindows = require('is-windows') const spawnSync = require('child_process').spawnSync module.exports = function (targetDir, options) { const expected = '\nLicense: ([^\n]*)' const licenseeOutput = spawnSync(isWindows() ? 'licensee.bat' : 'licensee', [targetDir]).stdout if (licenseeOutput == null) { return { failures: [`Licensee is not installed`] } } const results = licenseeOutput.toString().match(expected) if (results != null) { // License: Apache License 2.0 const identified = results[1] return { passes: [`Licensee identified the license for project: ${identified}`] } } else { return { failures: ['Licensee did not identify a license for project'] } } }
Update helper to not look for success message.
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. * */ export const allowedAmpModes = { standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAmpAndSetMode = async ( mode ) => { await activatePlugin( 'amp' ); await setAMPMode( mode ); }; /** * Set AMP Mode * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const setAMPMode = async ( mode ) => { // Test to be sure that the passed mode is known. await expect( Object.keys( allowedAmpModes ) ).toContain( mode ); // Set the AMP mode await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); };
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. * */ export const allowedAmpModes = { standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAmpAndSetMode = async ( mode ) => { await activatePlugin( 'amp' ); await setAMPMode( mode ); }; /** * Set AMP Mode * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const setAMPMode = async ( mode ) => { // Test to be sure that the passed mode is known. expect( Object.keys( allowedAmpModes ) ).toContain( mode ); // Set the AMP mode await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); await page.waitForSelector( '#setting-error-settings_updated' ); await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } ); };
Fix for reports not showing up for not logged in users
AuthRouteController = RouteController.extend({ onBeforeAction: function() { if(_.isNull(Meteor.user())) { Router.go(Router.path('ConceptIndex')); } } }); ConceptIndexController = AuthRouteController.extend({ waitOn: function () { }, data: function () { }, action: function () { this.render(); } }); ReportListController = RouteController.extend({ waitOn: function () { return Meteor.subscribe('reports'); }, data: function () { }, action: function () { this.render(); } }); AdminCreateReportController = AuthRouteController.extend({ waitOn: function () { return [ Meteor.subscribe('images'), Meteor.subscribe('files') ]; }, data: function () { }, action: function () { this.render(); } }); ReportViewController = RouteController.extend({ waitOn: function () { return Meteor.subscribe('report', this.params._id); }, data: function () { return Reports.findOne({_id: this.params._id}); }, action: function () { this.render(); } });
AuthRouteController = RouteController.extend({ onBeforeAction: function() { if(_.isNull(Meteor.user())) { Router.go(Router.path('ConceptIndex')); } } }); ConceptIndexController = AuthRouteController.extend({ waitOn: function () { }, data: function () { }, action: function () { this.render(); } }); ReportListController = RouteController.extend({ waitOn: function () { return Meteor.subscribe('reports'); }, data: function () { }, action: function () { this.render(); } }); AdminCreateReportController = AuthRouteController.extend({ waitOn: function () { return [ Meteor.subscribe('images'), Meteor.subscribe('files') ]; }, data: function () { }, action: function () { this.render(); } }); ReportViewController = AuthRouteController.extend({ waitOn: function () { return Meteor.subscribe('report', this.params._id); }, data: function () { return Reports.findOne({_id: this.params._id}); }, action: function () { this.render(); } });
Allow $().BHMClient indexpage to be string Fix issue with client indexpage property having to be an array
<?php require('mysql.php'); //var_dump($_GET); function makequery($path) { return "SELECT bhm_helpers.* FROM bhm_pages, bhm_relationships, bhm_helpers WHERE 1=1 AND bhm_pages.url = '$path' AND bhm_pages.id = bhm_relationships.page_id AND bhm_relationships.help_id = bhm_helpers.id "; } $path = $_GET['collection']['pathname']; $res = $db->query(makequery($path)) or die(mysqli_error($db)); if ($res->num_rows < 1) { $index = $_GET['collection']['indexpage']; if (gettype($index) != 'array') { $p = $path.$index; $res = $db->query(makequery($p)) or die(mysqli_error($db)); } else { for($i=0; $i < count($index); $i++ ) { $p = $path.$index[$i]; echo $p; $res = $db->query(makequery($p)) or die(mysqli_error($db)); if ($res->num_rows > 0) break; } } } echo json_encode($res->fetch_all(MYSQLI_ASSOC), JSON_PRETTY_PRINT); ?>
<?php require('../mysql-creds.php'); //var_dump($_GET); function makequery($path) { return "SELECT bhm_helpers.* FROM bhm_pages, bhm_relationships, bhm_helpers WHERE 1=1 AND bhm_pages.url = '$path' AND bhm_pages.id = bhm_relationships.page_id AND bhm_relationships.help_id = bhm_helpers.id "; } $path = $_GET['collection']['pathname']; $res = $db->query(makequery($path)) or die(mysqli_error($db)); if ($res->num_rows < 1) { $index = $_GET['collection']['indexpage']; for($i=0; $i < count($index); $i++ ) { $p = $path.$index[$i]; $res = $db->query(makequery($p)) or die(mysqli_error($db)); if ($res->num_rows > 0) break; } } echo json_encode($res->fetch_all(MYSQLI_ASSOC), JSON_PRETTY_PRINT); ?>
Add Cabal & Opam dependency types
/** * Copyright (C) 2017 White Source Ltd. * * 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.whitesource.agent.api.model; /** * Enum for describing the type of dependency sent to the server. * * @author tom.shapira */ public enum DependencyType { MAVEN, GRADLE, NPM, BOWER, GRUNT, GO, PYTHON, RUBY, NUGET, PHP, RPM, DEBIAN, COCOAPODS, HEX, R, CRATE, CABAL, OPAM; @Override public String toString() { switch(this) { case COCOAPODS: return "CocoaPods"; case CRATE: return "Crate"; case CABAL: return "Cabal"; case OPAM: return "Opam"; default: return super.toString(); } } }
/** * Copyright (C) 2017 White Source Ltd. * * 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.whitesource.agent.api.model; /** * Enum for describing the type of dependency sent to the server. * * @author tom.shapira */ public enum DependencyType { MAVEN, GRADLE, NPM, BOWER, GRUNT, GO, PYTHON, RUBY, NUGET, PHP, RPM, DEBIAN, COCOAPODS, HEX, R, CRATE; @Override public String toString() { switch(this) { case COCOAPODS: return "CocoaPods"; case CRATE: return "Crate"; default: return super.toString(); } } }
Fix docstring in `PacmanUnpackGroup` fact.
from pyinfra.api import FactBase from .util.packaging import parse_packages PACMAN_REGEX = r'^([0-9a-zA-Z\-]+)\s([0-9\._+a-z\-]+)' class PacmanUnpackGroup(FactBase): ''' Returns a list of actual packages belonging to the provided package name, expanding groups or virtual packages. .. code:: python [ 'package_name', ] ''' requires_command = 'pacman' default = list def command(self, name): # Accept failure here (|| true) for invalid/unknown packages return 'pacman -S --print-format "%n" {0} || true'.format(name) def process(self, output): return output class PacmanPackages(FactBase): ''' Returns a dict of installed pacman packages: .. code:: python { 'package_name': ['version'], } ''' command = 'pacman -Q' requires_command = 'pacman' default = dict def process(self, output): return parse_packages(PACMAN_REGEX, output)
from pyinfra.api import FactBase from .util.packaging import parse_packages PACMAN_REGEX = r'^([0-9a-zA-Z\-]+)\s([0-9\._+a-z\-]+)' class PacmanUnpackGroup(FactBase): ''' Returns a list of actual packages belonging to the provided package name, expanding groups or virtual packages. .. code:: python [ 'package_name', [ ''' requires_command = 'pacman' default = list def command(self, name): # Accept failure here (|| true) for invalid/unknown packages return 'pacman -S --print-format "%n" {0} || true'.format(name) def process(self, output): return output class PacmanPackages(FactBase): ''' Returns a dict of installed pacman packages: .. code:: python { 'package_name': ['version'], } ''' command = 'pacman -Q' requires_command = 'pacman' default = dict def process(self, output): return parse_packages(PACMAN_REGEX, output)
Check the existence of env_fields.json file
'use strict' const cozy = require('./cozyclient') const fs = require('fs') const path = require('path') // account id path is mandatory in the cli let accountIdPath = process.argv[2] if (accountIdPath) { accountIdPath = path.resolve(accountIdPath) } else { console.log(`Account id file not found : ${accountIdPath}`) process.exit(0) } let fieldsFilePath = process.argv[3] if (fieldsFilePath) { fieldsFilePath = path.resolve(fieldsFilePath) } else { console.log(`Fields file not found : ${fieldsFilePath} Please copy the env_fields.json.template file and fill the credentials`) process.exit(0) } if (!fs.existsSync(fieldsFilePath)) { console.log(`Fields file not found : ${fieldsFilePath} Please copy the env_fields.json.template file and fill the credentials`) process.exit(0) } cozy.data.create('io.cozy.accounts', { account_type: 'dev_account', status: 'PENDING', auth: JSON.parse(fs.readFileSync(fieldsFilePath), 'utf-8') }) .then(doc => { fs.writeFileSync(accountIdPath, doc._id) console.log('account created') console.log('account id in ' + accountIdPath) }) .catch(err => console.log(err, 'there was an error'))
'use strict' const cozy = require('./cozyclient') const fs = require('fs') const path = require('path') // account id path is mandatory in the cli let accountIdPath = process.argv[2] if (accountIdPath) { accountIdPath = path.resolve(accountIdPath) } else { console.log(`Account id file not found : ${accountIdPath}`) process.exit(1) } let fieldsFilePath = process.argv[3] if (fieldsFilePath) { fieldsFilePath = path.resolve(fieldsFilePath) } else { console.log(`Fields file not found : ${fieldsFilePath}`) process.exit(1) } cozy.data.create('io.cozy.accounts', { account_type: 'dev_account', status: 'PENDING', auth: JSON.parse(fs.readFileSync(fieldsFilePath), 'utf-8') }) .then(doc => { fs.writeFileSync(accountIdPath, doc._id) console.log('account created') console.log('account id in ' + accountIdPath) }) .catch(err => console.log(err, 'there was an error'))
Add curly brackets for better readability
<?php /** * We made this code. * By pH7 (Pierre-Henry SORIA). */ namespace PFBC\Validation; use PH7\Framework\Mvc\Model\DbConfig; class Password extends \PFBC\Validation { protected $iMin, $iMax; public function __construct() { parent::__construct(); $this->iMin = DbConfig::getSetting('minPasswordLength'); $this->iMax = DbConfig::getSetting('maxPasswordLength'); $this->message = t('Error: Your password has to contain from %0% to %1% characters.', $this->iMin, $this->iMax); } public function isValid($sValue) { if ($this->isNotApplicable($sValue)) { return true; } return $this->oValidate->password($sValue, $this->iMin, $this->iMax); } }
<?php /** * We made this code. * By pH7 (Pierre-Henry SORIA). */ namespace PFBC\Validation; use PH7\Framework\Mvc\Model\DbConfig; class Password extends \PFBC\Validation { protected $iMin, $iMax; public function __construct() { parent::__construct(); $this->iMin = DbConfig::getSetting('minPasswordLength'); $this->iMax = DbConfig::getSetting('maxPasswordLength'); $this->message = t('Error: Your password has to contain from %0% to %1% characters.', $this->iMin, $this->iMax); } public function isValid($sValue) { if ($this->isNotApplicable($sValue)) return true; return $this->oValidate->password($sValue, $this->iMin, $this->iMax); } }
Allow filling content of a blob from file path
#!/usr/bin/env node /** * Jit hash-object */ var program = require('commander'), fs = require('fs'), path = require('path'), Blob = require('./common/blob'); program // TODO .option('-t <type>', 'object type') // TODO .option('-w', 'write the object into the object database') .option('--stdin', 'read the object from stdin') // TODO .option('--stdin-paths', 'read file names from stdin') // TODO .option('--no-filters store file as is without filters') // TODO .option('--path <file>', 'process file as it were from this path') .parse(process.argv); content = ''; if(program.stdin) { process.stdin.on('data', function(chunk) { content += chunk; }) process.stdin.on('end', function() { run(); }) } else if(program.args.length > 0) { var file_path = path.resolve(program.args[0]); fs.readFile(file_path, 'utf8', function(err, data) { content = data; run(); }); } else { run(); } function run() { var blob = new Blob(); blob.hash_object({content: content}, function(err) { // console.log(blob); }); }
#!/usr/bin/env node /** * Jit hash-object */ var program = require('commander'), Blob = require('./common/blob'); program // TODO .option('-t <type>', 'object type') // TODO .option('-w', 'write the object into the object database') // TODO .option('--stdin', 'read the object from stdin') // TODO .option('--stdin-paths', 'read file names from stdin') // TODO .option('--no-filters store file as is without filters') // TODO .option('--path <file>', 'process file as it were from this path') .parse(process.argv); content = ''; if(program.stdin) { process.stdin.on('data', function(chunk) { content += chunk; }) process.stdin.on('end', function() { run(); }) } else { run(); } function run() { Blob.hash_object({content: content}, function(err, blob) { console.log(blob) }); }
Remove error handlers for now.
require('node-jsx').install({extension:'.jsx'}); var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var bowlScoreApi = require('./lib/server/api'); var config = require('./lib/config'); var app = express(); // uncomment after placing your favicon in /public app.use(favicon(__dirname + '/public/favicon.ico')); // logs each request, response code, and response time app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/api', bowlScoreApi); module.exports = app;
require('node-jsx').install({extension:'.jsx'}); var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var bowlScoreApi = require('./lib/server/api'); var config = require('./lib/config'); var app = express(); // uncomment after placing your favicon in /public app.use(favicon(__dirname + '/public/favicon.ico')); // logs each request, response code, and response time app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/api', bowlScoreApi); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
Add map recycling in BitmapMatcher
package com.jraska.falcon.sample.matchers; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.io.File; /** * Utility class to check if the file is bitmap */ public class BitmapFileMatcher extends TypeSafeMatcher<File> implements Matcher<File> { //region Matcher impl @Override protected boolean matchesSafely(File item) { Bitmap bitmap = BitmapFactory.decodeFile(item.getAbsolutePath()); boolean matches = bitmap != null && bitmap.getWidth() > 0 && bitmap.getHeight() > 0; if (bitmap != null) { bitmap.recycle(); } return matches; } @Override public void describeTo(Description description) { description.appendText("The file is Bitmap"); } @Override protected void describeMismatchSafely(File item, Description mismatchDescription) { mismatchDescription.appendText(" file ").appendText(item.getAbsolutePath()); mismatchDescription.appendText(" was not decoded as Bitmap"); } //endregion //region Methods public static Matcher<File> isBitmap() { return new BitmapFileMatcher(); } //endregion }
package com.jraska.falcon.sample.matchers; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.io.File; /** * Utility class to check if the file is bitmap */ public class BitmapFileMatcher extends TypeSafeMatcher<File> implements Matcher<File> { //region Matcher impl @Override protected boolean matchesSafely(File item) { Bitmap bitmap = BitmapFactory.decodeFile(item.getAbsolutePath()); return bitmap != null && bitmap.getWidth() > 0 && bitmap.getHeight() > 0; } @Override public void describeTo(Description description) { description.appendText("The file is Bitmap"); } @Override protected void describeMismatchSafely(File item, Description mismatchDescription) { mismatchDescription.appendText(" file ").appendText(item.getAbsolutePath()); mismatchDescription.appendText(" was not decoded as Bitmap"); } //endregion //region Methods public static Matcher<File> isBitmap() { return new BitmapFileMatcher(); } //endregion }
Update to new version :)
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='trufflehog', version='0.1.1', packages=['trufflehog'], include_package_data=True, license='MIT', description='Track Django model instances', long_description=README, url='https://github.com/jleeothon/trufflehog', author='Johnny Lee', author_email='jleeothon@outlook.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], install_requires=['django'], tests_require=['django'], )
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='trufflehog', version='0.1', packages=['trufflehog'], include_package_data=True, license='MIT', description='Track Django model instances!', long_description=README, url='https://github.com/jleeothon/trufflehog', author='Johnny Lee', author_email='jleeothon@outlook.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], install_requires=['django'], tests_require=['django'], )
Change doc setting for release.
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = False """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
Put back an import that my IDE incorrectly flagged as unused
# -*- coding: utf-8 -*- """ Created on Fri Mar 30 18:27:25 2012 Author: Josef Perktold """ from statsmodels.sandbox.stats.multicomp import tukeyhsd, MultiComparison def pairwise_tukeyhsd(endog, groups, alpha=0.05): '''calculate all pairwise comparisons with TukeyHSD confidence intervals this is just a wrapper around tukeyhsd method of MultiComparison Parameters ---------- endog : ndarray, float, 1d response variable groups : ndarray, 1d array with groups, can be string or integers alpha : float significance level for the test Returns ------- results : TukeyHSDResults instance A results class containing relevant data and some post-hoc calculations See Also -------- MultiComparison tukeyhsd statsmodels.sandbox.stats.multicomp.TukeyHSDResults ''' return MultiComparison(endog, groups).tukeyhsd(alpha=alpha)
# -*- coding: utf-8 -*- """ Created on Fri Mar 30 18:27:25 2012 Author: Josef Perktold """ from statsmodels.sandbox.stats.multicomp import MultiComparison def pairwise_tukeyhsd(endog, groups, alpha=0.05): '''calculate all pairwise comparisons with TukeyHSD confidence intervals this is just a wrapper around tukeyhsd method of MultiComparison Parameters ---------- endog : ndarray, float, 1d response variable groups : ndarray, 1d array with groups, can be string or integers alpha : float significance level for the test Returns ------- results : TukeyHSDResults instance A results class containing relevant data and some post-hoc calculations See Also -------- MultiComparison tukeyhsd statsmodels.sandbox.stats.multicomp.TukeyHSDResults ''' return MultiComparison(endog, groups).tukeyhsd(alpha=alpha)
Declare MIT license and support for Python 2 and 3
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.txt')) as f: long_description = f.read() setup( name="pyshark", version="0.3.7.2", packages=find_packages(), package_data={'': ['*.ini', '*.pcapng']}, # Temporarily using trollis 1.0.4 until issue https://github.com/haypo/trollius/issues/4 is resolved. install_requires=['lxml', 'py', 'trollius==1.0.4', 'logbook'], tests_require=['mock', 'pytest'], url="https://github.com/KimiNewt/pyshark", long_description=long_description, author="KimiNewt", description="Python wrapper for tshark, allowing python packet parsing using wireshark dissectors", keywords="wireshark capture packets parsing packet", use_2to3=True, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.txt')) as f: long_description = f.read() setup( name="pyshark", version="0.3.7.2", packages=find_packages(), package_data={'': ['*.ini', '*.pcapng']}, # Temporarily using trollis 1.0.4 until issue https://github.com/haypo/trollius/issues/4 is resolved. install_requires=['lxml', 'py', 'trollius==1.0.4', 'logbook'], tests_require=['mock', 'pytest'], url="https://github.com/KimiNewt/pyshark", long_description=long_description, author="KimiNewt", description="Python wrapper for tshark, allowing python packet parsing using wireshark dissectors", keywords="wireshark capture packets parsing packet", use_2to3=True, )
Fix for installing with PIP
#!/usr/bin/env python """ A light wrapper for Cybersource SOAP Toolkit API """ from setuptools import setup setup( name='pycybersource', version='0.1.2alpha', description='A light wrapper for Cybersource SOAP Toolkit API', author='Eric Bartels', author_email='ebartels@gmail.com', url='', packages=['pycybersource'], platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='cybersource payment soap suds api wrapper', requires=['suds'], install_requires=['suds-jurko>=0.6'], test_suite='pycybersource.tests', )
#!/usr/bin/env python """ A light wrapper for Cybersource SOAP Toolkit API """ from setuptools import setup import pycybersource setup( name='pycybersource', version=pycybersource.__version__, description='A light wrapper for Cybersource SOAP Toolkit API', author='Eric Bartels', author_email='ebartels@gmail.com', url='', packages=['pycybersource'], platforms=['Platform Independent'], license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='cybersource payment soap suds api wrapper', requires=['suds'], install_requires=['suds-jurko>=0.6'], test_suite='pycybersource.tests', )