text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix version autodetection from git tags
""" iniconfig: brain-dead simple config-ini parsing. compatible CPython 2.3 through to CPython 3.2, Jython, PyPy (c) 2010 Ronny Pfannschmidt, Holger Krekel """ from setuptools import setup def main(): with open('README.txt') as fp: readme = fp.read() setup( name='iniconfig', packages=['iniconfig'], package_dir={'': 'src'}, description='iniconfig: brain-dead simple config-ini parsing', long_description=readme, use_scm_version=True, url='http://github.com/RonnyPfannschmidt/iniconfig', license='MIT License', platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'], author='Ronny Pfannschmidt, Holger Krekel', author_email=( '[email protected], [email protected]'), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], include_package_data=True, zip_safe=False, ) if __name__ == '__main__': main()
""" iniconfig: brain-dead simple config-ini parsing. compatible CPython 2.3 through to CPython 3.2, Jython, PyPy (c) 2010 Ronny Pfannschmidt, Holger Krekel """ from setuptools import setup def main(): with open('README.txt') as fp: readme = fp.read() setup( name='iniconfig', packages=['iniconfig'], package_dir={'': 'src'}, description='iniconfig: brain-dead simple config-ini parsing', long_description=readme, url='http://github.com/RonnyPfannschmidt/iniconfig', license='MIT License', platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'], author='Ronny Pfannschmidt, Holger Krekel', author_email=( '[email protected], [email protected]'), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], include_package_data=True, zip_safe=False, ) if __name__ == '__main__': main()
Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve
from mono_master import MonoMasterPackage from bockbuild.util.util import * class MonoMasterEncryptedPackage (MonoMasterPackage): def __init__(self): MonoMasterPackage.__init__ (self) self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types']) def prep(self): MonoMasterPackage.prep(self) retry (self.checkout_mono_extensions) def checkout_mono_extensions(self): ext = '[email protected]:xamarin/mono-extensions.git' dirname = os.path.join(self.profile.build_root, "mono-extensions") if not os.path.exists(dirname): self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname)) self.pushd(dirname) try: self.sh('%{git} clean -xffd') self.sh('%{git} fetch --all --prune') if "pr/" not in self.git_branch: self.sh('%' + '{git} checkout origin/%s' % self.git_branch) else: self.sh('%{git} checkout origin/master') self.sh ('%{git} reset --hard') except Exception as e: self.rm_if_exists (dirname) raise finally: info ('Mono crypto extensions (rev. %s)' % git_get_revision (self)) self.popd () MonoMasterEncryptedPackage()
from mono_master import MonoMasterPackage from bockbuild.util.util import * class MonoMasterEncryptedPackage (MonoMasterPackage): def __init__(self): MonoMasterPackage.__init__ (self) self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types']) def prep(self): MonoMasterPackage.prep(self) retry (self.checkout_mono_extensions) def checkout_mono_extensions(self): ext = '[email protected]:xamarin/mono-extensions.git' dirname = os.path.join(self.profile.build_root, "mono-extensions") if not os.path.exists(dirname): self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname)) self.pushd(dirname) try: self.sh('%{git} clean -xffd') self.sh('%{git} fetch --all --prune') if "pr/" not in self.git_branch: self.sh('%' + '{git} checkout origin/%s' % self.git_branch) else: self.sh('%{git} checkout origin/master') except Exception as e: self.rm_if_exists (dirname) raise finally: info ('Mono crypto extensions (rev. %s)' % git_get_revision (self)) self.popd () MonoMasterEncryptedPackage()
Add author badge to comments
<ul> @foreach($comments as $comment) <li> <div> {{-- Comment owner --}} <label class="text-info">{{ $comment->user->name }} </label> @if($comment->user->ownsArticle($comment->article)) <span class="badge badge-info">author</span> @endif <span> - {{ $comment->created_at->diffForHumans() }}</span> </div> <div class="comment-body"> <div class="row"> {{-- Comment Body --}} <div class="col-md-9"> {{ $comment->body }} </div> {{-- Comment action buttons --}} @if(Gate::check('update', $comment) || Gate::check('delete', $comment)) <div class="col-md-3"> {{-- Edit comment button --}} @can('update', $comment) <a class="btn btn-primary btn-sm" href="{{ route('comment.edit', ['comment' => $comment->id]) }}">Edit</a> @endcan {{-- Delete comment button --}} @can('delete', $comment) <a class="btn btn-danger btn-sm deleteBtn" data-toggle="modal" data-target="#deleteConfirmModal" data-message="Are you sure you want to delete this comment ?" data-action="{{ route('comment.delete', ['comment' => $comment->id]) }}" href="#">Delete</a> @endcan </div> @endif </div> </div> @endforeach </ul> {{-- Comments pagination links --}} <div class="row justify-content-center"> {{ $comments->links('vendor.pagination.simple-bootstrap-4') }} </div>
<ul> @foreach($comments as $comment) <li> <div> {{-- Comment owner --}} <label class="text-info">{{ $comment->user->name }} </label> <span> - {{ $comment->created_at->diffForHumans() }}</span> </div> <div class="comment-body"> <div class="row"> {{-- Comment Body --}} <div class="col-md-9"> {{ $comment->body }} </div> {{-- Comment action buttons --}} @if(Gate::check('update', $comment) || Gate::check('delete', $comment)) <div class="col-md-3"> {{-- Edit comment button --}} @can('update', $comment) <a class="btn btn-primary btn-sm" href="{{ route('comment.edit', ['comment' => $comment->id]) }}">Edit</a> @endcan {{-- Delete comment button --}} @can('delete', $comment) <a class="btn btn-danger btn-sm deleteBtn" data-toggle="modal" data-target="#deleteConfirmModal" data-message="Are you sure you want to delete this comment ?" data-action="{{ route('comment.delete', ['comment' => $comment->id]) }}" href="#">Delete</a> @endcan </div> @endif </div> </div> @endforeach </ul> {{-- Comments pagination links --}} <div class="row justify-content-center"> {{ $comments->links('vendor.pagination.simple-bootstrap-4') }} </div>
Fix python 2 testing issue
__all__ = [ 'test', ] import unittest import fnmatch import os try: from colour_runner.runner import ColourTextTestRunner as TextTestRunner except ImportError: from unittest import TextTestRunner def test(close=False): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. @notes: This can be executed from either the command line of within a standard Python environment. @example: ```bash $ python -m PVGeo test ``` ```py >>> import PVGeo >>> PVGeo.test() ``` """ test_file_strings = [] for root, dirnames, filenames in os.walk(os.path.dirname(__file__)): for filename in fnmatch.filter(filenames, '__test__.py'): test_file_strings.append(os.path.join(root, filename)) # Remove extensions and change to module import syle test_file_strings = [s.replace(os.path.dirname(os.path.dirname(__file__)), '') for s in test_file_strings] print(test_file_strings) idx = 0 if test_file_strings[0][0] == '/': idx = 1 module_strings = [mod[idx:len(mod)-3].replace('/', '.') for mod in test_file_strings] suites = [unittest.defaultTestLoader.loadTestsFromName(mod) for mod in module_strings] testSuite = unittest.TestSuite(suites) run = TextTestRunner(verbosity=2).run(testSuite) if close: exit(len(run.failures) > 0 or len(run.errors) > 0) return run
__all__ = [ 'test', ] import unittest import fnmatch import os try: from colour_runner.runner import ColourTextTestRunner as TextTestRunner except ImportError: from unittest import TextTestRunner def test(close=False): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. @notes: This can be executed from either the command line of within a standard Python environment. @example: ```bash $ python -m PVGeo test ``` ```py >>> import PVGeo >>> PVGeo.test() ``` """ test_file_strings = [] for root, dirnames, filenames in os.walk(os.path.dirname(__file__)): for filename in fnmatch.filter(filenames, '__test__.py'): test_file_strings.append(os.path.join(root, filename)) # Remove extensions and change to module import syle test_file_strings = [s.replace(os.path.dirname(os.path.dirname(__file__)), '') for s in test_file_strings] module_strings = [mod[1:len(mod)-3].replace('/', '.') for mod in test_file_strings] suites = [unittest.defaultTestLoader.loadTestsFromName(mod) for mod in module_strings] testSuite = unittest.TestSuite(suites) run = TextTestRunner(verbosity=2).run(testSuite) if close: exit(len(run.failures) > 0 or len(run.errors) > 0) return run
Fix crash in FAB background tint am: 9d42ab847a * commit '9d42ab847a9187fe54c53553a0593fad0aea9263': Fix crash in FAB background tint
/* * Copyright (C) 2015 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 android.support.design.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageButton; class VisibilityAwareImageButton extends ImageButton { private int mUserSetVisibility; public VisibilityAwareImageButton(Context context) { this(context, null); } public VisibilityAwareImageButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mUserSetVisibility = getVisibility(); } @Override public void setVisibility(int visibility) { internalSetVisibility(visibility, true); } final void internalSetVisibility(int visibility, boolean fromUser) { super.setVisibility(visibility); if (fromUser) { mUserSetVisibility = visibility; } } final int getUserSetVisibility() { return mUserSetVisibility; } }
/* * 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 android.support.design.widget; import android.content.Context; import android.support.v7.widget.AppCompatImageButton; import android.util.AttributeSet; class VisibilityAwareImageButton extends AppCompatImageButton { private int mUserSetVisibility; public VisibilityAwareImageButton(Context context) { this(context, null); } public VisibilityAwareImageButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mUserSetVisibility = getVisibility(); } @Override public void setVisibility(int visibility) { internalSetVisibility(visibility, true); } final void internalSetVisibility(int visibility, boolean fromUser) { super.setVisibility(visibility); if (fromUser) { mUserSetVisibility = visibility; } } final int getUserSetVisibility() { return mUserSetVisibility; } }
Add missing INTEGRATION_INSTALLATION_REPOSITORIES github event
package org.kohsuke.github; import java.util.Locale; /** * Hook event type. * * @author Kohsuke Kawaguchi * @see GHEventInfo * @see <a href="https://developer.github.com/v3/activity/events/types/">Event type reference</a> */ public enum GHEvent { COMMIT_COMMENT, CREATE, DELETE, DEPLOYMENT, DEPLOYMENT_STATUS, DOWNLOAD, FOLLOW, FORK, FORK_APPLY, GIST, GOLLUM, INSTALLATION, INSTALLATION_REPOSITORIES, INTEGRATION_INSTALLATION_REPOSITORIES, ISSUE_COMMENT, ISSUES, LABEL, MARKETPLACE_PURCHASE, MEMBER, MEMBERSHIP, MILESTONE, ORGANIZATION, ORG_BLOCK, PAGE_BUILD, PROJECT_CARD, PROJECT_COLUMN, PROJECT, PUBLIC, PULL_REQUEST, PULL_REQUEST_REVIEW, PULL_REQUEST_REVIEW_COMMENT, PUSH, RELEASE, REPOSITORY, // only valid for org hooks STATUS, TEAM, TEAM_ADD, WATCH, PING, /** * Special event type that means "every possible event" */ ALL; /** * Returns GitHub's internal representation of this event. */ String symbol() { if (this==ALL) return "*"; return name().toLowerCase(Locale.ENGLISH); } }
package org.kohsuke.github; import java.util.Locale; /** * Hook event type. * * @author Kohsuke Kawaguchi * @see GHEventInfo * @see <a href="https://developer.github.com/v3/activity/events/types/">Event type reference</a> */ public enum GHEvent { COMMIT_COMMENT, CREATE, DELETE, DEPLOYMENT, DEPLOYMENT_STATUS, DOWNLOAD, FOLLOW, FORK, FORK_APPLY, GIST, GOLLUM, INSTALLATION, INSTALLATION_REPOSITORIES, ISSUE_COMMENT, ISSUES, LABEL, MARKETPLACE_PURCHASE, MEMBER, MEMBERSHIP, MILESTONE, ORGANIZATION, ORG_BLOCK, PAGE_BUILD, PROJECT_CARD, PROJECT_COLUMN, PROJECT, PUBLIC, PULL_REQUEST, PULL_REQUEST_REVIEW, PULL_REQUEST_REVIEW_COMMENT, PUSH, RELEASE, REPOSITORY, // only valid for org hooks STATUS, TEAM, TEAM_ADD, WATCH, PING, /** * Special event type that means "every possible event" */ ALL; /** * Returns GitHub's internal representation of this event. */ String symbol() { if (this==ALL) return "*"; return name().toLowerCase(Locale.ENGLISH); } }
Hide log chart when empty
/* global google Gabra $ */ // $(document).ready(function () { google.load('visualization', '1.0', {'packages': ['corechart']}) google.setOnLoadCallback(function () { $.ajax({ method: 'GET', url: Gabra.api_url + 'logs/chart', success: function (data) { var table = new google.visualization.DataTable() table.addColumn('date', 'Date') // Just totals var empty = true table.addColumn('number', Gabra.i18n.updates) for (var day in data) { if (data[day]['total'] > 0) empty = false table.addRow([new Date(day), data[day]['total']]) } if (empty) return var options = { legend: { position: 'none' }, hAxis: { textPosition: 'none', gridlines: { count: 0 } }, vAxis: { textPosition: 'none', gridlines: { count: 4, color: '#eeeeee' } }, height: 100, chartArea: { width: '100%', height: '90%' } } var chart = new google.visualization.AreaChart(document.getElementById('log-chart')) chart.draw(table, options) }, complete: function () { } }) }) // })
/* global google Gabra $ */ // $(document).ready(function () { google.load('visualization', '1.0', {'packages': ['corechart']}) google.setOnLoadCallback(function () { $.ajax({ method: 'GET', url: Gabra.api_url + 'logs/chart', success: function (data) { var table = new google.visualization.DataTable() table.addColumn('date', 'Date') // Just totals table.addColumn('number', Gabra.i18n.updates) for (var day in data) { table.addRow([new Date(day), data[day]['total']]) } var options = { legend: { position: 'none' }, hAxis: { textPosition: 'none', gridlines: { count: 0 } }, vAxis: { textPosition: 'none', gridlines: { count: 4, color: '#eeeeee' } }, height: 100, chartArea: { width: '100%', height: '90%' } } var chart = new google.visualization.AreaChart(document.getElementById('log-chart')) chart.draw(table, options) }, complete: function () { } }) }) // })
Add modal class to body when a modal view is shown
define(["backbone", "jquery", "utils"], function(B, $, $u) { return B.View.extend({ initialize: function(options) { if (options.url) this.template = $u.templateWithUrl(options.url); else if (options.template) this.template = function(_, cb) { cb(options.template()); }; if (!this.template) throw new Error("You must initialize a modal view with a URL or template."); this.showingClass = options.showingClass || "showing"; this.container = options.container || "#modal"; this.shouldShow = false; }, el: "#modal-contents", getContainer: function() { return this.$el.closest(this.container); }, getContext: function() { return {model: this.model, collection: this.collection}; }, _update: function() { this.getContainer() .toggleClass(this.showingClass, this.shouldShow) .toggle(this.shouldShow); $(document.body).toggleClass("modal", this.shouldShow); if (this.shouldShow && this.wasRendered) this.wasRendered(); }, render: function() { if (this.shouldShow) { var self = this; this.template( this.getContext(), function(html) { self.$el.html(html); self._update(); }); } return this; }, show: function() { this.shouldShow = true; this.render(); }, hide: function() { this.shouldShow = false; this._update(); } }); });
define(["backbone", "utils"], function(B, $u) { return B.View.extend({ initialize: function(options) { if (options.url) this.template = $u.templateWithUrl(options.url); else if (options.template) this.template = function(_, cb) { cb(options.template()); }; if (!this.template) throw new Error("You must initialize a modal view with a URL or template."); this.showingClass = options.showingClass || "showing"; this.container = options.container || "#modal"; this.shouldShow = false; }, el: "#modal-contents", getContainer: function() { return this.$el.closest(this.container); }, getContext: function() { return {model: this.model, collection: this.collection}; }, _update: function() { this.getContainer() .toggleClass(this.showingClass, this.shouldShow) .toggle(this.shouldShow); if (this.shouldShow && this.wasRendered) this.wasRendered(); }, render: function() { if (this.shouldShow) { var self = this; this.template( this.getContext(), function(html) { self.$el.html(html); self._update(); }); } return this; }, show: function() { this.shouldShow = true; this.render(); }, hide: function() { this.shouldShow = false; this._update(); } }); });
Add url to the description field. Signed-off-by: François de Metz <[email protected]>
var icalendar = require('icalendar'); var _ = require('underscore'); exports.generateIcal = function(currentUser, boards, params) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; if (params && params.only_me == 'true' && !_(card.get('idMembers')).include(currentUser.id)) { return; } var description = card.get('desc'); description += "\n\n"+ card.get('url'); var event = new icalendar.VEvent(card.id); event.setSummary(card.get('name')); event.setDescription(description); event.setDate(card.get('badges').due, 60*60); event.addProperty('ATTACH', card.get('url')); event.addProperty('URL', card.get('url')); if (params && params.alarm != '-1') { comp = event.addComponent('VALARM'); comp.addProperty('ACTION', 'DISPLAY'); comp.addProperty('DESCRIPTION', 'Generated by trello calendar'); comp.addProperty('TRIGGER', params.alarm); } ical.addComponent(event); }); }); return ical; }
var icalendar = require('icalendar'); var _ = require('underscore'); exports.generateIcal = function(currentUser, boards, params) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; if (params && params.only_me == 'true' && !_(card.get('idMembers')).include(currentUser.id)) { return; } var event = new icalendar.VEvent(card.id); event.setSummary(card.get('name')); event.setDescription(card.get('desc')); event.setDate(card.get('badges').due, 60*60); event.addProperty('ATTACH', card.get('url')); event.addProperty('URL', card.get('url')); if (params && params.alarm != '-1') { comp = event.addComponent('VALARM'); comp.addProperty('ACTION', 'DISPLAY'); comp.addProperty('DESCRIPTION', 'Generated by trello calendar'); comp.addProperty('TRIGGER', params.alarm); } ical.addComponent(event); }); }); return ical; }
Format reporter output with Chalk
'use strict'; const chalk = require('chalk'); /* eslint max-statements: 'off' */ class Reporter { /** * Writes to console * * @static * @param {Array} statsObjArray An array of stats objects * @param {String} statsType The type of stat being processed * @return {Undefined} No return * @memberof Reporter */ static write(statsObjArray, statsType) { if (statsType === 'overall') { console.log(chalk.bgWhite.black('Overall stats')); console.log(statsObjArray.overall.getMessage()); } else if (statsType === 'project') { console.log(chalk.bgWhite.black('Project level stats')); for (const projectKey in statsObjArray) { const currentProjectPrStats = statsObjArray[projectKey]; console.log(`${chalk.white.bold('Project:')} ${chalk.white(projectKey)}`); console.log(currentProjectPrStats.getMessage()); } } else { console.log(chalk.bgWhite.black('Repo level stats')); for (const projectKey in statsObjArray) { const currentProjectPrStats = statsObjArray[projectKey]; const keyParts = projectKey.split('|'); const projectName = keyParts[0]; const repoName = keyParts[1]; console.log(`${chalk.white.bold('Project:')} ${chalk.white(projectName)}`); console.log(`${chalk.white.bold('Repo:')} ${chalk.white(repoName)}`); console.log(currentProjectPrStats.getMessage()); } } } } module.exports = Reporter;
'use strict'; const chalk = require('chalk'); /* eslint max-statements: 'off' */ class Reporter { /** * Writes to console * * @static * @param {Array} statsObjArray An array of stats objects * @param {String} statsType The type of stat being processed * @return {Undefined} No return * @memberof Reporter */ static write(statsObjArray, statsType) { if (statsType === 'overall') { console.log(chalk.red.bold('Overall stats')); console.log(statsObjArray.overall.getMessage()); } else if (statsType === 'project') { console.log(chalk.red.bold('Project level stats')); for (const projectKey in statsObjArray) { const currentProjectPrStats = statsObjArray[projectKey]; console.log(`${chalk.magenta.bold('Project:')} ${chalk.magenta(projectKey)}`); console.log(currentProjectPrStats.getMessage()); } } else { console.log(chalk.red.bold('Repo level stats')); for (const projectKey in statsObjArray) { const currentProjectPrStats = statsObjArray[projectKey]; const keyParts = projectKey.split('|'); const projectName = keyParts[0]; const repoName = keyParts[1]; console.log(`${chalk.magenta.bold('Project:')} ${chalk.magenta(projectName)}`); console.log(`${chalk.magenta.bold('Repo:')} ${chalk.magenta(repoName)}`); console.log(currentProjectPrStats.getMessage()); } } } } module.exports = Reporter;
Clean up using servers listening and error events
'use strict'; const { EventEmitter } = require('events'); const logger = require('./logger')('server-impl.js'); const migrator = require('../migrator'); const getApp = require('./app'); const { startMonitoring } = require('./metrics'); const { createStores } = require('./db'); const { createOptions } = require('./options'); const User = require('./user'); const AuthenticationRequired = require('./authentication-required'); function createApp(options) { // Database dependecies (statefull) const stores = createStores(options); const eventBus = new EventEmitter(); const config = Object.assign( { stores, eventBus, }, options ); const app = getApp(config); startMonitoring(options.serverMetrics, eventBus); const server = app.listen({ port: options.port, host: options.host }, () => logger.info(`Unleash started on port ${server.address().port}`) ); return new Promise((resolve, reject) => { server.on('listening', () => resolve({ app, server, eventBus })); server.on('error', reject); }); } function start(opts) { const options = createOptions(opts); return migrator({ databaseUrl: options.databaseUrl }) .catch(err => logger.error('failed to migrate db', err)) .then(() => createApp(options)); } module.exports = { start, User, AuthenticationRequired, };
'use strict'; const { EventEmitter } = require('events'); const logger = require('./logger')('server-impl.js'); const migrator = require('../migrator'); const getApp = require('./app'); const { startMonitoring } = require('./metrics'); const { createStores } = require('./db'); const { createOptions } = require('./options'); const User = require('./user'); const AuthenticationRequired = require('./authentication-required'); function createApp(options) { // Database dependecies (statefull) const stores = createStores(options); const eventBus = new EventEmitter(); const config = Object.assign( { stores, eventBus, }, options ); const app = getApp(config); startMonitoring(options.serverMetrics, eventBus); return new Promise(resolve => { const server = app.listen( { port: options.port, host: options.host }, () => { logger.info(`Unleash started on port ${server.address().port}`); resolve({ app, server, eventBus }); } ); }); } function start(opts) { const options = createOptions(opts); return migrator({ databaseUrl: options.databaseUrl }) .catch(err => logger.error('failed to migrate db', err)) .then(() => createApp(options)) .catch(err => logger.error('failed creating app', err)); } module.exports = { start, User, AuthenticationRequired, };
Set message attribute on InvalidValidationResponse error class.
__all___ = [ 'YubicoError', 'StatusCodeError', 'InvalidClientIdError', 'InvalidValidationResponse', 'SignatureVerificationError' ] class YubicoError(Exception): """ Base class for Yubico related exceptions. """ pass class StatusCodeError(YubicoError): def __init__(self, status_code): self.status_code = status_code def __str__(self): return ('Yubico server returned the following status code: %s' % (self.status_code)) class InvalidClientIdError(YubicoError): def __init__(self, client_id): self.client_id = client_id def __str__(self): return 'The client with ID %s does not exist' % (self.client_id) class InvalidValidationResponse(YubicoError): def __init__(self, reason, response, parameters=None): self.reason = reason self.response = response self.parameters = parameters self.message = self.reason def __str__(self): return self.reason class SignatureVerificationError(YubicoError): def __init__(self, generated_signature, response_signature): self.generated_signature = generated_signature self.response_signature = response_signature def __str__(self): return repr('Server response message signature verification failed' + '(expected %s, got %s)' % (self.generated_signature, self.response_signature))
__all___ = [ 'YubicoError', 'StatusCodeError', 'InvalidClientIdError', 'InvalidValidationResponse', 'SignatureVerificationError' ] class YubicoError(Exception): """ Base class for Yubico related exceptions. """ pass class StatusCodeError(YubicoError): def __init__(self, status_code): self.status_code = status_code def __str__(self): return ('Yubico server returned the following status code: %s' % (self.status_code)) class InvalidClientIdError(YubicoError): def __init__(self, client_id): self.client_id = client_id def __str__(self): return 'The client with ID %s does not exist' % (self.client_id) class InvalidValidationResponse(YubicoError): def __init__(self, reason, response, parameters=None): self.reason = reason self.response = response self.parameters = parameters def __str__(self): return self.reason class SignatureVerificationError(YubicoError): def __init__(self, generated_signature, response_signature): self.generated_signature = generated_signature self.response_signature = response_signature def __str__(self): return repr('Server response message signature verification failed' + '(expected %s, got %s)' % (self.generated_signature, self.response_signature))
Add done flag to experiment.
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.done = false; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
Fix replace bug in equality formula.
package model.formulas; public class Equality extends Formula { public final Term lhs; public final Term rhs; public Equality(Term lhs, Term rhs){ this.lhs = lhs; this.rhs = rhs; super.precedence = 3; } @Override public Formula replace(String newId,String oldId){ return new Equality(lhs.replace(newId, oldId), rhs.replace(newId, oldId)); } @Override public Formula replace(Term newTerm,Term oldTerm){ Term lhsRet = this.lhs.equals(oldTerm) ? newTerm : this.lhs; Term rhsRet = this.rhs.equals(oldTerm) ? newTerm : this.rhs; return new Equality(lhsRet, rhsRet); } @Override public boolean equals(Object o){ if(o instanceof Equality){ Equality e = (Equality)o; return this.lhs.equals(e.lhs) && this.rhs.equals(e.rhs); } return false; } @Override public String toString(){ return lhs+" = "+rhs; } @Override public String parenthesize() { return toString(); } @Override public boolean containsFreeObjectId(String id) { return lhs.containsObjectId(id) || rhs.containsObjectId(id); } }
package model.formulas; public class Equality extends Formula { public final Term lhs; public final Term rhs; public Equality(Term lhs, Term rhs){ this.lhs = lhs; this.rhs = rhs; super.precedence = 3; } @Override public Formula replace(String newId,String oldId){ return new Equality(lhs.replace(newId, oldId), rhs.replace(newId, oldId)); } @Override public Formula replace(Term newTerm,Term oldTerm){ Term lhsRet = this.lhs.equals(oldTerm) ? newTerm : oldTerm; Term rhsRet = this.rhs.equals(oldTerm) ? newTerm : oldTerm; return new Equality(lhsRet, rhsRet); } @Override public boolean equals(Object o){ if(o instanceof Equality){ Equality e = (Equality)o; return this.lhs.equals(e.lhs) && this.rhs.equals(e.rhs); } return false; } @Override public String toString(){ return lhs+" = "+rhs; } @Override public String parenthesize() { return toString(); } @Override public boolean containsFreeObjectId(String id) { return lhs.containsObjectId(id) || rhs.containsObjectId(id); } }
Sort the exocomp system list by name.
import React, { Component } from "react"; import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from "reactstrap"; class DestinationSelect extends Component { state = { dropdownOpen: false }; toggle = () => { this.setState({ dropdownOpen: !this.state.dropdownOpen }); }; render() { const { systems, destination, select } = this.props; const selectedSystem = systems.find(s => s.id === destination); return ( <ButtonDropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}> <DropdownToggle caret> {selectedSystem ? selectedSystem.displayName : "Select a System"} </DropdownToggle> <DropdownMenu> {systems .concat() .sort((a, b) => { if (a.displayName > b.displayName) return 1; if (a.displayName < b.displayName) return -1; return 0; }) .map(s => ( <DropdownItem key={s.id} onClick={() => select(s.id)}> {s.displayName} </DropdownItem> ))} </DropdownMenu> </ButtonDropdown> ); } } export default DestinationSelect;
import React, { Component } from "react"; import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from "reactstrap"; class DestinationSelect extends Component { state = { dropdownOpen: false }; toggle = () => { this.setState({ dropdownOpen: !this.state.dropdownOpen }); }; render() { const { systems, destination, select } = this.props; const selectedSystem = systems.find(s => s.id === destination); return ( <ButtonDropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}> <DropdownToggle caret> {selectedSystem ? selectedSystem.displayName : "Select a System"} </DropdownToggle> <DropdownMenu> {systems .concat() .sort((a, b) => { if (a.type > b.type) return 1; if (a.type < b.type) return -1; return 0; }) .map(s => ( <DropdownItem key={s.id} onClick={() => select(s.id)}> {s.displayName} </DropdownItem> ))} </DropdownMenu> </ButtonDropdown> ); } } export default DestinationSelect;
Fix region and removing version in file
<?php /** * @copyright Federico Nicolás Motta * @author Federico Nicolás Motta <[email protected]> * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) * @package yii2-aws-sdk */ namespace fedemotta\awssdk; use yii\base\Component; use Aws\Common\Aws; /** * Yii2 component wrapping of the AWS SDK for easy configuration * @author Federico Nicolás Motta <[email protected]> */ class AwsSdk extends Component { /* * @var string specifies the AWS key */ public $key = null; /* * @var string specifies the AWS secret */ public $secret = null; /* * @var string specifies the AWS region */ public $region = null; /** * @var AWS SDK instance */ protected $_awssdk; /** * Initializes (if needed) and fetches the AWS SDK instance * @return Aws instance */ public function getAwsSdk() { if (empty($this->_awssdk) || !$this->_awssdk instanceof Aws\Common\Aws) { $this->setAwsSdk(); } return $this->_awssdk; } /** * Sets the AWS SDK instance */ public function setAwsSdk() { $this->_awssdk = Aws::factory([ 'key'=>$this->key, 'secret'=>$this->secret, 'region'=>$this->region]); } }
<?php /** * @copyright Federico Nicolás Motta * @author Federico Nicolás Motta <[email protected]> * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) * @package yii2-aws-sdk * @version 0.1 */ namespace fedemotta\awssdk; use yii\base\Component; use Aws\Common\Aws; /** * Yii2 component wrapping of the AWS SDK for easy configuration * * @author Federico Nicolás Motta <[email protected]> * @since 0.1 */ class AwsSdk extends Component { /* * @var string specifies the AWS key */ public $key = null; /* * @var string specifies the AWS secret */ public $secret = null; /* * @var string specifies the AWS region */ public $region = null; /** * @var AWS SDK instance */ protected $_awssdk; /** * Initializes (if needed) and fetches the AWS SDK instance * @return Aws instance */ public function getAwsSdk() { if (empty($this->_awssdk) || !$this->_awssdk instanceof Aws\Common\Aws) { $this->setAwsSdk(); } return $this->_awssdk; } /** * Sets the AWS SDK instance */ public function setAwsSdk() { $this->_awssdk = Aws::factory([$this->key,$this->secret,$this->region]); } }
Move checkNumber function to the buttom of class implementation.
/** * Copyright (c) 2016, Christopher Ramírez * All rights reserved. * * This source code is licensed under the MIT license. */ 'use strict' const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/ class NicaraguanId { constructor(number) { this.fullName = undefined this.birthPlace = undefined this.birthDate = undefined this.validSince = undefined this.validThrough = undefined this.setNewNumber(number) } setNewNumber(number) { this.checkNumber(number) let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number) this.number = number this.cityId = cityId this.birthDigits = birthDigits this.consecutive = consecutive this.birthDate = dateFromSixIntDigits(this.birthDigits) } checkNumber(number) { if (!validIdNumberRegExp.test(number)) { throw `${number} is an invalid nicaraguan ID number.` } } } function dateFromSixIntDigits(sixIntDigits) { const dateFormat = /^(\d{2})(\d{2})(\d{2})$/ let [_, day, month, year] = dateFormat.exec(this.birthDigits) return new Date(parseInt(year), parseInt(month) -1, parseInt(day)) } module.exports.NicaraguanId = NicaraguanId
/** * Copyright (c) 2016, Christopher Ramírez * All rights reserved. * * This source code is licensed under the MIT license. */ 'use strict' const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/ class NicaraguanId { constructor(number) { this.fullName = undefined this.birthPlace = undefined this.birthDate = undefined this.validSince = undefined this.validThrough = undefined this.setNewNumber(number) } checkNumber(number) { if (!validIdNumberRegExp.test(number)) { throw `${number} is an invalid nicaraguan ID number.` } } setNewNumber(number) { this.checkNumber(number) let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number) this.number = number this.cityId = cityId this.birthDigits = birthDigits this.consecutive = consecutive this.birthDate = dateFromSixIntDigits(this.birthDigits) } } function dateFromSixIntDigits(sixIntDigits) { const dateFormat = /^(\d{2})(\d{2})(\d{2})$/ let [_, day, month, year] = dateFormat.exec(this.birthDigits) return new Date(parseInt(year), parseInt(month) -1, parseInt(day)) } module.exports.NicaraguanId = NicaraguanId
Improve login page when wrong password is entered
// // Copyright 2014 Ilkka Oksanen <[email protected]> // // 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. // 'use strict'; $(function() { $('input[name="username"]').focus(); $('#login-form').submit(function() { $('.login-error').empty(); $('input').keypress(function() { $('.login-error').empty(); }); $.post('/login', $('#login-form').serialize(), function(data) { if (data.success === true) { $.cookie('ProjectEvergreen', data.userId + '-' + data.secret + '-n', { path: '/', expires: new Date(data.expires) }); window.location.pathname = '/app/'; } else { $('.login-error').text(data.msg); $('input[name="username"]').val('').focus(); $('input[name="password"]').val(''); } }); return false; }); });
// // Copyright 2014 Ilkka Oksanen <[email protected]> // // 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. // 'use strict'; $(function() { $('input[name="username"]').focus(); $('#login-form').submit(function() { $('.login-error').empty(); $.post('/login', $('#login-form').serialize(), function(data) { if (data.success === true) { $.cookie('ProjectEvergreen', data.userId + '-' + data.secret + '-n', { path: '/', expires: new Date(data.expires) }); window.location.pathname = '/app/'; } else { $('.login-error').text(data.msg); } }); return false; }); });
Use github's `clone_url` instead of mandating ssh.
from collections import namedtuple Remote = namedtuple('Remote', ('name', 'url')) CommitInfo = namedtuple("CommitInfo", ('commit', 'origin', 'remote_repo', 'ref')) class PRInfo(object): def __init__(self, json): self.json = json @property def base_sha(self): return self.json['base']['sha'] @property def head_sha(self): return self.json['head']['sha'] @property def base_ref(self): return self.json['base']['ref'] @property def head_ref(self): return self.json['head']['ref'] @property def has_remote_repo(self): return self.json['base']['repo']['owner']['login'] != \ self.json['head']['repo']['owner']['login'] @property def remote_repo(self): remote = None if self.has_remote_repo: remote = Remote(name=self.json['head']['repo']['owner']['login'], url=self.json['head']['repo']['clone_url']) return remote def to_commit_info(self): return CommitInfo(self.base_sha, self.head_sha, self.remote_repo, self.head_ref) def get_pr_info(requester, reponame, number): "Returns the PullRequest as a PRInfo object" resp = requester.get( 'https://api.github.com/repos/%s/pulls/%s' % (reponame, number)) return PRInfo(resp.json())
from collections import namedtuple Remote = namedtuple('Remote', ('name', 'url')) CommitInfo = namedtuple("CommitInfo", ('commit', 'origin', 'remote_repo', 'ref')) class PRInfo(object): def __init__(self, json): self.json = json @property def base_sha(self): return self.json['base']['sha'] @property def head_sha(self): return self.json['head']['sha'] @property def base_ref(self): return self.json['base']['ref'] @property def head_ref(self): return self.json['head']['ref'] @property def has_remote_repo(self): return self.json['base']['repo']['owner']['login'] != \ self.json['head']['repo']['owner']['login'] @property def remote_repo(self): remote = None if self.has_remote_repo: remote = Remote(name=self.json['head']['repo']['owner']['login'], url=self.json['head']['repo']['ssh_url']) return remote def to_commit_info(self): return CommitInfo(self.base_sha, self.head_sha, self.remote_repo, self.head_ref) def get_pr_info(requester, reponame, number): "Returns the PullRequest as a PRInfo object" resp = requester.get( 'https://api.github.com/repos/%s/pulls/%s' % (reponame, number)) return PRInfo(resp.json())
Add group/job info to job dashboard Signed-off-by: Salim Alam <[email protected]>
import time from datetime import datetime def my_log_parser(logger, line): if line.count(',') >= 6: date, report_type, group_id, job_id, event, package, rest = line.split(',',6) if report_type == 'J' and event != 'Pending': date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") date = time.mktime(date.timetuple()) url = '${bldr_url}/#/pkgs/{0}/builds/{1}'.format(package, job_id) if event == 'Failed': error = rest.split(',')[-1] message = package + ' ' + error + ' ' + url elif event == 'Complete': message = package + ' ' + url else: message = package + ' grp:' + group_id + ' job:' + job_id logged_event = { 'msg_title': event, 'timestamp': date, 'msg_text': message, 'priority': 'normal', 'event_type': report_type, 'aggregation_key': group_id, 'alert_type': 'info' } return logged_event return None
import time from datetime import datetime def my_log_parser(logger, line): if line.count(',') >= 6: date, report_type, group_id, job_id, event, package, rest = line.split(',',6) if report_type == 'J' and event != 'Pending': date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") date = time.mktime(date.timetuple()) url = '${bldr_url}/#/pkgs/{0}/builds/{1}'.format(package, job_id) if event == 'Failed': error = rest.split(',')[-1] message = package + ' ' + error + ' ' + url elif event == 'Complete': message = package + ' ' + url else: message = package logged_event = { 'msg_title': event, 'timestamp': date, 'msg_text': message, 'priority': 'normal', 'event_type': report_type, 'aggregation_key': group_id, 'alert_type': 'info' } return logged_event return None
Change comment color to increase contrast
module.exports = { plain: { color: '#f8f8f2', backgroundColor: '#272822' }, styles: [ { types: ['comment', 'prolog', 'doctype', 'cdata'], style: { color: '#c6cad2' } }, { types: ['punctuation'], style: { color: '#F8F8F2' } }, { types: ['property', 'tag', 'constant', 'symbol', 'deleted'], style: { color: '#F92672' } }, { types: ['boolean', 'number'], style: { color: '#AE81FF' } }, { types: ['selector', 'attr-name', 'string', 'char', 'builtin', 'inserted'], style: { color: '#a6e22e' } }, { types: ['operator', 'entity', 'url', 'variable'], style: { color: '#F8F8F2' } }, { types: ['atrule', 'attr-value', 'function'], style: { color: '#E6D874' } }, { types: ['keyword'], style: { color: '#F92672' } }, { types: ['regex', 'important'], style: { color: '#FD971F' } } ] }
module.exports = { plain: { color: '#f8f8f2', backgroundColor: '#272822' }, styles: [ { types: ['comment', 'prolog', 'doctype', 'cdata'], style: { color: '#778090' } }, { types: ['punctuation'], style: { color: '#F8F8F2' } }, { types: ['property', 'tag', 'constant', 'symbol', 'deleted'], style: { color: '#F92672' } }, { types: ['boolean', 'number'], style: { color: '#AE81FF' } }, { types: ['selector', 'attr-name', 'string', 'char', 'builtin', 'inserted'], style: { color: '#a6e22e' } }, { types: ['operator', 'entity', 'url', 'variable'], style: { color: '#F8F8F2' } }, { types: ['atrule', 'attr-value', 'function'], style: { color: '#E6D874' } }, { types: ['keyword'], style: { color: '#F92672' } }, { types: ['regex', 'important'], style: { color: '#FD971F' } } ] }
Fix assertion into info e2e-test
'use strict'; describe('my angular musicbrainz app', function () { beforeEach(function () { browser().navigateTo('app/index.html'); }); describe('search', function () { beforeEach(function () { browser().navigateTo('#/search'); }); it('should render search when user navigates to /search', function () { expect(element('#search-input-label').text()). toContain('music'); }); it('U2 album search', function () { input('searchText').enter('U2'); element(':button').click(); expect(element('#result-number').text()). toContain('22'); }); }); describe('info', function () { beforeEach(function () { browser().navigateTo('#/info'); }); it('should render info when user navigates to /info', function () { expect(element('[ng-view] li:first').text()). toMatch(/Application version/); }); }); it('should automatically redirect to /search when location hash/fragment is empty', function () { expect(browser().location().url()).toBe('/search'); }); });
'use strict'; describe('my angular musicbrainz app', function () { beforeEach(function () { browser().navigateTo('app/index.html'); }); it('should automatically redirect to /search when location hash/fragment is empty', function () { expect(browser().location().url()).toBe('/search'); }); describe('search', function () { beforeEach(function () { browser().navigateTo('#/search'); }); it('should render search when user navigates to /search', function () { expect(element('#search-input-label').text()). toContain('music'); }); it('U2 album search', function () { input('searchText').enter('U2'); element(':button').click(); expect(element('#result-number').text()). toContain('22'); }); }); describe('info', function () { beforeEach(function () { browser().navigateTo('#/info'); }); it('should render info when user navigates to /info', function () { expect(element('[ng-view] p:first').text()). toMatch(/Information/); }); }); });
Update forms to bootstrap 3 form-horizontal needs additional helper classes in BS3
from django import forms from django.template.defaultfilters import slugify from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Submit from crispy_forms.bootstrap import FormActions from competition.models.team_model import Team class TeamForm(forms.ModelForm): class Meta: model = Team fields = ('name', ) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Fieldset( 'Create a new team', 'name', ), FormActions( Submit('submit', 'Submit') ) ) super(TeamForm, self).__init__(*args, **kwargs) def clean_name(self): c = self.instance.competition n = self.cleaned_data['name'] s = slugify(n) if Team.objects.filter(competition=c, slug=s).exists(): msg = "This name is already taken for %s" % c.name raise forms.ValidationError(msg) return n def validate_unique(self): exclude = self._get_validation_exclusions() exclude.remove('competition') try: self.instance.validate_unique(exclude=exclude) except ValidationError, e: self._update_errors(e.message_dict)
from django import forms from django.template.defaultfilters import slugify from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Submit from crispy_forms.bootstrap import FormActions from competition.models.team_model import Team class TeamForm(forms.ModelForm): class Meta: model = Team fields = ('name', ) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Fieldset( 'Create a new team', 'name', ), FormActions( Submit('submit', 'Submit') ) ) super(TeamForm, self).__init__(*args, **kwargs) def clean_name(self): c = self.instance.competition n = self.cleaned_data['name'] s = slugify(n) if Team.objects.filter(competition=c, slug=s).exists(): msg = "This name is already taken for %s" % c.name raise forms.ValidationError(msg) return n def validate_unique(self): exclude = self._get_validation_exclusions() exclude.remove('competition') try: self.instance.validate_unique(exclude=exclude) except ValidationError, e: self._update_errors(e.message_dict)
Make our PollingDataStreamers start up right away
import logging from datetime import timedelta from twisted.internet.task import LoopingCall from moksha.hub.hub import MokshaHub log = logging.getLogger('moksha.hub') class DataStream(object): """ The parent DataStream class. """ def __init__(self): self.hub = MokshaHub() def send_message(self, topic, message): try: self.hub.send_message(topic, message) except Exception, e: log.error('Cannot send message: %s' % e) def stop(self): self.hub.close() class PollingDataStream(DataStream): """ A self-polling data stream. This class represents a data stream that wakes up at a given frequency, and calls the :meth:`poll` method. """ frequency = None # Either a timedelta object, or the number of seconds def __init__(self, now=True): super(PollingDataStream, self).__init__() self.timer = LoopingCall(self.poll) if isinstance(self.frequency, timedelta): seconds = self.frequency.seconds + \ (self.frequency.days * 24 * 60 * 60) + \ (self.frequency.microseconds / 1000000.0) else: seconds = self.frequency log.debug("Setting a %s second timers" % seconds) self.timer.start(seconds, now=now) def poll(self): raise NotImplementedError def stop(self): super(PollingDataStream, self).stop() self.timer.stop()
import logging from datetime import timedelta from twisted.internet.task import LoopingCall from moksha.hub.hub import MokshaHub log = logging.getLogger('moksha.hub') class DataStream(object): """ The parent DataStream class. """ def __init__(self): self.hub = MokshaHub() def send_message(self, topic, message): try: self.hub.send_message(topic, message) except Exception, e: log.error('Cannot send message: %s' % e) def stop(self): self.hub.close() class PollingDataStream(DataStream): """ A self-polling data stream. This class represents a data stream that wakes up at a given frequency, and calls the :meth:`poll` method. """ frequency = None # Either a timedelta object, or the number of seconds def __init__(self): super(PollingDataStream, self).__init__() self.timer = LoopingCall(self.poll) if isinstance(self.frequency, timedelta): seconds = self.frequency.seconds + \ (self.frequency.days * 24 * 60 * 60) + \ (self.frequency.microseconds / 1000000.0) else: seconds = self.frequency log.debug("Setting a %s second timers" % seconds) self.timer.start(seconds, now=False) def poll(self): raise NotImplementedError def stop(self): super(PollingDataStream, self).stop() self.timer.stop()
Add missing like count from my projects list query fbshipit-source-id: fede441
import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; import ProjectList from '../components/ProjectList'; const MyAppsQuery = gql` query MyApps($limit: Int!, $offset: Int!){ viewer { me { id appCount apps(limit: $limit, offset: $offset) { id fullName iconUrl packageName description lastPublishedTime likeCount } } } } ` export default graphql(MyAppsQuery, { props: (props) => { let { data } = props; let apps, appCount; if (data.viewer && data.viewer.me) { apps = data.viewer.me.apps; appCount = data.viewer.me.appCount; } return { ...props, data: { ...data, appCount, apps, }, loadMoreAsync() { return data.fetchMore({ variables: { offset: apps.length, }, updateQuery: (previousData, { fetchMoreResult }) => { if (!fetchMoreResult.data) { return previousResult; } return Object.assign({}, previousData, { viewer: { me: { ...fetchMoreResult.data.viewer.me, apps: [ ...previousData.viewer.me.apps, ...fetchMoreResult.data.viewer.me.apps ], } }, }); }, }); } }; }, options: { variables: { limit: 15, offset: 0, }, }, })(ProjectList);
import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; import ProjectList from '../components/ProjectList'; const MyAppsQuery = gql` query MyApps($limit: Int!, $offset: Int!){ viewer { me { id appCount apps(limit: $limit, offset: $offset) { id fullName iconUrl packageName description lastPublishedTime } } } } ` export default graphql(MyAppsQuery, { props: (props) => { let { data } = props; let apps, appCount; if (data.viewer && data.viewer.me) { apps = data.viewer.me.apps; appCount = data.viewer.me.appCount; } return { ...props, data: { ...data, appCount, apps, }, loadMoreAsync() { return data.fetchMore({ variables: { offset: apps.length, }, updateQuery: (previousData, { fetchMoreResult }) => { if (!fetchMoreResult.data) { return previousResult; } return Object.assign({}, previousData, { viewer: { me: { ...fetchMoreResult.data.viewer.me, apps: [ ...previousData.viewer.me.apps, ...fetchMoreResult.data.viewer.me.apps ], } }, }); }, }); } }; }, options: { variables: { limit: 15, offset: 0, }, }, })(ProjectList);
Stop the centerOn animation if the user scrolls
/** * Pixel - jQuery plugins */ (function($){ /** * Center scroll on the selected element * * @param {number} [speed=1025] * @returns {*} */ $.fn.centerOn = function(speed) { // Scroll speed speed = speed || 1025; // Center the users viewport on the selected element debug.info("Centering the users viewport on " + this.prop("tagName")); var viewport = $('html,body'); viewport.animate({ scrollTop: this.offset().top - ( $(window).height() - this.outerHeight(true) ) / 2 }, speed); // Stop the animation if the user scrolls viewport.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){ if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){ viewport.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup'); } }); }; /** * Generate a data URL from file input and apply as the src of the selected attribute * * @param input * @returns {*} */ $.fn.srcDataUrl = function(input) { debug.info('Generating a data URL for the supplied image'); // Set up a FileReader instance var reader = new FileReader(); if (input.files && input.files[0]) { var file = input.files[0]; } else if (input[0]) { var file = input[0]; } // Render the preview var element = this; if (file) { reader.onload = function (e) { element.attr('src', e.target.result); } reader.readAsDataURL(file); } }; }(jQuery));
/** * Pixel - jQuery plugins */ (function($){ /** * Center scroll on the selected element * * @param {number} [speed=1025] * @returns {*} */ $.fn.centerOn = function(speed) { // Scroll speed speed = speed || 1025; // Center the users viewport on the selected element debug.info("Centering the users viewport on " + this.prop("tagName")); return $('html,body').animate({ scrollTop: this.offset().top - ( $(window).height() - this.outerHeight(true) ) / 2 }, speed); }; /** * Generate a data URL from file input and apply as the src of the selected attribute * * @param input * @returns {*} */ $.fn.srcDataUrl = function(input) { debug.info('Generating a data URL for the supplied image'); // Set up a FileReader instance var reader = new FileReader(); if (input.files && input.files[0]) { var file = input.files[0]; } else if (input[0]) { var file = input[0]; } // Render the preview var element = this; if (file) { reader.onload = function (e) { element.attr('src', e.target.result); } reader.readAsDataURL(file); } }; }(jQuery));
Update php version for magento connect
<?php return array( 'extension_name' => 'Allopass_Hipay', 'summary' => 'Official HiPay Fullservice payment extension.', 'description' => 'HiPay Fullservice is the first payment platform oriented towards merchants that responds to all matters related to online payment: transaction processing, risk management, relationship management with banks and acquirers, financial reconciliation or even international expansion.', 'notes' => 'Official HiPay Fullservice payment extension', 'extension_version' => '0.1.0', 'skip_version_compare' => false, 'auto_detect_version' => true, 'stability' => 'stable', 'license' => 'General Public License (GPL)', 'channel' => 'community', 'author_name' => 'HiPay', 'author_user' => 'HiPay', 'author_email' => '[email protected]', 'base_dir' => __DIR__.'/dist', 'archive_files' => 'Allopass_Hipay.tar', 'path_output' => __DIR__.'/dist', 'php_min' => '5.2.0', 'php_max' => '7.3.0', 'extensions' => array() );
<?php return array( 'extension_name' => 'Allopass_Hipay', 'summary' => 'Official HiPay Fullservice payment extension.', 'description' => 'HiPay Fullservice is the first payment platform oriented towards merchants that responds to all matters related to online payment: transaction processing, risk management, relationship management with banks and acquirers, financial reconciliation or even international expansion.', 'notes' => 'Official HiPay Fullservice payment extension', 'extension_version' => '0.1.0', 'skip_version_compare' => false, 'auto_detect_version' => true, 'stability' => 'stable', 'license' => 'General Public License (GPL)', 'channel' => 'community', 'author_name' => 'HiPay', 'author_user' => 'HiPay', 'author_email' => '[email protected]', 'base_dir' => __DIR__.'/dist', 'archive_files' => 'Allopass_Hipay.tar', 'path_output' => __DIR__.'/dist', 'php_min' => '5.2.0', 'php_max' => '7.2.0', 'extensions' => array() );
Change $urlRouterProvider.otherwise back to /home
(function () { 'use strict'; angular .module('app.core') .run(function($rootScope, $state) { return $rootScope.$on('$stateChangeStart', function() { return $rootScope.$state = $state; }); }) .config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('home', { url: '/home', controller: 'Home', controllerAs: 'home', templateUrl: 'app/home/home.html', data: { title: 'Home' } }) .state('color', { url: '/color', controller: 'Color', controllerAs: 'color', templateUrl: 'app/color/color.html', data: { title: 'Color' } }) .state('404', { url: '/404', templateUrl: 'app/core/404.html', data: { title: '404' } }); }); }());
(function () { 'use strict'; angular .module('app.core') .run(function($rootScope, $state) { return $rootScope.$on('$stateChangeStart', function() { return $rootScope.$state = $state; }); }) .config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/404'); $stateProvider .state('home', { url: '/home', controller: 'Home', controllerAs: 'home', templateUrl: 'app/home/home.html', data: { title: 'Home' } }) .state('color', { url: '/color', controller: 'Color', controllerAs: 'color', templateUrl: 'app/color/color.html', data: { title: 'Color' } }) .state('404', { url: '/404', templateUrl: 'app/core/404.html', data: { title: '404' } }); }); }());
Fix bug with manga names being cut.
<?php namespace App; use Illuminate\Database\Eloquent\Model; use \App\Manga; class Library extends Model { // protected $fillable = ['name', 'path']; public function getId() { return $this->id; } public function getName() { return $this->name; } public function getPath() { return $this->path; } public function scan() { // scan and add new directories foreach (\File::directories($this->getPath()) as $path) { $manga = Manga::updateOrCreate([ 'name' => pathinfo($path, PATHINFO_BASENAME), 'path' => $path, 'library_id' => Library::where('name','=',$this->getName())->first()->id ]); } // iterate through all the manga in the library // and remove those that no longer exist in the filesystem $manga = Manga::where('library_id', '=', $this->getId())->get(); foreach ($manga as $manga_) { if (\File::exists($manga_->getPath()) === false) { $manga_->forceDelete(); } } } public function forceDelete() { // get all the manga that have library_id to ours $manga = Manga::where('library_id', '=', $this->getId())->get(); // and delete them foreach ($manga as $manga_) { // Manga::forceDelete deletes all the references to other tables (artists, authors, manga_information, etc..) $manga_->forceDelete(); } parent::forceDelete(); } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use \App\Manga; class Library extends Model { // protected $fillable = ['name', 'path']; public function getId() { return $this->id; } public function getName() { return $this->name; } public function getPath() { return $this->path; } public function scan() { // scan and add new directories foreach (\File::directories($this->getPath()) as $path) { $manga = Manga::updateOrCreate([ 'name' => pathinfo($path, PATHINFO_FILENAME), 'path' => $path, 'library_id' => Library::where('name','=',$this->getName())->first()->id ]); } // iterate through all the manga in the library // and remove those that no longer exist in the filesystem $manga = Manga::where('library_id', '=', $this->getId())->get(); foreach ($manga as $manga_) { if (\File::exists($manga_->getPath()) === false) { $manga_->forceDelete(); } } } public function forceDelete() { // get all the manga that have library_id to ours $manga = Manga::where('library_id', '=', $this->getId())->get(); // and delete them foreach ($manga as $manga_) { // Manga::forceDelete deletes all the references to other tables (artists, authors, manga_information, etc..) $manga_->forceDelete(); } parent::forceDelete(); } }
Fix Skype postDeploy hook name
'use strict'; const skReply = require('./reply'); const skParse = require('./parse'); module.exports = function skSetup(api, bot, logError) { api.post('/skype', request => { let arr = [].concat.apply([], request.body), skContextId = request.headers.contextid; let skHandle = parsedMessage => { if (!parsedMessage) return; return bot(parsedMessage) .then(botResponse => skReply(request.env.skypeAppId, request.env.skypePrivateKey, parsedMessage.sender, botResponse, skContextId)) .catch(logError); }; return Promise.all(arr.map(message => skParse(message)).map(skHandle)) .then(() => 'ok'); }); api.addPostDeployStep('skype', (options, lambdaDetails, utils) => { return utils.Promise.resolve().then(() => { if (options['configure-skype-bot']) { utils.Promise.promisifyAll(prompt); prompt.start(); return prompt.getAsync(['Skype App ID', 'Skype Private key']) .then(results => { const deployment = { restApiId: lambdaDetails.apiId, stageName: lambdaDetails.alias, variables: { skypeAppId: results['Skype App ID'], skypePrivateKey: results['Skype Private key'] } }; return utils.apiGatewayPromise.createDeploymentPromise(deployment); }); } }) .then(() => `${lambdaDetails.apiUrl}/skype`); }); };
'use strict'; const skReply = require('./reply'); const skParse = require('./parse'); module.exports = function skSetup(api, bot, logError) { api.post('/skype', request => { let arr = [].concat.apply([], request.body), skContextId = request.headers.contextid; let skHandle = parsedMessage => { if (!parsedMessage) return; return bot(parsedMessage) .then(botResponse => skReply(request.env.skypeAppId, request.env.skypePrivateKey, parsedMessage.sender, botResponse, skContextId)) .catch(logError); }; return Promise.all(arr.map(message => skParse(message)).map(skHandle)) .then(() => 'ok'); }); api.addPostDeployStep('facebook', (options, lambdaDetails, utils) => { return utils.Promise.resolve().then(() => { if (options['configure-skype-bot']) { utils.Promise.promisifyAll(prompt); prompt.start(); return prompt.getAsync(['Skype App ID', 'Skype Private key']) .then(results => { const deployment = { restApiId: lambdaDetails.apiId, stageName: lambdaDetails.alias, variables: { skypeAppId: results['Skype App ID'], skypePrivateKey: results['Skype Private key'] } }; return utils.apiGatewayPromise.createDeploymentPromise(deployment); }); } }) .then(() => `${lambdaDetails.apiUrl}/skype`); }); };
Replace double quotes with single quotes
<?php namespace RpsCompetition\Db; if (!class_exists('AVH_RPS_Client')) { header('Status: 403 Forbidden'); header('HTTP/1.1 403 Forbidden'); exit(); } /** * Class QueryBanquet * * @author Peter van der Does * @copyright Copyright (c) 2015, AVH Software * @package RpsCompetition\Db */ class QueryBanquet { private $rpsdb; /** * Constructor * * @param RpsDb $rpsdb */ public function __construct(RpsDb $rpsdb) { $this->rpsdb = $rpsdb; } /** * Get the banquets between the given dates * * @param string $season_start_date * @param string $season_end_date * * @return array */ public function getBanquets($season_start_date, $season_end_date) { $sql = $this->rpsdb->prepare( 'SELECT * FROM competitions WHERE Competition_Date >= %s AND Competition_Date < %s AND Theme LIKE %s ORDER BY ID', $season_start_date, $season_end_date, '%banquet%' ) ; $return = $this->rpsdb->get_results($sql, ARRAY_A); return $return; } }
<?php namespace RpsCompetition\Db; if (!class_exists('AVH_RPS_Client')) { header('Status: 403 Forbidden'); header('HTTP/1.1 403 Forbidden'); exit(); } /** * Class QueryBanquet * * @author Peter van der Does * @copyright Copyright (c) 2015, AVH Software * @package RpsCompetition\Db */ class QueryBanquet { private $rpsdb; /** * Constructor * * @param RpsDb $rpsdb */ public function __construct(RpsDb $rpsdb) { $this->rpsdb = $rpsdb; } /** * Get the banquets between the given dates * * @param string $season_start_date * @param string $season_end_date * * @return array */ public function getBanquets($season_start_date, $season_end_date) { $sql = $this->rpsdb->prepare( "SELECT * FROM competitions WHERE Competition_Date >= %s AND Competition_Date < %s AND Theme LIKE %s ORDER BY ID", $season_start_date, $season_end_date, '%banquet%' ) ; $return = $this->rpsdb->get_results($sql, ARRAY_A); return $return; } }
Add grunt-release and rename NPM module to grypher.
// Generated on 2014-07-07 using generator-nodejs 2.0.0 module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'test/**/*.js' ], options: { jshintrc: '.jshintrc' } }, jison: { all : { files: { 'lib/parser.js': 'data/grypher.jison' } } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, watch: { js: { files: ['**/*.js', 'data/*.jison', '!node_modules/**/*.js'], tasks: ['default'], options: { nospawn: true } } } }); grunt.loadNpmTasks('grunt-jison'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-cli'); grunt.loadNpmTasks('grunt-release'); grunt.registerTask('test', ['jshint', 'jison', 'mochacli', 'watch']); grunt.registerTask('ci', ['jshint', 'jison', 'mochacli']); grunt.registerTask('default', ['test']); grunt.registerTask('publish', ['ci', 'release']); };
// Generated on 2014-07-07 using generator-nodejs 2.0.0 module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'test/**/*.js' ], options: { jshintrc: '.jshintrc' } }, jison: { all : { files: { 'lib/parser.js': 'data/grypher.jison' } } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, watch: { js: { files: ['**/*.js', 'data/*.jison', '!node_modules/**/*.js'], tasks: ['default'], options: { nospawn: true } } } }); grunt.loadNpmTasks('grunt-jison'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-cli'); grunt.registerTask('test', ['jshint', 'jison', 'mochacli', 'watch']); grunt.registerTask('ci', ['jshint', 'jison', 'mochacli']); grunt.registerTask('default', ['test']); };
Fix issue with Flatpickr re-initializing itself
(function (window, document) { let fields = Array.prototype.slice.call( document.querySelectorAll('input[data-provides="anomaly.field_type.datetime"]:not(.flatpickr-input)') ); // Initialize inputs fields.forEach(function (field) { if (!field.getAttribute('readonly')) { let inputMode = field.getAttribute('data-input-mode'); let clearToggle = field.parentElement.querySelector('a[data-clear]'); let options = { altInput: true, allowInput: false, locale: field.getAttribute('data-locale'), altFormat: field.getAttribute('data-alt-format'), minuteIncrement: field.getAttribute('data-step') || 1, dateFormat: field.getAttribute('data-datetime-format'), time_24hr: Boolean(field.getAttribute('data-alt-format').match(/[GH]/)), enableTime: inputMode !== 'date', noCalendar: inputMode === 'time' }; let picker = field.flatpickr(options); if (clearToggle) { clearToggle.addEventListener('click', function (event) { event.preventDefault(); picker.clear(); }); } } }); })(window, document);
(function (window, document) { let fields = Array.prototype.slice.call( document.querySelectorAll('input[data-provides="anomaly.field_type.datetime"]') ); // Initialize inputs fields.forEach(function (field) { if (!field.getAttribute('readonly')) { let inputMode = field.getAttribute('data-input-mode'); let clearToggle = field.parentElement.querySelector('a[data-clear]'); let options = { altInput: true, allowInput: false, locale: field.getAttribute('data-locale'), altFormat: field.getAttribute('data-alt-format'), minuteIncrement: field.getAttribute('data-step') || 1, dateFormat: field.getAttribute('data-datetime-format'), time_24hr: Boolean(field.getAttribute('data-alt-format').match(/[GH]/)), enableTime: inputMode !== 'date', noCalendar: inputMode === 'time' }; let picker = field.flatpickr(options); if (clearToggle) { clearToggle.addEventListener('click', function (event) { event.preventDefault(); picker.clear(); }); } } }); })(window, document);
Make basestring work in Python 3
#! /usr/bin/env python # encoding: utf-8 from __future__ import absolute_import import urllib from .base import AuthenticationMixinBase from . import GrantFailed try: basestring except NameError: basestring = str class AuthorizationCodeMixin(AuthenticationMixinBase): """Implement helpers for the Authorization Code grant for OAuth2.""" def auth_url(self, scope, redirect): """Get the url to direct a user to authenticate.""" url = self.API_ROOT + "/oauth/authorize?" query = { "response_type": "code", "client_id": self.app_info[0] } if scope: if not isinstance(scope, basestring): scope = ' '.join(scope) query['scope'] = scope if redirect: query['redirect_uri'] = redirect return url + urllib.urlencode(query) def exchange_code(self, code, redirect): """Perform the exchange step for the code from the redirected user.""" code, headers, resp = self.call_grant('/oauth/access_token', { "grant_type": "authorization_code", "code": code, "redirect_uri": redirect }) if not code == 200: raise GrantFailed() self.token = resp['access_token'] return self.token, resp['user'], resp['scope']
#! /usr/bin/env python # encoding: utf-8 from __future__ import absolute_import import urllib from .base import AuthenticationMixinBase from . import GrantFailed class AuthorizationCodeMixin(AuthenticationMixinBase): """Implement helpers for the Authorization Code grant for OAuth2.""" def auth_url(self, scope, redirect): """Get the url to direct a user to authenticate.""" url = self.API_ROOT + "/oauth/authorize?" query = { "response_type": "code", "client_id": self.app_info[0] } if scope: if not isinstance(scope, basestring): scope = ' '.join(scope) query['scope'] = scope if redirect: query['redirect_uri'] = redirect return url + urllib.urlencode(query) def exchange_code(self, code, redirect): """Perform the exchange step for the code from the redirected user.""" code, headers, resp = self.call_grant('/oauth/access_token', { "grant_type": "authorization_code", "code": code, "redirect_uri": redirect }) if not code == 200: raise GrantFailed() self.token = resp['access_token'] return self.token, resp['user'], resp['scope']
Use requirements.txt for all requirements, at least for now.
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() version = '0.1' # Use requirements.txt for all requirements, at least for now. requires = [] if __name__ == '__main__': setup(name='pings', version=version, description='pings', long_description=README, classifiers=[ "Programming Language :: Python", "Framework :: Pylons", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='Christian Hudon', author_email='[email protected]', url='https://github.com/lisa-lab/pings', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="pings", scripts = ['leaderboards_server', 'storage_server'], entry_points = """\ [paste.app_factory] main = pings.web_server:main """, paster_plugins=['pyramid'], )
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() version = '0.1' requires = ['pyramid', 'pyramid_debugtoolbar'] if __name__ == '__main__': setup(name='pings', version=version, description='pings', long_description=README, classifiers=[ "Programming Language :: Python", "Framework :: Pylons", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='Christian Hudon', author_email='[email protected]', url='https://github.com/lisa-lab/pings', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="pings", scripts = ['leaderboards_server', 'storage_server'], entry_points = """\ [paste.app_factory] main = pings.web_server:main """, paster_plugins=['pyramid'], )
Modify migration file to include meta data changes The OIDCBackChannelLogoutEvent model's meta data was changed in commit f62a72b29f. Although this has no effect on the database, Django still wants to include the meta data in migrations. Since this migration file isn't yet included in any release, it can be modified, instead of creating a new migration file only for the meta data change.
from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ("helusers", "0001_add_ad_groups"), ] operations = [ migrations.CreateModel( name="OIDCBackChannelLogoutEvent", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("created_at", models.DateTimeField(default=django.utils.timezone.now)), ("iss", models.CharField(db_index=True, max_length=4096)), ("sub", models.CharField(blank=True, db_index=True, max_length=4096)), ("sid", models.CharField(blank=True, db_index=True, max_length=4096)), ], options={ "verbose_name": "OIDC back channel logout event", "verbose_name_plural": "OIDC back channel logout events", "unique_together": {("iss", "sub", "sid")}, }, ), ]
# Generated by Django 3.2.4 on 2021-06-21 05:46 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ("helusers", "0001_add_ad_groups"), ] operations = [ migrations.CreateModel( name="OIDCBackChannelLogoutEvent", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("created_at", models.DateTimeField(default=django.utils.timezone.now)), ("iss", models.CharField(db_index=True, max_length=4096)), ("sub", models.CharField(blank=True, db_index=True, max_length=4096)), ("sid", models.CharField(blank=True, db_index=True, max_length=4096)), ], options={ "unique_together": {("iss", "sub", "sid")}, }, ), ]
Disable district search + use contains filter for representatives.
var HDO = HDO || {}; (function (H, $) { H.representativeSelector = { init: function (opts) { var districtSelect, representativeSelect, representatives, selectedRepresentatives; districtSelect = opts.districtSelect; representativeSelect = opts.representativeSelect; representatives = districtSelect.data('representatives'); function useRepresentativesFrom(district) { representativeSelect.html('<option/>'); if (district === '') { selectedRepresentatives = representatives; } else { selectedRepresentatives = $(representatives).filter(function () { return district === this.district; }); } $.each(selectedRepresentatives, function () { representativeSelect.append($("<option />").val(this.slug).text(this.name)); }); representativeSelect.trigger('liszt:updated'); // chosen } districtSelect.change(function (e) { useRepresentativesFrom($(this).val()); if (opts.selectedRepresentative !== '') { representativeSelect.val(opts.selectedRepresentative).change(); } }); if (opts.selectedDistrict !== '') { districtSelect.val(opts.selectedDistrict).change(); } representativeSelect.chosen({search_contains: true}); districtSelect.chosen({disable_search: true}); } }; }(HDO, window.jQuery));
var HDO = HDO || {}; (function (H, $) { H.representativeSelector = { init: function (opts) { var districtSelect, representativeSelect, representatives, selectedRepresentatives; districtSelect = opts.districtSelect; representativeSelect = opts.representativeSelect; representatives = districtSelect.data('representatives'); function useRepresentativesFrom(district) { representativeSelect.html('<option/>'); if (district === '') { selectedRepresentatives = representatives; } else { selectedRepresentatives = $(representatives).filter(function () { return district === this.district; }); } $.each(selectedRepresentatives, function () { representativeSelect.append($("<option />").val(this.slug).text(this.name)); }); representativeSelect.trigger('liszt:updated'); // chosen } districtSelect.change(function (e) { useRepresentativesFrom($(this).val()); if (opts.selectedRepresentative !== '') { representativeSelect.val(opts.selectedRepresentative).change(); } }); if (opts.selectedDistrict !== '') { districtSelect.val(opts.selectedDistrict).change(); } representativeSelect.chosen({}); districtSelect.chosen({}); } }; }(HDO, window.jQuery));
Include worker in karma so coverage reveals that it's not tested
/*global module */ module.exports = function(config) { 'use strict'; 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: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'src/angular-jpeg-worker-app.js', 'src/angular-jpeg-worker-segments.js', 'src/angular-jpeg.js', 'src/angular-jpeg-worker.js', 'test/*.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: true, reporters: ['dots', 'coverage'], preprocessors: { 'src/*.js': ['coverage'] }, coverageReporter: { type: 'lcov', dir: 'coverage/' }, // 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 }); };
/*global module */ module.exports = function(config) { 'use strict'; 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: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'src/angular-jpeg-worker-app.js', 'src/angular-jpeg-worker-segments.js', 'src/angular-jpeg.js', //'src/angular-jpeg-worker.js', 'test/*.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: true, reporters: ['dots', 'coverage'], preprocessors: { 'src/*.js': ['coverage'] }, coverageReporter: { type: 'lcov', dir: 'coverage/' }, // 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 }); };
Save event emitter y producer reference in relayer instance
from kafka import KafkaProducer from .event_emitter import EventEmitter from .exceptions import ConfigurationError __version__ = '0.1.3' class Relayer(object): def __init__(self, logging_topic, context_handler_class, kafka_hosts=None, topic_prefix='', topic_suffix='', source=''): self.logging_topic = logging_topic if not kafka_hosts: raise ConfigurationError() if source == '': self.source = '{0}{1}{2}'.format(topic_prefix, logging_topic, topic_suffix) else: self.source = source self._producer = KafkaProducer(bootstrap_servers=kafka_hosts) self._emitter = EventEmitter(self._producer, topic_prefix=topic_prefix, topic_suffix=topic_suffix) self.context = context_handler_class(self._emitter) def emit(self, event_type, event_subtype, payload, partition_key=None): payload = { 'source': self.source, 'event_type': event_type, 'event_subtype': event_subtype, 'payload': payload } self.context.emit(event_type, payload, partition_key) def emit_raw(self, topic, message, partition_key=None): self.context.emit(topic, message, partition_key) def log(self, log_level, payload): message = { 'log_level': log_level, 'payload': payload } self.context.log(message) def flush(self): self._emitter.flush()
from kafka import KafkaProducer from .event_emitter import EventEmitter from .exceptions import ConfigurationError __version__ = '0.1.3' class Relayer(object): def __init__(self, logging_topic, context_handler_class, kafka_hosts=None, topic_prefix='', topic_suffix='', source=''): self.logging_topic = logging_topic if not kafka_hosts: raise ConfigurationError() if source == '': self.source = '{0}{1}{2}'.format(topic_prefix, logging_topic, topic_suffix) else: self.source = source producer = KafkaProducer(bootstrap_servers=kafka_hosts) emitter = EventEmitter(producer, topic_prefix=topic_prefix, topic_suffix=topic_suffix) self.context = context_handler_class(emitter) def emit(self, event_type, event_subtype, payload, partition_key=None): payload = { 'source': self.source, 'event_type': event_type, 'event_subtype': event_subtype, 'payload': payload } self.context.emit(event_type, payload, partition_key) def emit_raw(self, topic, message, partition_key=None): self.context.emit(topic, message, partition_key) def log(self, log_level, payload): message = { 'log_level': log_level, 'payload': payload } self.context.log(message) def flush(self): self.emitter.flush()
Review: Add comments. Remove space removal.
package org.apache.mesos.elasticsearch.scheduler.state; import java.io.IOException; import java.security.InvalidParameterException; /** * Path utilities */ public class StatePath { private SerializableState zkState; public StatePath(SerializableState zkState) { this.zkState = zkState; } /** * Creates the zNode if it does not exist. Will create parent directories. * @param key the zNode path */ public void mkdir(String key) throws IOException { key = key.replace(" ", ""); if (key.endsWith("/") && !key.equals("/")) { throw new InvalidParameterException("Trailing slash not allowed in zookeeper path"); } String[] split = key.split("/"); StringBuilder builder = new StringBuilder(); for (String s : split) { builder.append(s); if (!s.isEmpty() && !exists(builder.toString())) { zkState.set(builder.toString(), null); } builder.append("/"); } } public Boolean exists(String key) throws IOException { Boolean exists = true; Object value = zkState.get(key); if (value == null) { exists = false; } return exists; } /** * Remove a zNode or zFolder. * * @param key the path to remove. * @throws IOException If unable to remove */ public void rm(String key) throws IOException { zkState.delete(key); } }
package org.apache.mesos.elasticsearch.scheduler.state; import org.apache.log4j.Logger; import java.io.IOException; import java.security.InvalidParameterException; /** * Path utilities */ public class StatePath { private static final Logger LOGGER = Logger.getLogger(StatePath.class); private SerializableState zkState; public StatePath(SerializableState zkState) { this.zkState = zkState; } /** * Creates the zNode if it does not exist. Will create parent directories. * @param key the zNode path */ public void mkdir(String key) throws IOException { key = key.replace(" ", ""); if (key.endsWith("/") && !key.equals("/")) { throw new InvalidParameterException("Trailing slash not allowed in zookeeper path"); } String[] split = key.split("/"); StringBuilder builder = new StringBuilder(); for (String s : split) { builder.append(s); if (!s.isEmpty() && !exists(builder.toString())) { zkState.set(builder.toString(), null); } builder.append("/"); } } public Boolean exists(String key) throws IOException { Boolean exists = true; Object value = zkState.get(key); if (value == null) { exists = false; } return exists; } public void rm(String key) throws IOException { key = key.replace(" ", ""); zkState.delete(key); } }
Update description and add 'tox' as a testing dependency.
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ # None ] test_requirements = [ 'tox', ] setup( name='generalwords', version='0.1.0', description='A somewhat curated collection of words to use in nonce generation.', long_description=readme + '\n\n' + history, author='Christopher Petrilli', author_email='[email protected]', url='https://github.com/petrilli/generalwords', packages=[ 'generalwords', ], package_dir={'generalwords': 'generalwords'}, include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='generalwords', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', tests_require=test_requirements )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ # TODO: put package requirements here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='generalwords', version='0.1.0', description='Python Boilerplate contains all the boilerplate you need to create a Python package.', long_description=readme + '\n\n' + history, author='Christopher Petrilli', author_email='[email protected]', url='https://github.com/petrilli/generalwords', packages=[ 'generalwords', ], package_dir={'generalwords': 'generalwords'}, include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='generalwords', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', tests_require=test_requirements )
Make index fields public constants So they are reusable by other classes.
package de.hsmannheim.iws2014.indexing; import org.apache.lucene.document.*; import org.apache.lucene.index.IndexWriter; import java.io.IOException; import java.util.List; /** * This class does all the hard work. Indexing developers. */ public class Indexer { public static final String FIRSTNAME = "firstname"; public static final String SURNAME = "surname"; public static final String RESIDENCE = "residence"; public static final String PERSONAL_ABSTRACT = "personalAbstract"; private final IndexWriter index; public Indexer(IndexWriter index) { this.index = index; } public void index(List<Developer> developers) { try { try { for (Developer developer : developers) { Document doc = new Document(); doc.add(stringField(FIRSTNAME, developer.firstname)); doc.add(stringField(SURNAME, developer.surname)); doc.add(stringField(RESIDENCE, developer.residence)); doc.add(textField(PERSONAL_ABSTRACT, developer.personalAbstract)); index.addDocument(doc); } } finally { index.close(); } } catch (IOException e) { new IndexerException("Cannot add dcoument to index.", e); } } private static StringField stringField(String name, String value) { return new StringField(name, value, Field.Store.YES); } private static TextField textField(String name, String value) { return new TextField(name, value, Field.Store.NO); } static class IndexerException extends RuntimeException { public IndexerException(String message, Throwable e) { super(message, e); } } }
package de.hsmannheim.iws2014.indexing; import org.apache.lucene.document.*; import org.apache.lucene.index.IndexWriter; import java.io.IOException; import java.util.List; /** * This class does all the hard work. Indexing developers. */ public class Indexer { private final IndexWriter index; public Indexer(IndexWriter index) { this.index = index; } public void index(List<Developer> developers) { try { try { for (Developer developer : developers) { Document doc = new Document(); doc.add(stringField("firstname", developer.firstname)); doc.add(stringField("surname", developer.surname)); doc.add(stringField("residence", developer.residence)); doc.add(textField("personalAbstract", developer.personalAbstract)); index.addDocument(doc); } } finally { index.close(); } } catch (IOException e) { new IndexerException("Cannot add dcoument to index.", e); } } private static StringField stringField(String name, String value) { return new StringField(name, value, Field.Store.YES); } private static TextField textField(String name, String value) { return new TextField(name, value, Field.Store.NO); } static class IndexerException extends RuntimeException { public IndexerException(String message, Throwable e) { super(message, e); } } }
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helper functions. """ # built-in modules import json # local modules from mass.exception import UnsupportedScheduler from mass.input_handler import InputHandler from mass.scheduler.swf import config def submit(job, protocol=None, priority=1, scheduler='swf'): """Submit mass job to SWF with specific priority. """ if scheduler != 'swf': raise UnsupportedScheduler(scheduler) import boto3 client = boto3.client('swf', region_name=config.REGION) handler = InputHandler(protocol) res = client.start_workflow_execution( domain=config.DOMAIN, workflowId=job.title, workflowType=config.WORKFLOW_TYPE_FOR_JOB, taskList={'name': config.DECISION_TASK_LIST}, taskPriority=str(priority), input=json.dumps({ 'protocol': protocol, 'body': handler.save( data=job, job_title=job.title, task_title=job.title ) }), executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT), tagList=[job.title], taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT), childPolicy=config.WORKFLOW_CHILD_POLICY) return job.title, res['runId']
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helper functions. """ # built-in modules import json # local modules from mass.input_handler import InputHandler from mass.scheduler.swf import config def submit(job, protocol=None, priority=1): """Submit mass job to SWF with specific priority. """ import boto3 client = boto3.client('swf', region_name=config.REGION) handler = InputHandler(protocol) res = client.start_workflow_execution( domain=config.DOMAIN, workflowId=job.title, workflowType=config.WORKFLOW_TYPE_FOR_JOB, taskList={'name': config.DECISION_TASK_LIST}, taskPriority=str(priority), input=json.dumps({ 'protocol': protocol, 'body': handler.save( data=job, job_title=job.title, task_title=job.title ) }), executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT), tagList=[job.title], taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT), childPolicy=config.WORKFLOW_CHILD_POLICY) return job.title, res['runId']
Fix issue where users were not saving to the database. We use .fetchAll() rather than .fetch() to find all instances of a user. Added auto-timestamp functionality so all create and update times are automatically marked with no manual intervention needed.
// SignupController // ================ // Handles routing for signing up for the pp 'use strict'; let express = require('express'), SignupController = express.Router(), bcrypt = require('bcrypt'), User = require(__dirname + '/../models/user'); SignupController.route('/?') // GET /signup/ // ----------- // Render login page .get(function(req, res, next) { res.render('authentication/signup', { csrf: req.csrfToken(), scripts: ['/js/signup.min.js'] }); }) // POST /signup/ // ------------ // Registers a new user .post(function(req, res, next) { // Check if user exists in database User.where({ email: req.body.email }) .fetchAll() .then(function(user) { if (user) { bcrypt.hash(req.body.password, 10, function(err, hash) { if (err) return next(new Error('Could not hash password')); // Create a new user new User({ email: req.body.email, password: hash }) .save() .then(function(user) { res.send('User created'); }) .catch(function(err) { res.send('username or email already taken'); }); }); } else { res.send('could not create new user'); } }) .catch(function(err) { console.log(err, 'FETCH ERROR'); res.send('Could not run fetch query'); }); }); module.exports = SignupController;
// SignupController // ================ // Handles routing for signing up for the pp 'use strict'; let express = require('express'), SignupController = express.Router(), bcrypt = require('bcrypt'), User = require(__dirname + '/../models/user'); SignupController.route('/?') // GET /signup/ // ----------- // Render login page .get(function(req, res, next) { res.render('authentication/signup', { csrf: req.csrfToken(), scripts: ['/js/signup.min.js'] }); }) // POST /signup/ // ------------ // Registers a new user .post(function(req, res, next) { // Check if user exists in database User .where({ email: req.body.email }) .fetch() .then(function(user) { if (user) { bcrypt.hash(req.body.password, 10, function(err, hash) { if (err) return next(new Error('Could not hash password')); // Create a new user new User({ email: req.body.email, password: hash }) .save() .then(function(user) { res.send('User created'); }) .catch(function(err) { res.send('username or email already taken'); }); }); } else { res.send('could not create new user'); } }) .catch(function(err) { console.log(err, 'FETCH ERROR'); res.send('Could not run fetch query'); }); }); module.exports = SignupController;
Fix deprecated usage of the config component
<?php namespace Incenteev\TranslationCheckerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('incenteev_translation_checker'); if (method_exists($treeBuilder, 'getRootNode')) { $rootNode = $treeBuilder->getRootNode(); } else { $rootNode = $treeBuilder->root('incenteev_translation_checker'); } $rootNode ->children() ->arrayNode('extraction') ->addDefaultsIfNotSet() ->fixXmlConfig('bundle') ->children() ->arrayNode('bundles') ->prototype('scalar')->end() ->end() ->arrayNode('js') ->addDefaultsIfNotSet() ->fixXmlConfig('path') ->children() ->scalarNode('default_domain') ->info('The default domain used for JS translation (should match the JsTranslationBundle config)') ->defaultValue('messages') ->end() ->arrayNode('paths') ->prototype('scalar')->end() ->end() ->end() ->end() ->end() ->end() ->end(); return $treeBuilder; } }
<?php namespace Incenteev\TranslationCheckerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder->root('incenteev_translation_checker') ->children() ->arrayNode('extraction') ->addDefaultsIfNotSet() ->fixXmlConfig('bundle') ->children() ->arrayNode('bundles') ->prototype('scalar')->end() ->end() ->arrayNode('js') ->addDefaultsIfNotSet() ->fixXmlConfig('path') ->children() ->scalarNode('default_domain') ->info('The default domain used for JS translation (should match the JsTranslationBundle config)') ->defaultValue('messages') ->end() ->arrayNode('paths') ->prototype('scalar')->end() ->end() ->end() ->end() ->end() ->end() ->end(); return $treeBuilder; } }
Complete parsing system, fully functional
<?php include("/home/c0smic/secure/data_db_settings.php"); $body = file_get_contents('php://input'); $stime = ""; $etime = ""; $moves = ""; function parseData($body) { $splitter = substr($body, 0, 1); global $stime, $etime, $moves; $mark1 = strpos($body, $splitter, 1); $mark2 = strpos($body, $splitter, $mark1+1); $mark3 = strpos($body, $splitter, $mark2+1); $stime = substr($body, 1, $mark1-1); $etime = substr($body, $mark1+1, $mark2-$mark1-1); $moves = substr($body, $mark2+1, $mark3-$mark2-1); } parseData($body); $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
<?php include("/home/c0smic/secure/data_db_settings.php"); $body = file_get_contents('php://input'); $stime = ""; $etime = ""; $moves = ""; function parseData($body) { $splitter = '|'; global $stime, $etime, $moves; $inc = 1; while(strcmp(substr($body, $inc, 1), $splitter) > 0) { $stime = $stime . substr($body, $inc, 1); $inc++; } $inc++; while(strcmp(substr($body, $inc, 1), $splitter) > 0) { $etime = $etime . substr($body, $inc, 1); $inc++; } $inc++; while(strcmp(substr($body, $inc, 1), $splitter) > 0) { $moves = $moves . substr($body, $inc, 1); } } parseData($body); $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
Use hgtools 5 or later for use_vcs_version
import sys import setuptools def read_long_description(): with open('README.rst') as f: data = f.read() with open('CHANGES.rst') as f: data += '\n\n' + f.read() return data importlib_req = ['importlib'] if sys.version_info < (2,7) else [] argparse_req = ['argparse'] if sys.version_info < (2,7) else [] setup_params = dict( name="irc", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), use_vcs_version=True, packages=setuptools.find_packages(), author="Joel Rosdahl", author_email="[email protected]", maintainer="Jason R. Coombs", maintainer_email="[email protected]", url="http://python-irclib.sourceforge.net", license="MIT", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], install_requires=[ 'six', 'jaraco.util', ] + importlib_req + argparse_req, setup_requires=[ 'hgtools>=5', 'pytest-runner', ], tests_require=[ 'pytest', 'mock', ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
import sys import setuptools def read_long_description(): with open('README.rst') as f: data = f.read() with open('CHANGES.rst') as f: data += '\n\n' + f.read() return data importlib_req = ['importlib'] if sys.version_info < (2,7) else [] argparse_req = ['argparse'] if sys.version_info < (2,7) else [] setup_params = dict( name="irc", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), use_hg_version=True, packages=setuptools.find_packages(), author="Joel Rosdahl", author_email="[email protected]", maintainer="Jason R. Coombs", maintainer_email="[email protected]", url="http://python-irclib.sourceforge.net", license="MIT", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], install_requires=[ 'six', 'jaraco.util', ] + importlib_req + argparse_req, setup_requires=[ 'hgtools', 'pytest-runner', ], tests_require=[ 'pytest', 'mock', ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitemap test ), ROOT_URLCONF='localeurl.tests.test_urls', SITE_ID=1, ) if VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive, failfast=False) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests( test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitemap test ), ROOT_URLCONF='localeurl.tests.test_urls', ) if VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive, failfast=False) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests( test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Allow error email to still be sent if DB is down We were seeing errors in the logs where the database was inaccessible, but the errors were not being emailed out because the handler makes a DB query.
from logging.handlers import SMTPHandler DEV_TEAM_EMAILS_QUERY = '''SELECT DISTINCT email FROM members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups WHERE group_name = "Devteam" ''' DEFAULT_DEV_TEAM_EMAILS = ['[email protected]'] class DonutSMTPHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, db_instance, credentials=None, secure=None, timeout=5.0): super().__init__(mailhost, fromaddr, toaddrs, subject, credentials, secure, timeout) self.db_instance = db_instance def emit(self, record): ''' Overrides SMTPHandler's emit such that we dynamically get current donut dev team members ''' self.toaddrs = self.getAdmins() super().emit(record) def getAdmins(self): ''' Returns current members in Devteam ''' try: with self.db_instance.cursor() as cursor: cursor.execute(DEV_TEAM_EMAILS_QUERY) res = cursor.fetchall() return [result['email'] for result in res] except Exception: # If the database is inaccessible, fallback to a hard-coded email list return DEFAULT_DEV_TEAM_EMAILS
from logging.handlers import SMTPHandler DEV_TEAM_EMAILS_QUERY = '''SELECT DISTINCT email FROM members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups WHERE group_name = "Devteam" ''' class DonutSMTPHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, db_instance, credentials=None, secure=None, timeout=5.0): super().__init__(mailhost, fromaddr, toaddrs, subject, credentials, secure, timeout) self.db_instance = db_instance def emit(self, record): ''' Overrides SMTPHandler's emit such that we dynamically get current donut dev team members ''' self.toaddrs = self.getAdmins() super().emit(record) def getAdmins(self): ''' Returns current members in Devteam ''' with self.db_instance.cursor() as cursor: cursor.execute(DEV_TEAM_EMAILS_QUERY, []) res = cursor.fetchall() return [result['email'] for result in res]
Add validation to show reactivate button to AdminUser list
window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'state', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: 'deleted', model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), (item.deactivated_at) ? m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) : '' ]), ]); } }; }(window.m, window._, window.c));
window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'state', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: 'deleted', model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) ]), ]); } }; }(window.m, window._, window.c));
Multiply rss parsed from ps on OSX by 1024 to convert to bytes
var exec = require('child_process').exec; module.exports = function(sysinfo) { return new MacProvider(sysinfo); }; function MacProvider(sysinfo) { this.lookup = function(pid, options, callback) { if(typeof options == 'function') { callback = options; options = {}; } options = options || {}; exec('ps -vp ' + pid, function(err, stdout, stderr) { if (err || stderr) return callback(err || stderr); var usage = parsePS(pid, stdout); if (!usage) return callback('INVALID_PID'); callback(null, usage); }); }; } function parsePS(pid, output) { var lines = output.trim().split('\n'); if (lines.length !== 2) return null; var labelsMap = {}; var labels = lines[0].trim().split(/[ \t]+/g); for (var i = 0; i < labels.length; i++) labelsMap[labels[i]] = i; var values = lines[1].trim().split(/[ \t]+/g); var foundPID = parseInt(values[labelsMap['PID']], 10); var rss = 1024 * parseInt(values[labelsMap['RSS']], 10); var cpu = parseFloat(values[labelsMap['%CPU']]); if (pid != foundPID || isNaN(rss) || isNaN(cpu)) return null; return { memory: rss, cpu: cpu }; }
var exec = require('child_process').exec; module.exports = function(sysinfo) { return new MacProvider(sysinfo); }; function MacProvider(sysinfo) { this.lookup = function(pid, options, callback) { if(typeof options == 'function') { callback = options; options = {}; } options = options || {}; exec('ps -vp ' + pid, function(err, stdout, stderr) { if (err || stderr) return callback(err || stderr); var usage = parsePS(pid, stdout); if (!usage) return callback('INVALID_PID'); callback(null, usage); }); }; } function parsePS(pid, output) { var lines = output.trim().split('\n'); if (lines.length !== 2) return null; var labelsMap = {}; var labels = lines[0].trim().split(/[ \t]+/g); for (var i = 0; i < labels.length; i++) labelsMap[labels[i]] = i; var values = lines[1].trim().split(/[ \t]+/g); var foundPID = parseInt(values[labelsMap['PID']], 10); var rss = parseInt(values[labelsMap['RSS']], 10); var cpu = parseFloat(values[labelsMap['%CPU']]); if (pid != foundPID || isNaN(rss) || isNaN(cpu)) return null; return { memory: rss, cpu: cpu }; }
Hide vote buttons if user is not logged in.
<?php use yii\helpers\Html; /* @var $model ShortCirquit\LinkoScopeApi\models\Link */ ?> <div> <div> <?= ($index + 1) ?>: <?php if (!Yii::$app->user->isGuest) : ?> <?= Html::a('<span class="glyphicon glyphicon-arrow-up"></span>', ['up', 'id' => $model->id,], ['title' => 'Up']) ?> <?= Html::a('<span class="glyphicon glyphicon-arrow-down"></span>', ['down', 'id' => $model->id,], ['title' => 'Down']) ?> <?php endif; ?> [<?= Html::a($model->title, $model->url, ['target' => '_blank',]); ?>] (<?= parse_url($model->url, PHP_URL_HOST) ?>) </div> <?php if (!Yii::$app->user->isGuest) : ?> <div style="top: 0px; float: right;"> <?= '' /* Html::a('<span class="glyphicon glyphicon-trash"></span>', ['delete', 'id' => $model->id,], ['title' => 'Delete']) */ ?> </div> <?php endif; ?> </div> <div> <?= "$model->authorName | " . date('D d M Y', strtotime($model->date)) . " | $model->votes votes | " . Html::a($model->comments == 0 ? "discuss" : "$model->comments comments", ['link/view', 'id' => $model->id]) ?> </div>
<?php use yii\helpers\Html; /* @var $model ShortCirquit\LinkoScopeApi\models\Link */ ?> <div> <div> <?= ($index + 1) ?>: <?= Html::a('<span class="glyphicon glyphicon-arrow-up"></span>', ['up', 'id' => $model->id,], ['title' => 'Up']) ?> <?= Html::a('<span class="glyphicon glyphicon-arrow-down"></span>', ['down', 'id' => $model->id,], ['title' => 'Down']) ?> [<?= Html::a($model->title, $model->url, ['target' => '_blank',]); ?>] (<?= parse_url($model->url, PHP_URL_HOST) ?>) </div> <?php if (!Yii::$app->user->isGuest) : ?> <div style="top: 0px; float: right;"> <?= '' /* Html::a('<span class="glyphicon glyphicon-trash"></span>', ['delete', 'id' => $model->id,], ['title' => 'Delete']) */ ?> </div> <?php endif; ?> </div> <div> <?= "$model->authorName | " . date('D d M Y', strtotime($model->date)) . " | $model->votes votes | " . Html::a($model->comments == 0 ? "discuss" : "$model->comments comments", ['link/view', 'id' => $model->id]) ?> </div>
Change encoding of xml to encode all except xml tags
package fr.insee.rmes.utils; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.codehaus.stax2.io.EscapingWriterFactory; public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory { public Writer createEscapingWriterFor(final Writer out, String enc) { return new Writer(){ @Override public void write(char[] cbuf, int off, int len) throws IOException { //WARN : the cbuf contains only part of the string = can't validate xml here String val = ""; for (int i = off; i < len; i++) { val += cbuf[i]; } String escapedStr = encodeXml(escapeHtml(val)); //encode manually some xml tags out.write(escapedStr); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } }; } private String escapeHtml(String s) { return s.replace("&", "&amp;") .replace(">", "&gt;") .replace("<", "&lt;") .replace("\"", "&quot;"); } private String encodeXml(String s) { return s.replaceAll("&lt;([a-zA-Z]+)&gt;", "<$1>") //xml open tag .replaceAll("&lt;/([a-zA-Z]+)&gt;", "</$1>") //xml close tag .replaceAll("&lt;([a-zA-Z]+)/&gt;", "<$1/>") //br .replaceAll("&lt;([a-zA-Z]+) /&gt;", "<$1 />"); //br with space } public Writer createEscapingWriterFor(OutputStream out, String enc) { throw new IllegalArgumentException("not supported"); } }
package fr.insee.rmes.utils; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.codehaus.stax2.io.EscapingWriterFactory; public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory { public Writer createEscapingWriterFor(final Writer out, String enc) { return new Writer(){ @Override public void write(char[] cbuf, int off, int len) throws IOException { String val = ""; for (int i = off; i < len; i++) { val += cbuf[i]; } String escapedStr = escapeHtml(val); //convert special characters excluding xml tags out.write(escapedStr); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } }; } private String escapeHtml(String s) { return s.replace("&", "&amp;") .replace(">", "&gt;") .replace("<", "&lt;") .replace("\"", "&quot;"); // .replace("'", "&apos;"); } public Writer createEscapingWriterFor(OutputStream out, String enc) { throw new IllegalArgumentException("not supported"); } }
Add on end stream event
var es = require('event-stream'); var cred = { app:require('../../config/app'), user:require('../../config/user') }; exports = module.exports = function (p) { return { // retrieve all of the lists defined for your user account 0: function () { p.query() .select('lists/list') .auth(cred.user.mailchimp.apikey) .request(function (err, res, body) { debugger; if (err) console.log(err); console.log(body); }); }, // export contacts from a list 1: function () { p.query('export') .select('list') .where({id:'bd0b216f1c'}) .auth(cred.user.mailchimp.apikey) .request(function (err, res, body) { debugger; if (err) console.log(err); console.log(body); }); }, // stream contacts from a list 2: function () { p.query('export') .select('list') .where({id:'bd0b216f1c'}) .auth(cred.user.mailchimp.apikey) .request() .pipe(es.split()) .pipe(es.map(function (data, done) { console.log(data); console.log('---------------------'); done(); })) .on('end', function (e) { console.log('DONE!'); }); } }; }
var es = require('event-stream'); var cred = { app:require('../../config/app'), user:require('../../config/user') }; exports = module.exports = function (p) { return { // retrieve all of the lists defined for your user account 0: function () { p.query() .select('lists/list') .auth(cred.user.mailchimp.apikey) .request(function (err, res, body) { debugger; if (err) console.log(err); console.log(body); }); }, // export contacts from a list 1: function () { p.query('export') .select('list') .where({id:'bd0b216f1c'}) .auth(cred.user.mailchimp.apikey) .request(function (err, res, body) { debugger; if (err) console.log(err); console.log(body); }); }, // stream contacts from a list 2: function () { p.query('export') .select('list') .where({id:'bd0b216f1c'}) .auth(cred.user.mailchimp.apikey) .request() .pipe(es.split()) .pipe(es.map(function (data, done) { console.log(data); console.log('---------------------'); done(); })); } }; }
Add basic validation of ui state.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter') self.selector_widget.added.connect(self.on_selection_changed) self.selector_widget.removed.connect(self.on_selection_changed) self.validate() def on_selection_changed(self, items): '''Handle selection change.''' self.validate() def validate(self): '''Validate options and update UI state.''' self.export_button.setEnabled(False) if not self.selector_widget.items(): return self.export_button.setEnabled(True)
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): '''Initialise with *host* application and *parent*.''' super(ExporterWidget, self).__init__(parent=parent) self.host = host self.build() self.post_build() def build(self): '''Build and layout the interface.''' self.setLayout(QtGui.QVBoxLayout()) self.selector_widget = SelectorWidget(host=self.host) self.selector_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.selector_widget) self.options_widget = OptionsWidget(host=self.host) self.options_widget.setFrameStyle( QtGui.QFrame.StyledPanel ) self.layout().addWidget(self.options_widget) self.export_button = QtGui.QPushButton('Export') self.layout().addWidget(self.export_button) def post_build(self): '''Perform post-build operations.''' self.setWindowTitle('Segue Exporter')
Handle the case of an empty path This will deal with the root domain request going to default page.
import boto3 import botocore from flask import ( abort, current_app, flash, make_response, redirect, request, Response, url_for, ) from flask_login import current_user from . import passthrough_bp @passthrough_bp.route('/<path:path>') def passthrough(path): if not current_user.is_authenticated: return redirect(url_for('auth.login', next=request.path)) else: default_page = current_app.config.get('S3_INDEX_DOCUMENT') if default_page and (path == '' or path.endswith('/')): path += default_page s3 = boto3.resource('s3') bucket = current_app.config.get('S3_BUCKET') obj = s3.Object(bucket, path) try: obj_resp = obj.get() def generate(result): for chunk in iter(lambda: result['Body'].read(8192), b''): yield chunk response = Response(generate(obj_resp)) response.headers['Content-Type'] = obj_resp['ContentType'] response.headers['Content-Encoding'] = obj_resp['ContentEncoding'] return response except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": abort(404) elif e.response['Error']['Code'] == 'NoSuchKey': abort(404) else: raise
import boto3 import botocore from flask import ( abort, current_app, flash, make_response, redirect, request, Response, url_for, ) from flask_login import current_user from . import passthrough_bp @passthrough_bp.route('/<path:path>') def passthrough(path): if not current_user.is_authenticated: return redirect(url_for('auth.login', next=request.path)) else: default_page = current_app.config.get('S3_INDEX_DOCUMENT') if default_page and path.endswith('/'): path += default_page s3 = boto3.resource('s3') bucket = current_app.config.get('S3_BUCKET') obj = s3.Object(bucket, path) try: obj_resp = obj.get() def generate(result): for chunk in iter(lambda: result['Body'].read(8192), b''): yield chunk response = Response(generate(obj_resp)) response.headers['Content-Type'] = obj_resp['ContentType'] response.headers['Content-Encoding'] = obj_resp['ContentEncoding'] return response except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": abort(404) elif e.response['Error']['Code'] == 'NoSuchKey': abort(404) else: raise
Add alert and logout when no login details given
/** * Generic error handler method for ajax responses. * Apply your specific requirements for an error response and then call this method to take care of the rest. * @param response */ function handleApiError(response) { if (!response || response.status === 200) return; if (response.status === 403 || response.status === 401) { //sweetAlert('You are not logged in', 'Please refresh Florence and log back in.'); logout(); } else if (response.status === 504) { sweetAlert('This task is taking longer than expected', "It will continue to run in the background.", "info"); } else { var message = 'An error has occurred, please contact an administrator.'; if (response.responseJSON) { message = response.responseJSON.message; } console.log(message); sweetAlert("Error", message, "error"); } } /* Unique error handling for the login screen */ function handleLoginApiError(response) { if (!response || response.status === 200) return; if (response.status === 400) { sweetAlert("Please enter a valid username and password"); logout(); } else if (response.status === 403 || response.status === 401) { sweetAlert('Incorrect login details', 'These login credentials were not recognised. Please try again.', 'error'); logout(); } else { var message = 'An error has occurred, please contact an administrator.'; if (response.responseJSON) { message = response.responseJSON.message; } console.log(message); sweetAlert("Error", message, "error"); } }
/** * Generic error handler method for ajax responses. * Apply your specific requirements for an error response and then call this method to take care of the rest. * @param response */ function handleApiError(response) { if (!response || response.status === 200) return; if (response.status === 403 || response.status === 401) { //sweetAlert('You are not logged in', 'Please refresh Florence and log back in.'); logout(); } else if (response.status === 504) { sweetAlert('This task is taking longer than expected', "It will continue to run in the background.", "info"); } else { var message = 'An error has occurred, please contact an administrator.'; if (response.responseJSON) { message = response.responseJSON.message; } console.log(message); sweetAlert("Error", message, "error"); } } /* Unique error handling for the login screen */ function handleLoginApiError(response) { if (!response || response.status === 200) return; if (response.status === 403 || response.status === 401) { sweetAlert('Incorrect login details', 'These login credentials were not recognised. Please try again.', 'error'); logout(); } else { var message = 'An error has occurred, please contact an administrator.'; if (response.responseJSON) { message = response.responseJSON.message; } console.log(message); sweetAlert("Error", message, "error"); } }
Edit tags in edit form input
import React, { Component, PropTypes } from 'react'; import { getDescriptionAndTags, buildDescriptionAndTags } from '../helpers'; class EditActivityForm extends Component { componentDidMount() { this.description.focus(); } updateActivity(e) { e.preventDefault(); const { description, tags } = getDescriptionAndTags(this.description.value); const activity = { description, tags, timestamp: this.props.timestamp, } this.props.updateActivity(activity); this.props.cancelEdit(); } render() { const { activity } = this.props; const { description, tags } = activity; return ( <div className="row row--middle row--start"> <form className="col--12" onSubmit={(e) => this.updateActivity(e)} ref={(input) => this.activityForm = input} > <div className="row row--middle"> <div className="col--6"> <input type="text" className="w--100 pv- ph-" ref={(node) => this.description = node} defaultValue={buildDescriptionAndTags(description, tags)} placeholder="went to the park" /> </div> <div className="col--2"> <button type="submit">Update</button> </div> <div className="col--2"> <div onClick={this.props.cancelEdit}>cancel</div> </div> </div> </form> </div> ); } } EditActivityForm.propTypes = { updateActivity: PropTypes.func.isRequired, cancelEdit: PropTypes.func.isRequired, activity: PropTypes.object.isRequired, }; export default EditActivityForm;
import React, { Component, PropTypes } from 'react'; class EditActivityForm extends Component { componentDidMount() { this.description.focus(); } updateActivity(e) { e.preventDefault(); const activity = { description: this.description.value, timestamp: this.props.timestamp, } this.props.updateActivity(activity); this.props.cancelEdit(); } render() { return ( <div className="row row--middle row--start"> <form className="col--12" onSubmit={(e) => this.updateActivity(e)} ref={(input) => this.activityForm = input} > <div className="row row--middle"> <div className="col--6"> <input type="text" className="w--100 pv- ph-" ref={(node) => this.description = node} defaultValue={this.props.activity.description} placeholder="went to the park" /> </div> <div className="col--2"> <button type="submit">Update</button> </div> <div className="col--2"> <div onClick={this.props.cancelEdit}>cancel</div> </div> </div> </form> </div> ); } } EditActivityForm.propTypes = { updateActivity: PropTypes.func.isRequired, cancelEdit: PropTypes.func.isRequired, activity: PropTypes.object.isRequired, }; export default EditActivityForm;
Remove semi-colon for sails lift to run correctly
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'safe' };
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'safe'; };
Allow list of flashers as show token value
"""Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager from mpf.core.utility_functions import Util class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ = ["delay"] def __init__(self, machine): """Initialise flasher_player.""" super().__init__(machine) self.delay = DelayManager(self.machine.delayRegistry) def play(self, settings, context, calling_context, priority=0, **kwargs): """Flash flashers.""" del kwargs for flasher, s in settings.items(): if isinstance(flasher, str): flasher_names = Util.string_to_list(flasher) for flasher_name in flasher_names: self._flash(self.machine.lights[flasher_name], duration_ms=s['ms'], key=context) else: self._flash(flasher, duration_ms=s['ms'], key=context) def _flash(self, light, duration_ms, key): light.color("white", fade_ms=0, key=key) self.delay.add(duration_ms, self._remove_flash, light=light, key=key) @staticmethod def _remove_flash(light, key): light.remove_from_stack_by_key(key=key, fade_ms=0) def get_express_config(self, value): """Parse express config.""" return dict(ms=value)
"""Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ = ["delay"] def __init__(self, machine): """Initialise flasher_player.""" super().__init__(machine) self.delay = DelayManager(self.machine.delayRegistry) def play(self, settings, context, calling_context, priority=0, **kwargs): """Flash flashers.""" del kwargs for flasher, s in settings.items(): if isinstance(flasher, str): self._flash(self.machine.lights[flasher], duration_ms=s['ms'], key=context) else: self._flash(flasher, duration_ms=s['ms'], key=context) def _flash(self, light, duration_ms, key): light.color("white", fade_ms=0, key=key) self.delay.add(duration_ms, self._remove_flash, light=light, key=key) @staticmethod def _remove_flash(light, key): light.remove_from_stack_by_key(key=key, fade_ms=0) def get_express_config(self, value): """Parse express config.""" return dict(ms=value)
Make sure to limit the number of simultaneous requests
<?php namespace Happyr\LocoBundle\Http; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Pool; use Happyr\LocoBundle\Exception\HttpException; /** * @author Tobias Nyholm */ class Guzzle5Adapter implements HttpAdapterInterface { /** * {@inheritdoc} */ public function send($method, $url, $data) { $client = new Client([ 'base_url' => HttpAdapterInterface::BASE_URL, ]); try { $response = $client->send($client->createRequest($method, $url, $data)); } catch (ClientException $e) { throw new HttpException('Could not transfer data to Loco', $e->getCode(), $e); } return $response->json(); } /** * @param array $data array($url=>$savePath) */ public function downloadFiles(array $data) { $client = new Client(); $requests = array(); foreach ($data as $url => $path) { $requests[] = $client->createRequest('GET', HttpAdapterInterface::BASE_URL.$url, [ 'save_to' => $path, ]); } // Results is a GuzzleHttp\BatchResults object. $results = Pool::batch($client, $requests, [ 'pool_size' => 5, ]); // Retrieve all failures. foreach ($results->getFailures() as $requestException) { //TODO error handling throw new \Exception($requestException->getMessage()); } } }
<?php namespace Happyr\LocoBundle\Http; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Pool; use Happyr\LocoBundle\Exception\HttpException; /** * @author Tobias Nyholm */ class Guzzle5Adapter implements HttpAdapterInterface { /** * {@inheritdoc} */ public function send($method, $url, $data) { $client = new Client([ 'base_url' => HttpAdapterInterface::BASE_URL, ]); try { $response = $client->send($client->createRequest($method, $url, $data)); } catch (ClientException $e) { throw new HttpException('Could not transfer data to Loco', $e->getCode(), $e); } return $response->json(); } /** * @param array $data array($url=>$savePath) */ public function downloadFiles(array $data) { $client = new Client(); $requests = array(); foreach ($data as $url => $path) { $requests[] = $client->createRequest('GET', HttpAdapterInterface::BASE_URL.$url, [ 'save_to' => $path, ]); } // Results is a GuzzleHttp\BatchResults object. $results = Pool::batch($client, $requests); // Retrieve all failures. foreach ($results->getFailures() as $requestException) { //TODO error handling throw new \Exception($requestException->getMessage()); } } }
Make queue_to_send a celery task
import datetime import logging from celery.task import task from django.core.mail.backends.smtp import EmailBackend from django.contrib.auth.models import User from pigeonpost.models import ContentQueue, Outbox logger = logging.getLogger('pigeonpost.tasks') @task def queue_to_send(sender, **kwargs): # Check to see if the object is mailable try: now = datetime.today() countdown = 0 if hasattr(sender, 'email_defer'): countdown = sender.email_defer() scheduled = now + datetime.timedelta(seconds=countdown) # Save it in the model try: post = ContentQueue.get(content_object=sender) except ContentQueue.DoesNotExist: post = ContentQueue(content_object=sender, scheduled=scheduled) post.save() # Create a task to send sendmessages.delay(sender, countdown=countdown) except AttributeError: if not hasattr(sender, 'email_render') or not hasattr(sender, 'email_user'): logger.error('%r requires both email_render and email_user methods.' % sender) else: raise @task def send_messages(content, backend=EmailBackend): users = User.objects.all() for user in users: if content.email_user(user): content.email_render(user) # send the message
import datetime import logging from celery.task import task from django.core.mail.backends.smtp import EmailBackend from django.contrib.auth.models import User from pigeonpost.models import ContentQueue, Outbox logger = logging.getLogger('pigeonpost.tasks') def queue_to_send(sender, **kwargs): # Check to see if the object is mailable try: now = datetime.today() countdown = 0 if hasattr(sender, 'email_defer'): countdown = sender.email_defer() scheduled = now + datetime.timedelta(seconds=countdown) # Save it in the model try: post = ContentQueue.get(content_object=sender) except ContentQueue.DoesNotExist: post = ContentQueue(content_object=sender, scheduled=scheduled) post.save() # Create a task to send sendmessages.delay(sender, countdown=countdown) except AttributeError: if not hasattr(sender, 'email_render') or not hasattr(sender, 'email_user'): logger.error('%r requires both email_render and email_user methods.' % sender) else: raise @task def send_messages(content, backend=EmailBackend): users = User.objects.all() for user in users: if content.email_user(user): content.email_render(user) # send the message
Add more security to the mock system who simulates Eloquent's constructor method.
<?php use Mockery as m; class AcTestCase extends Orchestra\Testbench\TestCase { protected $app; protected $router; public function tearDown() { parent::tearDown(); m::close(); } protected function mock($className) { $mock = m::mock($className); App::bind($className, function($app, $parameters = []) use($mock) { if(is_array($parameters) && is_array($attributes=array_get($parameters, 0, [])) && respond_to($mock, "fill")) { $mock = $this->fillMock($mock, $attributes); } return $mock; }); return $mock; } protected function fillMock($mock, $attributes = []) { $instance = $mock->makePartial(); foreach ($attributes as $key => $value) { $instance->$key = $value; } return $instance; } protected function getPackageProviders() { return [ 'Efficiently\AuthorityController\AuthorityControllerServiceProvider', ]; } protected function getPackageAliases() { return [ 'Authority' => 'Efficiently\AuthorityController\Facades\Authority', 'Params' => 'Efficiently\AuthorityController\Facades\Params', ]; } }
<?php use Mockery as m; class AcTestCase extends Orchestra\Testbench\TestCase { protected $app; protected $router; public function tearDown() { parent::tearDown(); m::close(); } protected function mock($className) { $mock = m::mock($className); App::bind($className, function($app, $parameters = []) use($mock) { if(is_array($parameters) && is_array($attributes=array_get($parameters, 0, []))) { $mock = $this->fillMock($mock, $attributes); } return $mock; }); return $mock; } protected function fillMock($mock, $attributes = []) { $instance = $mock->makePartial(); foreach ($attributes as $key => $value) { $instance->$key = $value; } return $instance; } protected function getPackageProviders() { return [ 'Efficiently\AuthorityController\AuthorityControllerServiceProvider', ]; } protected function getPackageAliases() { return [ 'Authority' => 'Efficiently\AuthorityController\Facades\Authority', 'Params' => 'Efficiently\AuthorityController\Facades\Params', ]; } }
Exit instead of die for ending json return
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); // save whole request to data property $request = (array)json_decode(file_get_contents('php://input')); if (count($request) > 0) { $_POST = $request; } } /** * Universal method to return JSON object in response * * @param boolean * @param mixed array | string * @return string (json) */ protected function _returnAjax($success, $data = []) { $return["success"] = $success; if ($success === false) { // data should be string now $return["error"] = ["message" => $data]; } else { $return["data"] = $data; } print json_encode($return); exit(); } /** * Check if request is sent over proper request method * @param string ("get" | "post" | "put" | "delete") */ protected function _access($allowedMethod) { if ($this->input->method() !== $allowedMethod) { $this->_returnAjax(false, "Access restricted due to wrong request method."); } } /** * Check if client is authenticated */ protected function _checkAuthentication() { $loggedIn = $this->session->userdata("loggedIn"); if (isset($loggedIn) === false) { $this->_returnAjax(false, "Please authenticate first."); } } }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); // save whole request to data property $request = (array)json_decode(file_get_contents('php://input')); if (count($request) > 0) { $_POST = $request; } } /** * Universal method to return JSON object in response * * @param boolean * @param mixed array | string * @return string (json) */ protected function _returnAjax($success, $data = []) { $return["success"] = $success; if ($success === false) { // data should be string now $return["error"] = ["message" => $data]; } else { $return["data"] = $data; } print json_encode($return); die(); } /** * Check if request is sent over proper request method * @param string ("get" | "post" | "put" | "delete") */ protected function _access($allowedMethod) { if ($this->input->method() !== $allowedMethod) { $this->_returnAjax(false, "Access restricted due to wrong request method."); } } /** * Check if client is authenticated */ protected function _checkAuthentication() { $loggedIn = $this->session->userdata("loggedIn"); if (isset($loggedIn) === false) { $this->_returnAjax(false, "Please authenticate first."); } } }
Add ogv and oga support
<?php return array( 'properties' => array( /** * Define the default array of allowed types/extensions * This list should be restrictive enough so that malicious users can't do too much damage. */ 'bucketDefaultAllowedTypes' => array( // Images 'png', 'jpg', 'gif', // Documents & Text 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'rtf', 'txt', 'csv', 'xml', // Video 'mp4', 'mov', 'm4v', 'mpg', 'mpeg', 'avi', 'ogv', // Audio 'mp3', 'wav', 'aiff', 'ogg', 'm4a', 'wma', 'aac', 'oga', // Zips 'zip' ) ), 'services' => array( 'Cdn' => function () { if (class_exists('\App\Cdn\Library\Cdn')) { return new \App\Cdn\Library\Cdn(); } else { return new \Nails\Cdn\Library\Cdn(); } } ) );
<?php return array( 'properties' => array( /** * Define the default array of allowed types/extensions * This list should be restrictive enough so that malicious users can't do too much damage. */ 'bucketDefaultAllowedTypes' => array( // Images 'png', 'jpg', 'gif', // Documents & Text 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'rtf', 'txt', 'csv', 'xml', // Video 'mp4', 'mov', 'm4v', 'mpg', 'mpeg', 'avi', // Audio 'mp3', 'wav', 'aiff', 'ogg', 'm4a', 'wma', 'aac', // Zips 'zip' ) ), 'services' => array( 'Cdn' => function () { if (class_exists('\App\Cdn\Library\Cdn')) { return new \App\Cdn\Library\Cdn(); } else { return new \Nails\Cdn\Library\Cdn(); } } ) );
Remove unneeded condition, update phpdoc, change description.
<?php namespace Symfony\Upgrade\Fixer; use Symfony\CS\Tokenizer\Token; use Symfony\CS\Tokenizer\Tokens; class FormGetnameToGetblockprefixFixer extends FormTypeFixer { /** * @inheritdoc */ public function fix(\SplFileInfo $file, $content) { $tokens = Tokens::fromCode($content); if ($this->isFormType($tokens) && null !== $this->matchGetNameMethod($tokens)) { $this->fixGetNameMethod($tokens); } return $tokens->generateCode(); } private function matchGetNameMethod(Tokens $tokens) { return $tokens->findSequence([ [T_PUBLIC, 'public'], [T_FUNCTION], [T_STRING, 'getName'], '(', ')' ]); } private function fixGetNameMethod(Tokens $tokens) { $matchedTokens = $this->matchGetNameMethod($tokens); $matchedIndexes = array_keys($matchedTokens); $matchedIndex = $matchedIndexes[count($matchedIndexes) - 3]; $matchedTokens[$matchedIndex]->setContent('getBlockPrefix'); } /** * @inheritdoc */ public function getDescription() { return 'The method FormTypeInterface::getName() was deprecated, you should now implement FormTypeInterface::getBlockPrefix() instead.'; } }
<?php namespace Symfony\Upgrade\Fixer; use Symfony\CS\Tokenizer\Token; use Symfony\CS\Tokenizer\Tokens; class FormGetnameToGetblockprefixFixer extends FormTypeFixer { /** * Fixes a file. * * @param \SplFileInfo $file A \SplFileInfo instance * @param string $content The file content * * @return string The fixed file content */ public function fix(\SplFileInfo $file, $content) { $tokens = Tokens::fromCode($content); if ($this->isFormType($tokens) && null !== $this->matchGetNameMethod($tokens)) { $this->fixGetNameMethod($tokens); } return $tokens->generateCode(); } private function matchGetNameMethod(Tokens $tokens) { return $tokens->findSequence([ [T_PUBLIC, 'public'], [T_FUNCTION], [T_STRING, 'getName'], '(', ')' ]); } private function fixGetNameMethod(Tokens $tokens) { $matchedTokens = $this->matchGetNameMethod($tokens); if (null === $matchedTokens) { return; } $matchedIndexes = array_keys($matchedTokens); $matchedIndex = $matchedIndexes[count($matchedIndexes) - 3]; $matchedTokens[$matchedIndex]->setContent('getBlockPrefix'); } /** * Returns the description of the fixer. * * A short one-line description of what the fixer does. * * @return string The description of the fixer */ public function getDescription() { return 'The method FormTypeInterface::getName() was deprecated and will be removed in Symfony 3.0. You should now implement FormTypeInterface::getBlockPrefix() instead.'; } }
Fix add security configurations compiler pass.
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\DependencyInjection\Compiler; use Darvin\ConfigBundle\DependencyInjection\Compiler\AddConfigurationsPass; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Add security configurations compiler pass */ class AddSecurityConfigurationsPass implements CompilerPassInterface { const POOL_ID = 'darvin_admin.security.configuration.pool'; const TAG_SECURITY_CONFIGURATION = 'darvin_admin.security_configuration'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition(self::POOL_ID)) { return; } $configurationIds = $container->findTaggedServiceIds(self::TAG_SECURITY_CONFIGURATION); if (empty($configurationIds)) { return; } $poolDefinition = $container->getDefinition(self::POOL_ID); foreach ($configurationIds as $id => $attr) { $poolDefinition->addMethodCall('addConfiguration', [ new Reference($id), ]); } (new AddConfigurationsPass())->addConfigurations($container, $configurationIds); } }
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\DependencyInjection\Compiler; use Darvin\ConfigBundle\DependencyInjection\Compiler\AddConfigurationsPass; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; /** * Add security configurations compiler pass */ class AddSecurityConfigurationsPass implements CompilerPassInterface { const POOL_ID = 'darvin_admin.security.configuration.pool'; const TAG_SECURITY_CONFIGURATION = 'darvin_admin.security_configuration'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition(self::POOL_ID)) { return; } $configurationIds = $container->findTaggedServiceIds(self::TAG_SECURITY_CONFIGURATION); if (empty($configurationIds)) { return; } $poolDefinition = $container->getDefinition(self::POOL_ID); foreach ($configurationIds as $id => $attr) { $container->getDefinition($id)->addTag(AddConfigurationsPass::TAG_CONFIGURATION); $poolDefinition->addMethodCall('addConfiguration', [ new Reference($id), ]); } } }
Make parameters in EndpointManager optional Change adminurl and internalurl parameters in EndpointManager create() to optional parameters. Change-Id: I490e35b89f7ae7c6cdbced6ba8d3b82d5132c19d Closes-Bug: #1318436
# Copyright 2012 Canonical Ltd. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystoneclient import base class Endpoint(base.Resource): """Represents a Keystone endpoint.""" def __repr__(self): return "<Endpoint %s>" % self._info class EndpointManager(base.ManagerWithFind): """Manager class for manipulating Keystone endpoints.""" resource_class = Endpoint def list(self): """List all available endpoints.""" return self._list('/endpoints', 'endpoints') def create(self, region, service_id, publicurl, adminurl=None, internalurl=None): """Create a new endpoint.""" body = {'endpoint': {'region': region, 'service_id': service_id, 'publicurl': publicurl, 'adminurl': adminurl, 'internalurl': internalurl}} return self._create('/endpoints', body, 'endpoint') def delete(self, id): """Delete an endpoint.""" return self._delete('/endpoints/%s' % id)
# Copyright 2012 Canonical Ltd. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystoneclient import base class Endpoint(base.Resource): """Represents a Keystone endpoint.""" def __repr__(self): return "<Endpoint %s>" % self._info class EndpointManager(base.ManagerWithFind): """Manager class for manipulating Keystone endpoints.""" resource_class = Endpoint def list(self): """List all available endpoints.""" return self._list('/endpoints', 'endpoints') def create(self, region, service_id, publicurl, adminurl, internalurl): """Create a new endpoint.""" body = {'endpoint': {'region': region, 'service_id': service_id, 'publicurl': publicurl, 'adminurl': adminurl, 'internalurl': internalurl}} return self._create('/endpoints', body, 'endpoint') def delete(self, id): """Delete an endpoint.""" return self._delete('/endpoints/%s' % id)
Add optional env vars to prevent additional leakage of personal info
var Pokeio = require('./poke.io') //Set environment variables or replace placeholder text var location = process.env.PGO_LOCATION || 'times squere'; var username = process.env.PGO_USERNAME || 'USERNAME'; var password = process.env.PGO_PASSWORD || 'PASSWORD'; Pokeio.SetLocation(location, function(err, loc) { if (err) throw err; console.log('[i] Current location: ' + location) console.log('[i] lat/long/alt: : ' + loc.latitude + ' ' + loc.longitude + ' ' + loc.altitude) Pokeio.GetAccessToken(username, password, function(err, token) { if (err) throw err; Pokeio.GetApiEndpoint(function(err, api_endpoint) { if (err) throw err; Pokeio.GetProfile(function(err, profile) { if (err) throw err; console.log("[i] Username: " + profile.username) console.log("[i] Poke Storage: " + profile.poke_storage) console.log("[i] Item Storage: " + profile.item_storage) if (profile.currency[0].amount == null) { var poke = 0 } else { var poke = profile.currency[0].amount } console.log("[i] Pokecoin: " + poke) console.log("[i] Stardust: " + profile.currency[1].amount) }) }); }) });
var Pokeio = require('./poke.io') var location = 'Stockflethsvej 39'; var username = 'Arm4x'; var password = 'OHSHITWADDUP'; Pokeio.SetLocation(location, function(err, loc) { if (err) throw err; console.log('[i] Current location: ' + location) console.log('[i] lat/long/alt: : ' + loc.latitude + ' ' + loc.longitude + ' ' + loc.altitude) Pokeio.GetAccessToken(username, password, function(err, token) { if (err) throw err; Pokeio.GetApiEndpoint(function(err, api_endpoint) { if (err) throw err; Pokeio.GetProfile(function(err, profile) { if (err) throw err; console.log("[i] Username: " + profile.username) console.log("[i] Poke Storage: " + profile.poke_storage) console.log("[i] Item Storage: " + profile.item_storage) if (profile.currency[0].amount == null) { var poke = 0 } else { var poke = profile.currency[0].amount } console.log("[i] Pokecoin: " + poke) console.log("[i] Stardust: " + profile.currency[1].amount) }) }); }) });
Add support for looking up all subscriptions on a specific release note.
'use strict'; const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository'); class SubscriptionRepository extends BaseRepository { getSchemaDefinition() { return { subscriberId: { type: String, required: true, index: true, }, releaseNotesId: { type: String, required: true, index: true, }, releaseNotesScope: { type: String, required: true, index: true, }, releaseNotesName: { type: String, required: true, }, email: { type: String, }, }; } /** * Lookup all subscriptions of the given subscriber. * * @param {string} subscriberId * @param {function} callback * @return {SubscriptionRepository} */ findBySubscriberId(subscriberId, callback) { return this.find({ subscriberId, }, callback); } /** * Lookup all subscriptions of a subscriber on a specific release notes. * * @param subscriberId * @param releaseNotesScope * @param releaseNotesName * @param callback * @return {BaseRepository} */ findBySubscriberAndReleaseNotes({ subscriberId, releaseNotesScope, releaseNotesName }, callback) { return this.find({ subscriberId, releaseNotesScope, releaseNotesName, }, callback); } /** * Lookup all subscriptions on the given release notes. * * @param releaseNotesId * @param callback * @return {BaseRepository} */ findByReleaseNotesId(releaseNotesId, callback) { return this.find({ releaseNotesId, }, callback); } } module.exports = SubscriptionRepository;
'use strict'; const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository'); class SubscriptionRepository extends BaseRepository { getSchemaDefinition() { return { subscriberId: { type: String, required: true, index: true, }, releaseNotesId: { type: String, required: true, index: true, }, releaseNotesScope: { type: String, required: true, index: true, }, releaseNotesName: { type: String, required: true, }, email: { type: String, }, }; } /** * Lookup all subscriptions of the given subscriber. * * @param {string} subscriberId * @param {function} callback * @return {SubscriptionRepository} */ findBySubscriberId(subscriberId, callback) { return this.find({ subscriberId, }, callback); } /** * Lookup all subscriptions of a subscriber on a specific release notes. * * @param subscriberId * @param releaseNotesScope * @param releaseNotesName * @param callback * @return {BaseRepository} */ findBySubscriberAndReleaseNotes({ subscriberId, releaseNotesScope, releaseNotesName }, callback) { return this.find({ subscriberId, releaseNotesScope, releaseNotesName, }, callback); } } module.exports = SubscriptionRepository;
Make comment tests compatible with decaffeinate-parser.
import check from './support/check'; describe('comments', () => { it('converts line comments to // form', function() { check(` # foo 1 `, ` // foo 1; `); }); it('converts block comments to /* */', function() { check(` ### HEY ### 1 `, ` /* HEY */ 1; `); }); it('turns leading hashes on block comment lines to leading asterisks', function() { check(` ### # HEY ### 1 `, ` /* * HEY */ 1; `); }); it('converts mixed doc block comments to /** */', function() { check(` ###* @param {Buffer} un-hashed ### (buffer) -> `, ` /** @param {Buffer} un-hashed */ (function(buffer) {}); `); }); it('converts single-line block comments to /* */', () => { check(` ### HEX ### a0 `, ` /* HEX */ a0; `); }); it('preserves shebang lines but changes `coffee` to `node`', () => { check(` #!/usr/bin/env coffee console.log "Hello World!" `, ` #!/usr/bin/env node console.log("Hello World!"); `); }); });
import check from './support/check'; describe('comments', () => { it('converts line comments to // form', function() { check(` # foo 1 `, ` // foo 1; `); }); it('converts block comments to /* */', function() { check(` a( ### HEY ### 1 ) `, ` a( /* HEY */ 1 ); `); }); it('turns leading hashes on block comment lines to leading asterisks', function() { check(` a( ### # HEY ### 1 ) `, ` a( /* * HEY */ 1 ); `); }); it('converts mixed doc block comments to /** */', function() { check(` ###* @param {Buffer} un-hashed ### (buffer) -> `, ` /** @param {Buffer} un-hashed */ (function(buffer) {}); `); }); it('converts single-line block comments to /* */', () => { check(` ### HEX ### a0 `, ` /* HEX */ a0; `); }); it('preserves shebang lines but changes `coffee` to `node`', () => { check(` #!/usr/bin/env coffee console.log "Hello World!" `, ` #!/usr/bin/env node console.log("Hello World!"); `); }); });
Fix image_obj template tag when sending Nonetype image
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from django.conf import settings 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): HALIGN_VALUES = ("left", "center", "right") VALIGN_VALUES = ("top", "middle", "bottom") if image == "" or not image: return "" if settings.THUMBOR_ENABLED: new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign and image.halign in HALIGN_VALUES: new['halign'] = image.halign if image.valign and image.valign in VALIGN_VALUES: 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.archive.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from django.conf import settings 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): HALIGN_VALUES = ("left", "center", "right") VALIGN_VALUES = ("top", "middle", "bottom") if image == "": return "" if settings.THUMBOR_ENABLED: new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign and image.halign in HALIGN_VALUES: new['halign'] = image.halign if image.valign and image.valign in VALIGN_VALUES: 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.archive.url, **kwargs)
Make the shortcut an interface to satisfy SonarQube
package org.mybatis.qbe.mybatis3; import org.mybatis.qbe.Criterion; import org.mybatis.qbe.WhereClause; import org.mybatis.qbe.condition.Condition; import org.mybatis.qbe.field.Field; import org.mybatis.qbe.mybatis3.render.WhereClauseRenderer; /** * This interface combines the operations of building the where clause * and rendering it. It is a shortcut to make the client code easier. * * @author Jeff Butler * */ public interface RenderingShortcut { public static <T> Builder where(Field<T> field, Condition<T> condition, Criterion<?>...criteria) { return new Builder(field, condition, criteria); } public static class Builder extends WhereClause.AbstractBuilder<Builder> { public <T> Builder(Field<T> field, Condition<T> condition, Criterion<?>...criteria) { super(field, condition, criteria); } public RenderedWhereClause render() { return buildRenderer().render(); } public RenderedWhereClause renderWithoutTableAlias() { return buildRenderer().renderWithoutTableAlias(); } private WhereClauseRenderer buildRenderer() { return WhereClauseRenderer.of(super.build()); } @Override public Builder getThis() { return this; } } }
package org.mybatis.qbe.mybatis3; import org.mybatis.qbe.Criterion; import org.mybatis.qbe.WhereClause; import org.mybatis.qbe.condition.Condition; import org.mybatis.qbe.field.Field; import org.mybatis.qbe.mybatis3.render.WhereClauseRenderer; /** * This class combines the operations of building the where clause * and rendering it. It is a shortcut to make the client code easier. * * @author Jeff Butler * */ public class RenderingShortcut { public static <T> Builder where(Field<T> field, Condition<T> condition, Criterion<?>...criteria) { return new Builder(field, condition, criteria); } public static class Builder extends WhereClause.AbstractBuilder<Builder> { public <T> Builder(Field<T> field, Condition<T> condition, Criterion<?>...criteria) { super(field, condition, criteria); } public RenderedWhereClause render() { return buildRenderer().render(); } public RenderedWhereClause renderWithoutTableAlias() { return buildRenderer().renderWithoutTableAlias(); } private WhereClauseRenderer buildRenderer() { return WhereClauseRenderer.of(super.build()); } @Override public Builder getThis() { return this; } } }
:wrench: Remove two more required prop warnings
import React, { Component, PropTypes } from 'react'; import fetchData from '../../actions/fetchData'; import Toast from '../../components/Toast'; import Modals from '../Modals'; import SocketEvents from '../../utils/socketEvents'; import t from '../../utils/types'; import './Main.scss'; import MainNav from '../MainNav'; export default class Main extends Component { static propTypes = { site: t.site, socket: PropTypes.object.isRequired, ui: PropTypes.object.isRequired, user: t.user, location: PropTypes.object.isRequired, children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; static defaultProps = { site: null, user: null, } componentDidMount() { const { dispatch, socket } = this.props; fetchData(); const events = new SocketEvents(socket, dispatch); events.listen(); } render() { const { ui, dispatch, site, user } = this.props; const isFetching = Object.keys(this.props).some(key => this.props[key].isFetching); if (isFetching) return null; return ( <main className="main"> <MainNav siteName={site.siteName} user={user} /> {React.cloneElement(this.props.children, { ...this.props, key: this.props.location.pathname, })} <div className="toasts"> {ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)} </div> <Modals {...this.props} /> </main> ); } }
import React, { Component, PropTypes } from 'react'; import fetchData from '../../actions/fetchData'; import Toast from '../../components/Toast'; import Modals from '../Modals'; import SocketEvents from '../../utils/socketEvents'; import t from '../../utils/types'; import './Main.scss'; import MainNav from '../MainNav'; export default class Main extends Component { static propTypes = { site: t.site.isRequired, socket: PropTypes.object.isRequired, ui: PropTypes.object.isRequired, user: t.user.isRequired, location: PropTypes.object.isRequired, children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; componentDidMount() { const { dispatch, socket } = this.props; fetchData(); const events = new SocketEvents(socket, dispatch); events.listen(); } render() { const { ui, dispatch, site, user } = this.props; const isFetching = Object.keys(this.props).some(key => this.props[key].isFetching); if (isFetching) return null; return ( <main className="main"> <MainNav siteName={site.siteName} user={user} /> {React.cloneElement(this.props.children, { ...this.props, key: this.props.location.pathname, })} <div className="toasts"> {ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)} </div> <Modals {...this.props} /> </main> ); } }
Update function to keep defaultValue and Value in sync in config forms
define(['knockout', 'underscore', 'viewmodels/widget'], function (ko, _, WidgetViewModel) { /** * registers a text-widget component for use in forms * @function external:"ko.components".text-widget * @param {object} params * @param {string} params.value - the value being managed * @param {function} params.config - observable containing config object * @param {string} params.config().label - label to use alongside the text input * @param {string} params.config().placeholder - default text to show in the text input */ return ko.components.register('text-widget', { viewModel: function(params) { params.configKeys = ['placeholder', 'width', 'maxLength', 'defaultValue']; WidgetViewModel.apply(this, [params]); var self = this; var defaultValue = ko.unwrap(this.defaultValue) if (this.tile && this.tile.tileid() == "" && defaultValue != null && defaultValue != "") { this.value(defaultValue); } if (!self.form) { self.value.subscribe(function(val){ if (self.defaultValue() != val) { self.defaultValue(val) }; }); self.defaultValue.subscribe(function(val){ if (self.value() != val) { self.value(val) }; }); }; }, template: { require: 'text!widget-templates/text' } }); });
define(['knockout', 'underscore', 'viewmodels/widget'], function (ko, _, WidgetViewModel) { /** * registers a text-widget component for use in forms * @function external:"ko.components".text-widget * @param {object} params * @param {string} params.value - the value being managed * @param {function} params.config - observable containing config object * @param {string} params.config().label - label to use alongside the text input * @param {string} params.config().placeholder - default text to show in the text input */ return ko.components.register('text-widget', { viewModel: function(params) { params.configKeys = ['placeholder', 'width', 'maxLength', 'defaultValue']; WidgetViewModel.apply(this, [params]); var self = this; var defaultValue = ko.unwrap(this.defaultValue) if (this.tile && this.tile.tileid() == "" && defaultValue != null && defaultValue != "") { this.value(defaultValue); } if (!self.form) { self.value.subscribe(function(){ self.defaultValue(self.value()) }) self.defaultValue.subscribe(function(){ self.value(self.defaultValue()) }) }; }, template: { require: 'text!widget-templates/text' } }); });
Allow routes to be resolved by name property.
(function () { 'use strict'; angular.module('angular-reverse-url', ['ngRoute']) .filter('reverseUrl', ['$route', function ($route) { var regexp = /:([A-Za-z0-9]*)\\*?\\??/g; return _.memoize(function (name, params) { var targetRoute; angular.forEach($route.routes, function (route) { if (route.controller === name || route.name === name) { // we need to check we are passing the parameters in var success = true; var matches = regexp.exec(route.originalPath); // we can't allow empty params if this route is expecting params if ((matches !== null) && (matches.length > 0) && (angular.isUndefined(params) === true)) { success = false; } // TODO: check params exist for each match if (success === true) { targetRoute = route.originalPath; return; } } }); targetRoute = targetRoute.replace(regexp, function (match, pattern) { return params[pattern]; }); return '#' + targetRoute; }, function (name, params) { return name + JSON.stringify(params); }); }]); }());
(function () { 'use strict'; angular.module('angular-reverse-url', ['ngRoute']) .filter('reverseUrl', ['$route', function ($route) { var regexp = /:([A-Za-z0-9]*)\\*?\\??/g; return _.memoize(function (controller, params) { var targetRoute; angular.forEach($route.routes, function (route) { if (route.controller === controller) { // we need to check we are passing the parameters in var success = true; var matches = regexp.exec(route.originalPath); // we can't allow empty params if this route is expecting params if ((matches !== null) && (matches.length > 0) && (angular.isUndefined(params) === true)) { success = false; } // TODO: check params exist for each match if (success === true) { targetRoute = route.originalPath; return; } } }); targetRoute = targetRoute.replace(regexp, function (match, pattern) { return params[pattern]; }); return '#' + targetRoute; }, function (controller, params) { return controller + JSON.stringify(params); }); }]); }());
Use https to load openstreetmap data
(function() { 'use strict'; angular.module('kuulemmaApp').directive('locationMap', function($window) { return { restrict: 'A', scope: { latitude: '@', longitude: '@', polygon: '@' }, link: function(scope, element) { var L = $window.L; var map = L.map(element[0] ,{ zoomControl:false, scrollWheelZoom: false, dragging:false, touchZoom:false, tap:false, doubleClickZoom:false, }); var zoom = 14; var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; var osmAttribution = 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'; var osm = new L.TileLayer(osmUrl, { minzoom: 1, maxzoom: 15, attribution: osmAttribution }); map.setView(new L.LatLng(scope.latitude, scope.longitude), zoom); map.addLayer(osm); if (scope.polygon) { var poly = L.geoJson(JSON.parse(scope.polygon)); poly.addTo(map); // Center and zoom map map.fitBounds(poly.getBounds()); } } }; }); })();
(function() { 'use strict'; angular.module('kuulemmaApp').directive('locationMap', function($window) { return { restrict: 'A', scope: { latitude: '@', longitude: '@', polygon: '@' }, link: function(scope, element) { var L = $window.L; var map = L.map(element[0] ,{ zoomControl:false, scrollWheelZoom: false, dragging:false, touchZoom:false, tap:false, doubleClickZoom:false, }); var zoom = 14; var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; var osmAttribution = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'; var osm = new L.TileLayer(osmUrl, { minzoom: 1, maxzoom: 15, attribution: osmAttribution }); map.setView(new L.LatLng(scope.latitude, scope.longitude), zoom); map.addLayer(osm); if (scope.polygon) { var poly = L.geoJson(JSON.parse(scope.polygon)); poly.addTo(map); // Center and zoom map map.fitBounds(poly.getBounds()); } } }; }); })();
Add examples to the endpoint documentation
'use strict'; module.exports = defineRoute; // Define the route function defineRoute (server, opts) { server.route({ method: 'GET', path: '/', handler: handler, config: { jsonp: 'callback', validate: { query: {}, payload: false } } }); function handler (req) { var host = req.info.host; var exampleId = (opts.things[0] ? opts.things[0].id : 1); req.reply({ endpoints: [ { method: 'GET', endpoint: '/' + opts.plural, description: 'Get all ' + opts.plural, example: 'http://' + host + '/' + opts.plural }, { method: 'GET', endpoint: '/' + opts.plural + '/{id}', description: 'Get a single ' + opts.singular + ' by id', example: 'http://' + host + '/' + opts.plural + '/' + exampleId }, { method: 'GET', endpoint: '/random', description: 'Get a random ' + opts.singular, example: 'http://' + host + '/random' }, { method: 'GET', endpoint: '/bomb?count={n}', description: 'Get multiple random ' + opts.plural, example: 'http://' + host + '/bomb?count=3' } ] }); } }
'use strict'; module.exports = defineRoute; // Define the route function defineRoute (server, opts) { server.route({ method: 'GET', path: '/', handler: handler, config: { jsonp: 'callback', validate: { query: {}, payload: false } } }); function handler (req) { req.reply({ endpoints: [ { method: 'GET', endpoint: '/' + opts.plural, description: 'Get all ' + opts.plural }, { method: 'GET', endpoint: '/' + opts.plural + '/{id}', description: 'Get a single ' + opts.singular + ' by id' }, { method: 'GET', endpoint: '/random', description: 'Get a random ' + opts.singular }, { method: 'GET', endpoint: '/bomb?count={n}', description: 'Get multiple random ' + opts.plural } ] }); } }
Include simple type in bottom descrption
package io.quarkus.annotation.processor.generate_doc; import java.util.List; class DescriptiveDocFormatter implements DocFormatter { private static final String ENTRY_END = "\n\n"; private static final String DETAILS_TITLE = "\n== Details\n"; private static final String DEFAULTS_VALUE_FORMAT = "Defaults to: `%s` +\n"; private static final String BASIC_DESCRIPTION_FORMAT = "\n[[%s]]\n`%s`%s:: %s \n+\nType: `%s` +\n"; /** * Generate configuration keys in descriptive format. * The key defines an anchor that used to link the description with the corresponding * key in the table of summary. */ @Override public String format(List<ConfigItem> configItems) { StringBuilder generatedAsciiDoc = new StringBuilder(DETAILS_TITLE); for (ConfigItem configItem : configItems) { final String basicDescription = String.format(BASIC_DESCRIPTION_FORMAT, getAnchor(configItem), configItem.getKey(), configItem.getConfigPhase().getIllustration(), configItem.getConfigDoc(), configItem.computeTypeSimpleName()); generatedAsciiDoc.append(basicDescription); if (!configItem.getDefaultValue().isEmpty()) { generatedAsciiDoc.append(String.format(DEFAULTS_VALUE_FORMAT, configItem.getDefaultValue())); } generatedAsciiDoc.append(ENTRY_END); } return generatedAsciiDoc.toString(); } }
package io.quarkus.annotation.processor.generate_doc; import java.util.List; class DescriptiveDocFormatter implements DocFormatter { private static final String ENTRY_END = "\n\n"; private static final String DETAILS_TITLE = "\n== Details\n"; private static final String DEFAULTS_VALUE_FORMAT = "Defaults to: `%s` +\n"; private static final String BASIC_DESCRIPTION_FORMAT = "\n[[%s]]\n`%s`%s:: %s \n+\nType: `%s` +\n"; /** * Generate configuration keys in descriptive format. * The key defines an anchor that used to link the description with the corresponding * key in the table of summary. */ @Override public String format(List<ConfigItem> configItems) { StringBuilder generatedAsciiDoc = new StringBuilder(DETAILS_TITLE); for (ConfigItem configItem : configItems) { final String basicDescription = String.format(BASIC_DESCRIPTION_FORMAT, getAnchor(configItem), configItem.getKey(), configItem.getConfigPhase().getIllustration(), configItem.getConfigDoc(), configItem.getType()); generatedAsciiDoc.append(basicDescription); if (!configItem.getDefaultValue().isEmpty()) { generatedAsciiDoc.append(String.format(DEFAULTS_VALUE_FORMAT, configItem.getDefaultValue())); } generatedAsciiDoc.append(ENTRY_END); } return generatedAsciiDoc.toString(); } }
Remove if statement before return
import React from 'react'; const CurrentWeather = ({ weather }) => { const today = weather[0].forecast.simpleforecast.forecastday[0]; const hourly = weather[0].hourly_forecast[0]; return ( <article className='weather-card'> <h2 className='location'> {weather[0].current_observation.display_location.full} </h2> <div className='temp-wrap'> <img className='icon' src={hourly.icon_url} alt='weather icon' /> <h1 className='temperature'> {hourly.temp.english}° </h1> <div className='temp-range'> <p className='high'> {today.high.fahrenheit}° <img className='arrow arrow-high' src='lib/images/arrow-high.svg'/> </p> <p className='low'> {today.low.fahrenheit}° <img className='arrow arrow-low' src='lib/images/arrow-low.svg'/> </p> </div> </div> <p className='date'> {today.date.monthname} </p> <p className='summary'> {weather[0].forecast.txt_forecast.forecastday[0].fcttext} </p> </article> ); }; export default CurrentWeather;
import React from 'react'; // import CurrentTemp from '../CurrentTemp.js'; const CurrentWeather = ({ weather }) => { let today; let hourly; if (weather.length) { today = weather[0].forecast.simpleforecast.forecastday[0]; hourly = weather[0].hourly_forecast[0]; } else { return ( <div> <h3>Please add a location.</h3> </div> ); } return ( <article className='weather-card'> <h2 className='location'> {weather[0].current_observation.display_location.full} </h2> <div className='temp-wrap'> <img className='icon' src={hourly.icon_url} alt='weather icon' /> <h1 className='temperature'> {hourly.temp.english}° </h1> <div className='temp-range'> <p className='high'> {today.high.fahrenheit}° <img className='arrow arrow-high' src='lib/images/arrow-high.svg'/> </p> <p className='low'> {today.low.fahrenheit}° <img className='arrow arrow-low' src='lib/images/arrow-low.svg'/> </p> </div> </div> <p className='date'> {today.date.monthname} </p> <p className='summary'> {weather[0].forecast.txt_forecast.forecastday[0].fcttext} </p> </article> ); }; export default CurrentWeather;
Update UI preferences model (dict)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Resource information of host """ def get_name(): """ Get name of this resource :return: name of this resource :rtype: str """ return 'uipref' def get_schema(): """ Schema structure of this resource :return: schema dictionnary :rtype: dict """ return { 'allow_unknown': True, 'schema': { 'type': { 'type': 'string', 'ui': { 'title': "Preference's type", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'user': { 'type': 'string', 'ui': { 'title': "User name", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'data': { 'type': 'dict', 'ui': { 'title': "Preference's dictionary", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': [] }, } }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Resource information of host """ def get_name(): """ Get name of this resource :return: name of this resource :rtype: str """ return 'uipref' def get_schema(): """ Schema structure of this resource :return: schema dictionnary :rtype: dict """ return { 'allow_unknown': True, 'schema': { 'type': { 'type': 'string', 'ui': { 'title': "Preference's type", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'user': { 'type': 'string', 'ui': { 'title': "User name", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': '' }, 'data': { 'type': 'list', 'ui': { 'title': "User name", 'visible': True, 'orderable': True, 'searchable': True, "format": None }, 'default': [] }, } }
Return boolean instead of if statement.
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Stdlib\Hydrator\Filter; use ReflectionException; use ReflectionMethod; use Zend\Stdlib\Exception\InvalidArgumentException; class NumberOfParameterFilter implements FilterInterface { /** * The number of parameters beeing accepted * @var int */ protected $numberOfParameters = null; /** * @param int $numberOfParameters Number of accepted parameters */ public function __construct($numberOfParameters = 0) { $this->numberOfParameters = (int) $numberOfParameters; } /** * @param string $property the name of the property * @return bool * @throws InvalidArgumentException */ public function filter($property) { try { $reflectionMethod = new ReflectionMethod($property); } catch (ReflectionException $exception) { throw new InvalidArgumentException( "Method $property doesn't exist" ); } return $reflectionMethod->getNumberOfParameters() === $this->numberOfParameters; } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Stdlib\Hydrator\Filter; use ReflectionException; use ReflectionMethod; use Zend\Stdlib\Exception\InvalidArgumentException; class NumberOfParameterFilter implements FilterInterface { /** * The number of parameters beeing accepted * @var int */ protected $numberOfParameters = null; /** * @param int $numberOfParameters Number of accepted parameters */ public function __construct($numberOfParameters = 0) { $this->numberOfParameters = (int) $numberOfParameters; } /** * @param string $property the name of the property * @return bool * @throws InvalidArgumentException */ public function filter($property) { try { $reflectionMethod = new ReflectionMethod($property); } catch (ReflectionException $exception) { throw new InvalidArgumentException( "Method $property doesn't exist" ); } if ($reflectionMethod->getNumberOfParameters() !== $this->numberOfParameters) { return false; } return true; } }
Fix resource category help text. Fixes #15
from django.db import models class Category(models.Model): """A category of resources.""" important = models.BooleanField( default=False, help_text=('Categories marked important will be shown at the top of ' 'the resource list'), verbose_name='important') title = models.CharField( max_length=100, unique=True, verbose_name='title') class Meta: ordering = ('title',) verbose_name_plural = 'categories' def __str__(self): """Return the category's title""" return self.title class Resource(models.Model): """A resource containing various information.""" address = models.TextField( blank=True, verbose_name='address') category = models.ForeignKey( to='Category', verbose_name='resource category') description = models.TextField( blank=True, verbose_name='description') email = models.EmailField( blank=True, verbose_name='email address') phone = models.CharField( blank=True, max_length=50, verbose_name='phone number') title = models.CharField( max_length=100, unique=True, verbose_name='title') url = models.URLField( blank=True, verbose_name='website URL') class Meta: ordering = ('title',) def __str__(self): """Return the resource's title""" return self.title
from django.db import models class Category(models.Model): """A category of resources.""" important = models.BooleanField( default=False, help_text=('categories marked important will be shown at the top of ', 'the resource list'), verbose_name='important') title = models.CharField( max_length=100, unique=True, verbose_name='title') class Meta: ordering = ('title',) verbose_name_plural = 'categories' def __str__(self): """Return the category's title""" return self.title class Resource(models.Model): """A resource containing various information.""" address = models.TextField( blank=True, verbose_name='address') category = models.ForeignKey( to='Category', verbose_name='resource category') description = models.TextField( blank=True, verbose_name='description') email = models.EmailField( blank=True, verbose_name='email address') phone = models.CharField( blank=True, max_length=50, verbose_name='phone number') title = models.CharField( max_length=100, unique=True, verbose_name='title') url = models.URLField( blank=True, verbose_name='website URL') class Meta: ordering = ('title',) def __str__(self): """Return the resource's title""" return self.title
Reset user data when signed out.
import { createUser, updateUser } from '../../../api/db/user' import userMutations from './mutations' import authMutations from '../auth/mutations' import { getCurrentUserObject } from './getters' import { ValueChangedObserver } from '../../../services/observers' import * as paths from '../../../api/db/paths' const observers = { user: new ValueChangedObserver() } const subscriptions = { [userMutations.CHANGED]: ({state}) => { const user = getCurrentUserObject(state) createUser(user.uid, user).then(() => { updateUser(user.uid, user) }).catch(error => { console.log(`Error while creating/updating user on ${userMutations.CHANGED}: ${error.message}`) }) }, [authMutations.USER_CHANGED]: ({dispatch}, mutation) => { const user = mutation.payload[0] if (user) { const path = paths.user(user.uid) observers.user.start(path, data => { if (data) { dispatch(userMutations.CHANGED, data) } else { createUser(user.uid, user) } }) } else { observers.user.stop() dispatch(userMutations.RESET) } } } export default function createPlugin(store) { store.subscribe((mutation, state) => { const type = mutation.type if (type in subscriptions) { subscriptions[type](store, mutation) } }) }
import { createUser, updateUser } from '../../../api/db/user' import userMutations from './mutations' import authMutations from '../auth/mutations' import { getCurrentUserObject } from './getters' import { ValueChangedObserver } from '../../../services/observers' import * as paths from '../../../api/db/paths' const observers = { user: new ValueChangedObserver() } const subscriptions = { [userMutations.CHANGED]: ({state}) => { const user = getCurrentUserObject(state) createUser(user.uid, user).then(() => { updateUser(user.uid, user) }).catch(error => { console.log(`Error while creating/updating user on ${userMutations.CHANGED}: ${error.message}`) }) }, [authMutations.USER_CHANGED]: ({dispatch}, mutation) => { const user = mutation.payload[0] if (user) { const path = paths.user(user.uid) observers.user.start(path, data => { if (data) { dispatch(userMutations.CHANGED, data) } else { createUser(user.uid, user) } }) } else { observers.user.stop() } } } export default function createPlugin(store) { store.subscribe((mutation, state) => { const type = mutation.type if (type in subscriptions) { subscriptions[type](store, mutation) } }) }
tests: Fix the temp file initialization Signed-off-by: Kai Blin <94ddc6985b47aef772521e302594241f46a8f665@biotech.uni-tuebingen.de>
# -*- coding: utf-8 -*- from flask.ext.testing import TestCase import os import tempfile import shutil import websmash class ModelTestCase(TestCase): def create_app(self): self.app = websmash.app self.dl = websmash.dl self.app.config['TESTING'] = True self.app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" websmash.mail.suppress = True return self.app def setUp(self): self.db = websmash.db self.db.create_all() def tearDown(self): self.db.session.remove() self.db.drop_all() class WebsmashTestCase(ModelTestCase): def create_app(self): return super(WebsmashTestCase, self).create_app() def setUp(self): super(WebsmashTestCase, self).setUp() self.tmpdir = tempfile.mkdtemp() (fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa') tmp_file = os.fdopen(fd, 'w+b') tmp_file.write('>test\nATGACCGAGAGTACATAG\n') tmp_file.close() self.tmp_file = open(self.tmp_name, 'r') self.app.config['RESULTS_PATH'] = self.tmpdir def tearDown(self): super(WebsmashTestCase, self).tearDown() self.tmp_file.close() shutil.rmtree(self.tmpdir)
# -*- coding: utf-8 -*- from flask.ext.testing import TestCase import os import tempfile import shutil import websmash class ModelTestCase(TestCase): def create_app(self): self.app = websmash.app self.dl = websmash.dl self.app.config['TESTING'] = True self.app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" websmash.mail.suppress = True return self.app def setUp(self): self.db = websmash.db self.db.create_all() def tearDown(self): self.db.session.remove() self.db.drop_all() class WebsmashTestCase(ModelTestCase): def create_app(self): return super(WebsmashTestCase, self).create_app() def setUp(self): super(WebsmashTestCase, self).setUp() self.tmpdir = tempfile.mkdtemp() (fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa') self.tmp_file = os.fdopen(fd, 'w+b') self.tmp_file.write('>test\nATGACCGAGAGTACATAG\n') self.app.config['RESULTS_PATH'] = self.tmpdir def tearDown(self): super(WebsmashTestCase, self).tearDown() self.tmp_file.close() shutil.rmtree(self.tmpdir)
Add dropdown menu to navbar
import React, { PureComponent, PropTypes } from 'react' import { Link } from 'react-router' import { Menu, Button, Header, Dropdown } from 'semantic-ui-react' class Navbar extends PureComponent { static propTypes = { currentUser: PropTypes.object, signedIn: PropTypes.bool.isRequired, signOut: PropTypes.func.isRequired } render() { const { signedIn, signOut, currentUser } = this.props return( <Menu stackable borderless> <Menu.Item as={Link} to='/'><Header color='grey'>SlimPoll</Header></Menu.Item> { signedIn && <Menu.Item> <Button basic animated='vertical' color='orange' as={Link} to='/create-poll'> <Button.Content visible>Create a poll</Button.Content> <Button.Content hidden>Easy as 1. 2. 3.</Button.Content> </Button> </Menu.Item> } <Menu.Menu position='right'> { signedIn && <Dropdown item closeOnBlur text={ currentUser.name }> <Dropdown.Menu> <Dropdown.Item as={Link} to='/create-poll'>Create a poll</Dropdown.Item> <Dropdown.Item>Your polls</Dropdown.Item> <Dropdown.Item>Polls you voted on</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item onClick={signOut}>Sign out</Dropdown.Item> </Dropdown.Menu> </Dropdown> } { !signedIn && <Menu.Item as={Link} to='sign-in'>Sign in</Menu.Item> } </Menu.Menu> </Menu> ) } } export default Navbar
import React, { PureComponent, PropTypes } from 'react' import { Link } from 'react-router' import { Menu, Button, Header, Icon } from 'semantic-ui-react' class Navbar extends PureComponent { static propTypes = { currentUser: PropTypes.object, signedIn: PropTypes.bool.isRequired, signOut: PropTypes.func.isRequired } render() { const { signedIn, signOut } = this.props return( <Menu stackable borderless> <Menu.Item as={Link} to='/'><Header color='grey'>SlimPoll</Header></Menu.Item> { signedIn && <Menu.Item> <Button basic animated='vertical' color='orange' as={Link} to='/create-poll'> <Button.Content visible>Create a poll</Button.Content> <Button.Content hidden>Easy as 1. 2. 3.</Button.Content> </Button> </Menu.Item> } <Menu.Menu position='right'> { signedIn && <Menu.Item onClick={signOut}>Sign out</Menu.Item> } { !signedIn && <Menu.Item as={Link} to='sign-in'>Sign in</Menu.Item> } </Menu.Menu> </Menu> ) } } export default Navbar
Change xml_encode to permit adding attributes to root node
<?php function xml_encode($mixed, $attrs = [], $domElement = null, $DOMDocument = null) { if (is_null($DOMDocument)) { $DOMDocument = new DOMDocument; $DOMDocument->formatOutput = true; xml_encode($mixed, null, $DOMDocument, $DOMDocument); foreach ($attrs as $name => $value) { $domAttribute = $DOMDocument->createAttribute($name); $domAttribute->value = $value; $DOMDocument->firstChild->appendChild($domAttribute); } return $DOMDocument->saveXML(); } else { if (is_array($mixed)) { foreach ($mixed as $index => $mixedElement) { if (is_int($index)) { if ($index === 0) { $node = $domElement; } else { /** @var $DOMDocument DOMDocument */ /** @var $domElement DOMElement */ $node = $DOMDocument->createElement($domElement->tagName); $domElement->parentNode->appendChild($node); } } else { /** @var $DOMDocument DOMDocument */ $plural = $DOMDocument->createElement($index); /** @var $domElement DOMElement */ $domElement->appendChild($plural); $node = $plural; } xml_encode($mixedElement, null, $node, $DOMDocument); } } else { $mixed = is_bool($mixed) ? ($mixed ? 'true' : 'false') : $mixed; /** @var $DOMDocument DOMDocument */ /** @var $domElement DOMElement */ $domElement->appendChild($DOMDocument->createTextNode($mixed)); } } return null; }
<?php function xml_encode($mixed, $domElement = null, $DOMDocument = null) { if (is_null($DOMDocument)) { $DOMDocument = new DOMDocument; $DOMDocument->formatOutput = true; xml_encode($mixed, $DOMDocument, $DOMDocument); return $DOMDocument->saveXML(); } else { if (is_array($mixed)) { foreach ($mixed as $index => $mixedElement) { if (is_int($index)) { if ($index === 0) { $node = $domElement; } else { /** @var $DOMDocument DOMDocument */ /** @var $domElement DOMElement */ $node = $DOMDocument->createElement($domElement->tagName); $domElement->parentNode->appendChild($node); } } else { /** @var $DOMDocument DOMDocument */ $plural = $DOMDocument->createElement($index); /** @var $domElement DOMElement */ $domElement->appendChild($plural); $node = $plural; } xml_encode($mixedElement, $node, $DOMDocument); } } else { $mixed = is_bool($mixed) ? ($mixed ? 'true' : 'false') : $mixed; /** @var $DOMDocument DOMDocument */ /** @var $domElement DOMElement */ $domElement->appendChild($DOMDocument->createTextNode($mixed)); } } return null; }
Update coverage values to match current
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 98, statements: 96 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) }
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 100, statements: 99 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) }
Fix trl controller fuer directories
<?php class Vpc_Directories_Item_Directory_Trl_Controller extends Vps_Controller_Action_Auto_Vpc_Grid { protected $_buttons = array( 'save', 'reload', ); protected $_editDialog = array( 'width' => 500, 'height' => 400 ); protected $_hasComponentId = false; //component_id nicht speichern protected $_paging = 25; public function preDispatch() { $this->setModel(new Vpc_Directories_Item_Directory_Trl_AdminModel(array( 'proxyModel' => Vpc_Abstract::createChildModel( Vpc_Abstract::getSetting($this->_getParam('class'), 'masterComponentClass') ), 'trlModel' => Vpc_Abstract::createChildModel($this->_getParam('class')), ))); parent::preDispatch(); $url = Vpc_Admin::getInstance($this->_getParam('class'))->getControllerUrl('Form'); $this->_editDialog['controllerUrl'] = $url; } protected function _initColumns() { parent::_initColumns(); $this->_columns->add(new Vps_Grid_Column('id')); } protected function _getSelect() { $ret = parent::_getSelect(); $ret->whereEquals('component_id', $this->_getParam('componentId')); return $ret; } protected function _getRowById($id) { if (!$id) return null; $s = new Vps_Model_Select(); $s->whereEquals($this->_model->getPrimaryKey(), $id); $s->whereEquals('component_id', $this->_getParam('componentId')); return $this->_model->getRow($s); } }
<?php class Vpc_Directories_Item_Directory_Trl_Controller extends Vps_Controller_Action_Auto_Vpc_Grid { protected $_buttons = array( 'save', 'reload', ); protected $_editDialog = array( 'width' => 500, 'height' => 400 ); protected $_paging = 25; public function preDispatch() { $this->setModel(new Vpc_Directories_Item_Directory_Trl_AdminModel(array( 'proxyModel' => Vpc_Abstract::createChildModel( Vpc_Abstract::getSetting($this->_getParam('class'), 'masterComponentClass') ), 'trlModel' => Vpc_Abstract::createChildModel($this->_getParam('class')), ))); parent::preDispatch(); $url = Vpc_Admin::getInstance($this->_getParam('class'))->getControllerUrl('Form'); $this->_editDialog['controllerUrl'] = $url; } protected function _initColumns() { parent::_initColumns(); $this->_columns->add(new Vps_Grid_Column('id')); } protected function _getRowById($id) { if (!$id) return null; $s = new Vps_Model_Select(); $s->whereEquals($this->_model->getPrimaryKey(), $id); $s->whereEquals('component_id', $this->_getParam('componentId')); return $this->_model->getRow($s); } }
Add basic Array.from polyfill for IE11
(function() { var isIE11 = !!window.MSInputMethodContext && !!document.documentMode; if (isIE11) { // IE11 does not provide classList on SVGElements if (! ("classList" in SVGElement.prototype)) { Object.defineProperty(SVGElement.prototype, 'classList', Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'classList')); } // IE11 does not provide children on SVGElements if (! ("children" in SVGElement.prototype)) { Object.defineProperty(SVGElement.prototype, 'children', Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'children')); } if (!Array.from) { // JSONata provides an Array.from polyfill that doesn't handle iterables. // So in IE11 we expect Array.from to exist already, it just needs some // changes to support iterables. throw new Error("Missing Array.from base polyfill"); } Array.from = function() { if (arguments.length > 1) { throw new Error("Node-RED's IE11 Array.from polyfill doesn't support multiple arguments"); } var arrayLike = arguments[0] if (arrayLike.forEach) { var result = []; arrayLike.forEach(function(i) { result.push(i); }) } else { for (var i=0;i<arrayLike.length;i++) { result.push(arrayList[i]); } } return result; } } })();
(function() { var isIE11 = !!window.MSInputMethodContext && !!document.documentMode; if (isIE11) { // IE11 does not provide classList on SVGElements if (! ("classList" in SVGElement.prototype)) { Object.defineProperty(SVGElement.prototype, 'classList', Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'classList')); } // IE11 does not provide children on SVGElements if (! ("children" in SVGElement.prototype)) { Object.defineProperty(SVGElement.prototype, 'children', Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'children')); } if (!Array.from) { // JSONata provides an Array.from polyfill that doesn't handle iterables. // So in IE11 we expect Array.from to exist already, it just needs some // changes to support iterables. throw new Error("Missing Array.from base polyfill"); } Array._from = Array.from; Array.from = function() { var arrayLike = arguments[0] if (arrayLike.forEach) { var result = []; arrayLike.forEach(function(i) { result.push(i); }) return result; } return Array._from.apply(null,arguments); } } })();
Refactor simple arrow head to use two lines instead of path
package SW9.model_canvas.arrow_heads; import javafx.scene.paint.Color; import javafx.scene.shape.*; public class SimpleArrowHead extends ArrowHead { private static final double TRIANGLE_LENGTH = 20d; private static final double TRIANGLE_WIDTH = 15d; public SimpleArrowHead() { super(); addChildren(initializeLeftArrow(), initializeRightArrow()); } private Line initializeLeftArrow() { final Line leftArrow = new Line(); leftArrow.startXProperty().bind(xProperty); leftArrow.startYProperty().bind(yProperty); leftArrow.endXProperty().bind(xProperty.subtract(TRIANGLE_WIDTH / 2)); leftArrow.endYProperty().bind(yProperty.subtract(TRIANGLE_LENGTH)); return leftArrow; } private Line initializeRightArrow() { final Line rightArrow = new Line(); rightArrow.startXProperty().bind(xProperty); rightArrow.startYProperty().bind(yProperty); rightArrow.endXProperty().bind(xProperty.add(TRIANGLE_WIDTH / 2)); rightArrow.endYProperty().bind(yProperty.subtract(TRIANGLE_LENGTH)); return rightArrow; } @Override public double getHeadHeight() { return TRIANGLE_LENGTH; } @Override public double getHeadWidth() { return TRIANGLE_WIDTH; } @Override public boolean shouldBindToTip() { return true; } }
package SW9.model_canvas.arrow_heads; import javafx.scene.paint.Color; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; public class SimpleArrowHead extends ArrowHead { private static final double TRIANGLE_LENGTH = 20d; private static final double TRIANGLE_WIDTH = 15d; public SimpleArrowHead() { super(); addChild(initializeTriangle()); } private Path initializeTriangle() { final Path simpleArrow = new Path(); MoveTo start = new MoveTo(); LineTo l1 = new LineTo(); MoveTo l2 = new MoveTo(); LineTo l3 = new LineTo(); start.xProperty().bind(xProperty); start.yProperty().bind(yProperty); l1.xProperty().bind(start.xProperty().subtract(TRIANGLE_WIDTH / 2)); l1.yProperty().bind(start.yProperty().subtract(TRIANGLE_LENGTH)); l2.xProperty().bind(start.xProperty().add(TRIANGLE_WIDTH / 2)); l2.yProperty().bind(start.yProperty().subtract(TRIANGLE_LENGTH)); l3.xProperty().bind(start.xProperty()); l3.yProperty().bind(start.yProperty()); simpleArrow.setStroke(Color.BLACK); simpleArrow.getElements().addAll(start, l1, l2, l3); return simpleArrow; } @Override public double getHeadHeight() { return TRIANGLE_LENGTH; } @Override public double getHeadWidth() { return TRIANGLE_WIDTH; } @Override public boolean shouldBindToTip() { return true; } }
Change the way we create props for item
'use strict'; import React, { Component, PropTypes } from 'react'; // TODO: title and body componenets? // TODO: PropTypes export default class AccordionItem extends Component { getItemProps() { return { 'aria-expanded': this.props.expanded, 'aria-hidden': !this.props.expanded, className: 'react-sanfona-item', // TODO: modifier class role: 'tabpanel' }; } getTitleProps() { return { 'aria-controls': `react-sanfona-item-body-${ this.props.itemId }`, className: 'react-sanfona-item-title', id: `react-safona-item-title-${ this.props.itemId }` }; } getBodyProps() { return { 'aria-labelledby': `react-safona-item-title-${ this.props.itemId }`, className: 'react-sanfona-item-body', id: `react-safona-item-body-${ this.props.itemId }` }; } render() { return ( <div {this.getItemProps()}> <h3 {this.getTitleProps()}> {this.props.title} </h3> <div {this.getBodyProps()}> {this.props.children} </div> </div> ); } } AccordionItem.propTypes = { expanded: React.PropTypes.bool, itemId: React.PropTypes.string.isRequired, title: React.PropTypes.string };
'use strict'; import React, { Component, PropTypes } from 'react'; // TODO: title and body componenets? // TODO: PropTypes export default class AccordionItem extends Component { render() { let itemProps = { 'aria-expanded': this.props.expanded, 'aria-hidden': !this.props.expanded, className: 'react-sanfona-item', // TODO: modifier class role: 'tabpanel' }; let titleProps = { 'aria-controls': `react-sanfona-item-body-${ this.props.itemId }`, className: 'react-sanfona-item-title', id: `react-safona-item-title-${ this.props.itemId }` }; let bodyProps = { 'aria-labelledby': `react-safona-item-title-${ this.props.itemId }`, className: 'react-sanfona-item-body', id: `react-safona-item-body-${ this.props.itemId }` }; return ( <div {...itemProps}> <h3 {...titleProps}> {this.props.title} </h3> <div {...bodyProps}> {this.props.children} </div> </div> ); } } AccordionItem.propTypes = { expanded: React.PropTypes.bool, itemId: React.PropTypes.string.isRequired, title: React.PropTypes.string };
Update dashboard current width when window is resized (eg: when table orientation changes).
/** * Mycockpit Directive */ (function() { 'use strict'; angular .module('dashboard') .directive('dashboard', ['dashboardFactory', function(dashboardFactory) { // Width of the dashboard container var currentWidth; // To detet a change of column var lastNumberColumns; // Usually currentWidth / minWidth where max is numberMaxOfColumn var numberOfColumnPossible; // Width of columns in % to use in ng-style var columnsWidth; // Maximum number of columns var numberMaxOfColumn; // Thread to avoir too much event trigger during resize var timeout; return { restrict: 'E', scope: { 'id': '@', 'width': '@', 'columns': '@', 'columnsMinWidth': '@' }, templateUrl: 'dashboard.directive.html', controller: ['$scope', function(scope) { currentWidth = $( window ).width(); scope.dashboard = dashboardFactory.get(scope.id); scope.dashboard.setOptions({ 'width': scope['width'], 'columns': scope['columns'], 'columnsMinWidth': scope['columnsMinWidth'] }); scope.dashboard.refresh(); // On resize we refresh window.addEventListener('resize', function(event) { if ($( window ).width() !== currentWidth) { // update currentWidth with current window width currentWidth = $( window ).width(); clearTimeout(timeout); timeout = setTimeout(function () { scope.dashboard.refresh(); scope.$apply(); }, 150); } }, true); }] }; }]); })();
/** * Mycockpit Directive */ (function() { 'use strict'; angular .module('dashboard') .directive('dashboard', ['dashboardFactory', function(dashboardFactory) { // Width of the dashboard container var currentWidth; // To detet a change of column var lastNumberColumns; // Usually currentWidth / minWidth where max is numberMaxOfColumn var numberOfColumnPossible; // Width of columns in % to use in ng-style var columnsWidth; // Maximum number of columns var numberMaxOfColumn; // Thread to avoir too much event trigger during resize var timeout; return { restrict: 'E', scope: { 'id': '@', 'width': '@', 'columns': '@', 'columnsMinWidth': '@' }, templateUrl: 'dashboard.directive.html', controller: ['$scope', function(scope) { var screenWidth = $( window ).width(); scope.dashboard = dashboardFactory.get(scope.id); scope.dashboard.setOptions({ 'width': scope['width'], 'columns': scope['columns'], 'columnsMinWidth': scope['columnsMinWidth'] }); scope.dashboard.refresh(); // On resize we refresh window.addEventListener('resize', function(event) { if ($( window ).width() !== screenWidth) { clearTimeout(timeout); timeout = setTimeout(function () { scope.dashboard.refresh(); scope.$apply(); }, 150); } }, true); }] }; }]); })();
Add /users/list to authorized URLs
// Requires var _ = require('underscore'); var express = require('express'); function setup(options, imports, register) { // Import var app = imports.server.app; var workspace = imports.workspace; // Apply middlewares app.use(express.cookieParser()); app.use(express.cookieSession({ key: ['sess', workspace.id].join('.'), secret: workspace.secret, })); // Get User and set it to res object app.use(function getUser(req, res, next) { var uid = req.session.userId; if(uid) { return workspace.getUser(uid) .then(function(user) { // Set user res.user = user; next(); }) .fail(function(err) { res.user = null; next(); }); } return next(); }); // Block queries for unAuthenticated users var AUTHORIZED_PATHS = ['/', '/auth/join', '/users/list']; app.use(function filterAuth(req, res, next) { if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) { return next(); } // Unauthorized return res.send(403, { ok: false, data: {}, error: "Could not run RPC request because user has not authenticated", method: req.path, }); }); // Register register(null, {}); } // Exports module.exports = setup;
// Requires var _ = require('underscore'); var express = require('express'); function setup(options, imports, register) { // Import var app = imports.server.app; var workspace = imports.workspace; // Apply middlewares app.use(express.cookieParser()); app.use(express.cookieSession({ key: ['sess', workspace.id].join('.'), secret: workspace.secret, })); // Get User and set it to res object app.use(function getUser(req, res, next) { var uid = req.session.userId; if(uid) { return workspace.getUser(uid) .then(function(user) { // Set user res.user = user; next(); }) .fail(function(err) { res.user = null; next(); }); } return next(); }); // Block queries for unAuthenticated users var AUTHORIZED_PATHS = ['/', '/auth/join']; app.use(function filterAuth(req, res, next) { if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) { return next(); } // Unauthorized return res.send(403, { ok: false, data: {}, error: "Could not run RPC request because user has not authenticated", method: req.path, }); }); // Register register(null, {}); } // Exports module.exports = setup;
assertIdentifier: Clean up exception message for null identifier
////////////////////////////////////////////////////////////////////////////// // // Copyright 2010, Starting Block Technologies // www.startingblocktech.com // ////////////////////////////////////////////////////////////////////////////// package com.startingblocktech.tcases; import java.util.Collection; import java.util.regex.Pattern; /** * Defines utility methods for constructing test definitions. * * @version $Revision$, $Date$ */ public abstract class DefUtils { /** * Returns true if the given string is a valid identifier. */ public static boolean isIdentifier( String id) { return id != null && identifierRegex_.matcher( id).matches(); } /** * Throws an exception if the given string is not a valid identifier. */ public static void assertIdentifier( String id) throws IllegalArgumentException { if( !isIdentifier( id)) { throw new IllegalArgumentException ( (id==null? "null" : ("\"" + String.valueOf( id) + "\"")) + " is not a valid identifier"); } } /** * Throws an exception if any member of the given set of properties is not a valid identifier. */ public static void assertPropertyIdentifiers( Collection<String> properties) throws IllegalArgumentException { if( properties != null) { try { for( String property : properties) { assertIdentifier( property); } } catch( Exception e) { throw new IllegalArgumentException( "Invalid property set", e); } } } private static final Pattern identifierRegex_ = Pattern.compile( "[\\w\\-]+"); }
////////////////////////////////////////////////////////////////////////////// // // Copyright 2010, Starting Block Technologies // www.startingblocktech.com // ////////////////////////////////////////////////////////////////////////////// package com.startingblocktech.tcases; import java.util.Collection; import java.util.regex.Pattern; /** * Defines utility methods for constructing test definitions. * * @version $Revision$, $Date$ */ public abstract class DefUtils { /** * Returns true if the given string is a valid identifier. */ public static boolean isIdentifier( String id) { return id != null && identifierRegex_.matcher( id).matches(); } /** * Throws an exception if the given string is not a valid identifier. */ public static void assertIdentifier( String id) throws IllegalArgumentException { if( !isIdentifier( id)) { throw new IllegalArgumentException( "\"" + String.valueOf( id) + "\" is not a valid identifier"); } } /** * Throws an exception if any member of the given set of properties is not a valid identifier. */ public static void assertPropertyIdentifiers( Collection<String> properties) throws IllegalArgumentException { if( properties != null) { try { for( String property : properties) { assertIdentifier( property); } } catch( Exception e) { throw new IllegalArgumentException( "Invalid property set", e); } } } private static final Pattern identifierRegex_ = Pattern.compile( "[\\w\\-]+"); }
Make run loop work within the app class
var gl; var App = new Class({ Implements: Options, options: { name: 'webglet-app', width: 800, height: 600, frameRate: 60 }, initialize: function(element, options) { this.setOptions(options); this.element = element; this.createCanvas(); }, createCanvas: function() { this.canvas = new Element('canvas', {'id': this.options.name, 'width': this.options.width, 'height': this.options.height}); try { gl = this.canvas.getContext('experimental-webgl'); gl.viewport(0, 0, this.options.width, this.options.height); } catch (error) { } if (gl) { this.canvas.inject(this.element); // Load other modules here } else { var alertDiv = new Element('div', {'class': 'webglet-alert'}); alertDiv.set('text', 'WebGL not enabled'); alertDiv.inject(this.element); } }, draw: function() { }, run: function() { this.draw.periodical(1000/this.options.frameRate, this); } });
var gl; var App = new Class({ Implements: Options, options: { name: 'webglet-app', width: 800, height: 600, frameRate: 60 }, initialize: function(element, options) { this.setOptions(options); this.element = element; this.createCanvas(); }, createCanvas: function() { this.canvas = new Element('canvas', {'id': this.options.name, 'width': this.options.width, 'height': this.options.height}); try { gl = this.canvas.getContext('experimental-webgl'); gl.viewport(0, 0, this.options.width, this.options.height); } catch (error) { } if (gl) { this.canvas.inject(this.element); // Load other modules here } else { var alertDiv = new Element('div', {'class': 'webglet-alert'}); alertDiv.set('text', 'WebGL not enabled'); alertDiv.inject(this.element); } }, draw: function() { }, run: function() { setInterval('draw()', 1000/this.options.frameRate) } });
Create container on remote platform when launching client and no container has yet been created
package pt.up.fe.aiad.gui; import jade.core.*; import jade.wrapper.StaleProxyException; import javafx.fxml.FXML; import javafx.scene.control.ListView; import pt.up.fe.aiad.scheduler.SchedulerAgent; import pt.up.fe.aiad.utils.FXUtils; public class ClientController { private String _addressIp; private int _port; private String _nickname; private SchedulerAgent _agent; @FXML private ListView<String> _allAgents; @FXML void initialize() { System.out.println("ClientController.init"); } public void initData(String addressIp, int port, String nickname) { System.out.println("ClientController.initData"); _addressIp = addressIp; _port = port; _nickname = nickname; _agent = new SchedulerAgent(SchedulerAgent.Type.ABT); //TODO add type _allAgents.setItems(_agent._allAgents); } public void start() { System.out.println("ClientController.startServer: " + _nickname + " (" + _addressIp + ":" + _port + ")"); if (MainController.container != null) { try { MainController.container.acceptNewAgent(_nickname, _agent).start(); } catch (StaleProxyException e) { FXUtils.showExceptionDialog(e); } } else { ProfileImpl iae = new ProfileImpl(_addressIp, _port, _addressIp + ":" + Integer.toString(_port) + "/JADE", false); MainController.container = jade.core.Runtime.instance().createAgentContainer(iae); try { MainController.container.acceptNewAgent(_nickname, _agent).start(); } catch (StaleProxyException e) { FXUtils.showExceptionDialog(e); } } } }
package pt.up.fe.aiad.gui; import jade.wrapper.StaleProxyException; import javafx.fxml.FXML; import javafx.scene.control.ListView; import pt.up.fe.aiad.scheduler.SchedulerAgent; import pt.up.fe.aiad.utils.FXUtils; public class ClientController { private String _addressIp; private int _port; private String _nickname; private SchedulerAgent _agent; @FXML private ListView<String> _allAgents; @FXML void initialize() { System.out.println("ClientController.init"); } public void initData(String addressIp, int port, String nickname) { System.out.println("ClientController.initData"); _addressIp = addressIp; _port = port; _nickname = nickname; _agent = new SchedulerAgent(SchedulerAgent.Type.ABT); //TODO add type _allAgents.setItems(_agent._allAgents); } public void start() { System.out.println("ClientController.startServer: " + _nickname + " (" + _addressIp + ":" + _port + ")"); if (MainController.container != null) { try { MainController.container.acceptNewAgent(_nickname, _agent).start(); } catch (StaleProxyException e) { FXUtils.showExceptionDialog(e); } } } }
Add 'current-watching' column to overview
<table class="table table-horizontal table-striped"> <thead> <tr> <th>Tube</th> <th>current-jobs-urgent</th> <th>current-jobs-ready</th> <th>current-jobs-reserved</th> <th>current-jobs-delayed</th> <th>current-jobs-buried</th> <th>current-using</th> <th>current-watching</th> <th>total-jobs</th> <th>cmd-delete</th> </tr> </thead> <tbody> @foreach ($tubes as $name => $stats) <tr> <td> <a href="{{ route('beanstalkd.tubes.show', ['tube' => $name]) }}">{{ $name }}</a> </td> <td>{{ $stats['current-jobs-urgent'] }}</td> <td>{{ $stats['current-jobs-ready'] }}</td> <td>{{ $stats['current-jobs-reserved'] }}</td> <td>{{ $stats['current-jobs-delayed'] }}</td> <td>{{ $stats['current-jobs-buried'] }}</td> <td>{{ $stats['current-using'] }}</td> <td>{{ $stats['current-watching'] }}</td> <td>{{ $stats['total-jobs'] }}</td> <td>{{ $stats['cmd-delete'] }}</td> </tr> @endforeach </tbody> </table>
<table class="table table-horizontal table-striped"> <thead> <tr> <th>Tube</th> <th>current-jobs-urgent</th> <th>current-jobs-ready</th> <th>current-jobs-reserved</th> <th>current-jobs-delayed</th> <th>current-jobs-buried</th> <th>current-using</th> <th>total-jobs</th> <th>cmd-delete</th> </tr> </thead> <tbody> @foreach ($tubes as $name => $stats) <tr> <td> <a href="{{ route('beanstalkd.tubes.show', ['tube' => $name]) }}">{{ $name }}</a> </td> <td>{{ $stats['current-jobs-urgent'] }}</td> <td>{{ $stats['current-jobs-ready'] }}</td> <td>{{ $stats['current-jobs-reserved'] }}</td> <td>{{ $stats['current-jobs-delayed'] }}</td> <td>{{ $stats['current-jobs-buried'] }}</td> <td>{{ $stats['current-using'] }}</td> <td>{{ $stats['total-jobs'] }}</td> <td>{{ $stats['cmd-delete'] }}</td> </tr> @endforeach </tbody> </table>
Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.
import os import re from ..assets import build_asset from ..exceptions import FileNotFound from .base import BaseProcessor URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def rewrite_paths(source, func): repl = lambda match: 'url({quote}{path}{quote})'.format( quote=match.group(1), path=func(match.group(2)), ) return URL_RE.sub(repl, source) class HexdigestPathsProcessor(BaseProcessor): url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def __call__(self, asset): self.asset = asset self.environment = self.asset.attributes.environment self.current_dir = self.asset.attributes.dirname self.process() def process(self): if self.environment.fingerprinting: self.asset.processed_source = rewrite_paths( self.asset.processed_source, self.rewrite_path, ) def rewrite_path(self, path): logical_path = os.path.normpath(os.path.join(self.current_dir, path)) try: asset = build_asset(self.environment, logical_path) except FileNotFound: return path self.asset.dependencies.add(asset.absolute_path) relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir)) return relpath.encode('string-escape')
import os import re from ..assets import build_asset from ..exceptions import FileNotFound from .base import BaseProcessor URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def rewrite_paths(source, func): repl = lambda match: 'url({quote}{path}{quote})'.format( quote=match.group(1), path=func(match.group(2)), ) return URL_RE.sub(repl, source) class HexdigestPathsProcessor(BaseProcessor): url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""") def __call__(self, asset): self.asset = asset self.environment = self.asset.attributes.environment self.current_dir = self.asset.attributes.dirname self.process() def process(self): if self.environment.fingerprinting: self.asset.processed_source = rewrite_paths( self.asset.processed_source, self.rewrite_path, ) def rewrite_path(self, path): logical_path = os.path.normpath(os.path.join(self.current_dir, path)) try: asset = build_asset(self.environment, logical_path) except FileNotFound: return path self.asset.dependencies.add(asset.absolute_path) return os.path.relpath(asset.hexdigest_path, self.current_dir)
Use literal plus character as IE6-8 doesn't like HTML entity
define([ 'extensions/views/table/table' ], function (Table) { var FailuresTable = Table.extend({ columns: [ { id: 'description', title: 'Description', sortable: true }, { id: 'count', title: 'Occurrences last week', sortable: true, defaultDescending: true, getValue: function (model) { return this.formatNumericLabel(model.get('count')); } }, { id: 'fraction', title: 'Percentage of total errors', sortable: true, defaultDescending: true, getValue: function (model) { return this.formatPercentage(model.get('fraction')); } }, { id: 'change', title: 'Difference from week before', sortable: true, defaultDescending: true, getValue: function (model) { var change = model.get('change'); if (change == null) { return '-'; } var displayValue = this.formatNumericLabel(Math.abs(change)); if (change > 0) { return '<span class="increase">+' + displayValue + '</span>'; } else if (change < 0) { return '<span class="decrease">&minus;' + displayValue + '</span>'; } else { return '0'; } } } ], defaultSortColumn: 1 }); return FailuresTable; });
define([ 'extensions/views/table/table' ], function (Table) { var FailuresTable = Table.extend({ columns: [ { id: 'description', title: 'Description', sortable: true }, { id: 'count', title: 'Occurrences last week', sortable: true, defaultDescending: true, getValue: function (model) { return this.formatNumericLabel(model.get('count')); } }, { id: 'fraction', title: 'Percentage of total errors', sortable: true, defaultDescending: true, getValue: function (model) { return this.formatPercentage(model.get('fraction')); } }, { id: 'change', title: 'Difference from week before', sortable: true, defaultDescending: true, getValue: function (model) { var change = model.get('change'); if (change == null) { return '-'; } var displayValue = this.formatNumericLabel(Math.abs(change)); if (change > 0) { return '<span class="increase">&plus;' + displayValue + '</span>'; } else if (change < 0) { return '<span class="decrease">&minus;' + displayValue + '</span>'; } else { return '0'; } } } ], defaultSortColumn: 1 }); return FailuresTable; });