text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix circular dependency problem with django apps It looks like translation is importing *all other* django apps in the project when it is used from treemap. This means that it will load apps that depend on treemap when it is not finished import treemap. So while it appears that treemap/otm1_migrator/otm_comments have sane, non-circular dependencies on each other, the translation app is causing the circle. I'm pretty sure this is actually a django pattern. Django enjoys including dynamic apps that walk through installed apps and do magic stuff. To compensate, they provide this alternative, string-based import strategy that dynamic apps adhere to.
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from threadedcomments.models import ThreadedComment from django.contrib.gis.db import models class EnhancedThreadedComment(ThreadedComment): """ This class wraps the ThreadedComment model with moderation specific fields """ # If the comment should be hidden in the default filter view for moderation is_archived = models.BooleanField(default=False) # We could retrieve this through the GenericForeignKey on ThreadedComment, # but it makes things simpler to record instance here. instance = models.ForeignKey('treemap.Instance') def save(self, *args, **kwargs): if hasattr(self.content_object, 'instance'): self.instance = self.content_object.instance super(EnhancedThreadedComment, self).save(*args, **kwargs)
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from threadedcomments.models import ThreadedComment from django.contrib.gis.db import models from treemap.instance import Instance class EnhancedThreadedComment(ThreadedComment): """ This class wraps the ThreadedComment model with moderation specific fields """ # If the comment should be hidden in the default filter view for moderation is_archived = models.BooleanField(default=False) # We could retrieve this through the GenericForeignKey on ThreadedComment, # but it makes things simpler to record instance here. instance = models.ForeignKey(Instance) def save(self, *args, **kwargs): if hasattr(self.content_object, 'instance'): self.instance = self.content_object.instance super(EnhancedThreadedComment, self).save(*args, **kwargs)
Add test to verify it inserts <br> tag on new lines.
import { moduleForComponent, test } from 'ember-qunit'; import Ember from 'ember'; moduleForComponent('markdown-to-html', 'MarkdownToHtmlComponent', { // specify the other units that are required for this test needs: ['component:markdown-to-html'] }); test('it renders', function() { expect(2); // creates the component instance var component = this.subject(); equal(component._state, 'preRender'); // appends the component to the page this.append(); equal(component._state, 'inDOM'); }); test('it produces markdown', function() { expect(2); var component = this.subject(); this.append(); Ember.run(function() { component.set('markdown', '##Hello, [world](#)'); }); var expectedHtml = '<h2 id="helloworld">Hello, <a href="#">world</a></h2>'; equal(component.get('html').toString(), expectedHtml); equal(component.$().html().toString().trim(), expectedHtml); }); test('it inserts <br> tag', function() { expect(1); var component = this.subject(); this.append(); Ember.run(function() { component.set('markdown', 'foo \nbar'); }); var expectedHtml = '<p>foo <br />\nbar</p>'; equal(component.get('html').toString(), expectedHtml); });
import { moduleForComponent, test } from 'ember-qunit'; import Ember from 'ember'; moduleForComponent('markdown-to-html', 'MarkdownToHtmlComponent', { // specify the other units that are required for this test needs: ['component:markdown-to-html'] }); test('it renders', function() { expect(2); // creates the component instance var component = this.subject(); equal(component._state, 'preRender'); // appends the component to the page this.append(); equal(component._state, 'inDOM'); }); test('it produces markdown', function() { expect(2); var component = this.subject(); this.append(); Ember.run(function() { component.set('markdown', '##Hello, [world](#)'); }); var expectedHtml = '<h2 id="helloworld">Hello, <a href="#">world</a></h2>'; equal(component.get('html').toString(), expectedHtml); equal(component.$().html().toString().trim(), expectedHtml); });
Copy user before update (WAl-383)
import template from './auth-init.html'; export const authInit = { template, controller: class AuthInitController { constructor(usersService, $state, ENV, ncUtilsFlash) { // @ngInject this.usersService = usersService; this.$state = $state; this.ncUtilsFlash = ncUtilsFlash, this.user = {}; this.pageTitle = ENV.shortPageTitle; } $onInit() { this.loading = true; this.usersService.getCurrentUser().then(user => { this.user = angular.copy(user); }).finally(() => { this.loading = false; }); } save({ user }) { return this.usersService.update(user).then(response => { this.usersService.currentUser = response.data; this.$state.go('profile.details'); }).catch(response => { this.ncUtilsFlash.error('Unable to save user'); if (response.status === 400) { this.errors = response.data; } }); } } };
import template from './auth-init.html'; export const authInit = { template, controller: class AuthInitController { constructor(usersService, $state, ENV, ncUtilsFlash) { // @ngInject this.usersService = usersService; this.$state = $state; this.ncUtilsFlash = ncUtilsFlash, this.user = {}; this.pageTitle = ENV.shortPageTitle; } $onInit() { this.loading = true; this.usersService.getCurrentUser().then(user => { this.user = user; }).finally(() => { this.loading = false; }); } save({ user }) { return this.usersService.update(user).then(response => { this.usersService.currentUser = response.data; this.$state.go('profile.details'); }).catch(response => { this.ncUtilsFlash.error('Unable to save user'); if (response.status === 400) { this.errors = response.data; } }); } } };
Add include path for voro++
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright Β© 2017 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Command line tool to run simulations.""" from pathlib import Path from sysconfig import get_path import numpy as np from Cython.Build import cythonize from setuptools import find_packages, setup from setuptools.extension import Extension extensions = [ Extension( 'statdyn.analysis.order', ['statdyn/analysis/order.pyx'], language='c++', libraries=['m', 'voro++'], include_dirs=[np.get_include(), Path(get_path('data')) / 'include'], ), Extension( 'statdyn.math_helper', ['statdyn/math_helper.pyx'], libraries=['m'], include_dirs=[np.get_include()], ), ] setup( name='statdyn', use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm', ], packages=find_packages(), ext_modules=cythonize(extensions), include_package_data=True, entry_points=""" [console_scripts] sdrun=statdyn.sdrun.main:sdrun """, )
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright Β© 2017 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Command line tool to run simulations.""" import numpy as np from Cython.Build import cythonize from setuptools import find_packages, setup from setuptools.extension import Extension extensions = [ Extension( 'statdyn.analysis.order', ['statdyn/analysis/order.pyx'], language='c++', libraries=['m', 'voro++'], include_dirs=[np.get_include()], ), Extension( 'statdyn.math_helper', ['statdyn/math_helper.pyx'], libraries=['m'], include_dirs=[np.get_include()], ), ] setup( name='statdyn', use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm', ], packages=find_packages(), ext_modules=cythonize(extensions), include_package_data=True, entry_points=""" [console_scripts] sdrun=statdyn.sdrun.main:sdrun """, )
Fix some leftover issues from renaming browserify-dataset-sync-wrapper
var gulp = require('gulp'); var config = require('../config'); gulp.task('watch', function() { gulp.watch(config.css.watch, ['css']); gulp.watch(config.coffeelint.watch, ['coffeelint']); gulp.watch(config.browserify.app.watch, ['browserify-app']); gulp.watch(config.browserify.iframe.watch, ['browserify-iframe']); gulp.watch(config.browserify.datasetSyncWrapper.watch, ['browserify-dataset-sync-wrapper']); gulp.watch(config.browserify.saver.watch, ['browserify-saver']); gulp.watch(config.browserify.globals.watch, ['browserify-globals']); gulp.watch(config.assets.watch, ['assets']); gulp.watch(config.vendor.watch, ['vendor']); }); gulp.task('build-all', ['coffeelint', 'browserify-app', 'browserify-globals', 'browserify-iframe', 'browserify-dataset-sync-wrapper', 'browserify-saver', 'css', 'assets', 'vendor']); gulp.task('default', ['build-all', 'watch']);
var gulp = require('gulp'); var config = require('../config'); gulp.task('watch', function() { gulp.watch(config.css.watch, ['css']); gulp.watch(config.coffeelint.watch, ['coffeelint']); gulp.watch(config.browserify.app.watch, ['browserify-app']); gulp.watch(config.browserify.iframe.watch, ['browserify-iframe']); gulp.watch(config.browserify.datasetSyncWrapper.watch, ['browserify-wrapper']); gulp.watch(config.browserify.saver.watch, ['browserify-saver']); gulp.watch(config.browserify.globals.watch, ['browserify-globals']); gulp.watch(config.assets.watch, ['assets']); gulp.watch(config.vendor.watch, ['vendor']); }); gulp.task('build-all', ['coffeelint', 'browserify-app', 'browserify-globals', 'browserify-iframe', 'browserify-dataset-sync-wrapper', 'browserify-saver', 'css', 'assets', 'vendor']); gulp.task('default', ['build-all', 'watch']);
Set maximum bounds for both plots to provide a common scale for comparison between the different scenarios.
import os import sys from setuptools import setup, find_packages from tethys_apps.app_installation import custom_develop_command, custom_install_command ### Apps Definition ### app_package = 'canned_gssha' release_package = 'tethysapp-' + app_package app_class = 'canned_gssha.app:CannedGSSHA' app_package_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tethysapp', app_package) ### Python Dependencies ### dependencies = ['django',] setup( name=release_package, version='0.1.0', description='Access GSSHA model results that have been put away for a rainy day.', long_description='', keywords='', author='Nathan Swain, Herman Dolder', author_email='nathan.swain@byu.net', url='tethys.ci-water.org', license='BSD 2-Clause', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=['tethysapp', 'tethysapp.' + app_package], include_package_data=True, zip_safe=False, install_requires=dependencies, cmdclass={ 'install': custom_install_command(app_package, app_package_dir, dependencies), 'develop': custom_develop_command(app_package, app_package_dir, dependencies) } )
import os import sys from setuptools import setup, find_packages from tethys_apps.app_installation import custom_develop_command, custom_install_command ### Apps Definition ### app_package = 'canned_gssha' release_package = 'tethysapp-' + app_package app_class = 'canned_gssha.app:CannedGSSHA' app_package_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tethysapp', app_package) ### Python Dependencies ### dependencies = ['django',] setup( name=release_package, version='0.0.1', description='Access GSSHA model results that have been put away for a rainy day.', long_description='', keywords='', author='Nathan Swain, Herman Dolder', author_email='nathan.swain@byu.net', url='tethys.ci-water.org', license='BSD 2-Clause', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=['tethysapp', 'tethysapp.' + app_package], include_package_data=True, zip_safe=False, install_requires=dependencies, cmdclass={ 'install': custom_install_command(app_package, app_package_dir, dependencies), 'develop': custom_develop_command(app_package, app_package_dir, dependencies) } )
Send SMS to contact API
<?php /** * @package Mautic * @copyright 2014 Mautic, NP. All rights reserved. * @author Mautic * @link http://mautic.org * @license MIT http://opensource.org/licenses/MIT */ namespace Mautic\Api; /** * Smses Context */ class Smses extends Api { /** * {@inheritdoc} */ protected $endpoint = 'smses'; /** * {@inheritdoc} */ protected $listName = 'smses'; /** * {@inheritdoc} */ protected $itemName = 'sms'; /** * {@inheritdoc} */ protected $searchCommands = array( 'ids', 'is:published', 'is:unpublished', 'is:mine', 'is:uncategorized', 'category', 'lang', ); /** * Send sms to a specific contact * * @param int $id * @param int $contactId * * @return array|mixed */ public function sendToContact($id, $contactId, $parameters = array()) { return $this->makeRequest($this->endpoint.'/'.$id.'/contact/'.$contactId.'/send', $parameters, 'POST'); } }
<?php /** * @package Mautic * @copyright 2014 Mautic, NP. All rights reserved. * @author Mautic * @link http://mautic.org * @license MIT http://opensource.org/licenses/MIT */ namespace Mautic\Api; /** * Smses Context */ class Smses extends Api { /** * {@inheritdoc} */ protected $endpoint = 'smses'; /** * {@inheritdoc} */ protected $listName = 'smses'; /** * {@inheritdoc} */ protected $itemName = 'sms'; /** * {@inheritdoc} */ protected $searchCommands = array( 'ids', 'is:published', 'is:unpublished', 'is:mine', 'is:uncategorized', 'category', 'lang', ); }
Replace <Button variant="fab" /> with new <Fab />
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles, Fab } from '@material-ui/core'; const styles = theme => ({ FAButton: { position: 'absolute', top: -28, left: theme.spacing.unit * -6, // Para o botΓ£o ficar por cima das imagens do Card zIndex: theme.zIndex.mobileStepper, }, [theme.breakpoints.down(1000 + theme.spacing.unit * 8)]: { FAButton: { position: 'fixed', top: 'auto', left: 'auto', bottom: 20, right: 20, }, }, }); const FAButton = ({ children, classes, onClick, ...rest }) => ( <Fab onClick={onClick} color="secondary" className={classes.FAButton} {...rest}> {children} </Fab> ); FAButton.propTypes = { children: PropTypes.node.isRequired, }; export default withStyles(styles)(FAButton);
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles, Button } from '@material-ui/core'; const styles = theme => ({ FAButton: { position: 'absolute', top: -28, left: theme.spacing.unit * -6, // Para o botΓ£o ficar por cima das imagens do Card zIndex: theme.zIndex.mobileStepper, }, [theme.breakpoints.down(1000 + theme.spacing.unit * 8)]: { FAButton: { position: 'fixed', top: 'auto', left: 'auto', bottom: 20, right: 20, }, }, }); const FAButton = ({ children, classes, onClick, ...rest }) => ( <Button onClick={onClick} variant="fab" color="secondary" className={classes.FAButton} {...rest}> {children} </Button> ); FAButton.propTypes = { children: PropTypes.node.isRequired, }; export default withStyles(styles)(FAButton);
Fix memory leak due to TcpReaderThread AABB pools never being cleared. If you are on build 740 or later it is recommended to update to the latest build Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>
package me.nallar.patched; import net.minecraft.network.TcpConnection; import net.minecraft.server.ThreadMinecraftServer; import net.minecraft.util.AxisAlignedBB; public abstract class PatchTcpReaderThread extends ThreadMinecraftServer { final TcpConnection tcpConnection; public PatchTcpReaderThread(TcpConnection tcpConnection, String name) { super(null, name); this.tcpConnection = tcpConnection; } @Override public void run() { TcpConnection.field_74471_a.getAndIncrement(); try { while (tcpConnection.isRunning()) { while (true) { if (!tcpConnection.readNetworkPacket()) { AxisAlignedBB.getAABBPool().cleanPool(); try { sleep(2L); } catch (InterruptedException ignored) { } } } } } finally { TcpConnection.field_74471_a.getAndDecrement(); } } }
package me.nallar.patched; import net.minecraft.network.TcpConnection; import net.minecraft.server.ThreadMinecraftServer; public abstract class PatchTcpReaderThread extends ThreadMinecraftServer { final TcpConnection tcpConnection; public PatchTcpReaderThread(TcpConnection tcpConnection, String name) { super(null, name); this.tcpConnection = tcpConnection; } @Override public void run() { TcpConnection.field_74471_a.getAndIncrement(); try { while (tcpConnection.isRunning()) { while (true) { if (!tcpConnection.readNetworkPacket()) { try { sleep(2L); } catch (InterruptedException ignored) { } } } } } finally { TcpConnection.field_74471_a.getAndDecrement(); } } }
Add contactNumber field to doctor
package com.aviras.mrassistant.data.models; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Represent doctor * <p/> * Created by ashish on 8/6/16. */ public class Doctor extends RealmObject { @PrimaryKey private int id; private CharSequence name; private CharSequence contactNumber; private CharSequence address; private CharSequence notes; public int getId() { return id; } public void setId(int id) { this.id = id; } public CharSequence getName() { return name; } public void setName(CharSequence name) { this.name = name; } public CharSequence getContactNumber() { return contactNumber; } public void setContactNumber(CharSequence contactNumber) { this.contactNumber = contactNumber; } public CharSequence getAddress() { return address; } public void setAddress(CharSequence address) { this.address = address; } public CharSequence getNotes() { return notes; } public void setNotes(CharSequence notes) { this.notes = notes; } }
package com.aviras.mrassistant.data.models; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Represent doctor * <p/> * Created by ashish on 8/6/16. */ public class Doctor extends RealmObject{ @PrimaryKey private int id; private CharSequence name; private CharSequence address; private CharSequence notes; public int getId() { return id; } public void setId(int id) { this.id = id; } public CharSequence getName() { return name; } public void setName(CharSequence name) { this.name = name; } public CharSequence getAddress() { return address; } public void setAddress(CharSequence address) { this.address = address; } public CharSequence getNotes() { return notes; } public void setNotes(CharSequence notes) { this.notes = notes; } }
Add comments for different parts of entry and updated server listener to be within sequelize sync callback
import express from 'express' import models from './models'; import bodyParser from 'body-parser'; import users from './routes/users'; import cookieParser from 'cookie-parser'; import cookieSession from 'cookie-session'; import engine from 'ejs-mate'; import sessions from './routes/sessions' import methodOverride from 'method-override' const app = express(); // temp front-end views app.engine('ejs', engine); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(methodOverride('_method')) // Required middlewares app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser('S3CR37')); app.use(cookieSession({ name:'session', keys: ['key1', 'key2'] })) //setting port app.set('port', process.env.PORT || 3000); app.locals.userId = null //index page app.get('/', (req, res) => { res.render('index', {userId: req.session.userId}) }); //other routes app.use('/users', users()) app.use('/sessions', sessions()) //sync model and listen to server after promise for sync resolves models.sequelize.sync().then(() => { app.listen(app.get('port'), () => { console.log("listening on port " + app.get('port')); }); })
import express from 'express' import models from './models'; import bodyParser from 'body-parser'; import users from './routes/users'; import cookieParser from 'cookie-parser'; import cookieSession from 'cookie-session'; import engine from 'ejs-mate'; import sessions from './routes/sessions' import methodOverride from 'method-override' const app = express(); app.engine('ejs', engine); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(methodOverride('_method')) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser('S3CR37')); app.use(cookieSession({ name:'session', keys: ['key1', 'key2'] })) app.set('port', process.env.PORT || 3000); app.locals.userId = null app.get('/', (req, res) => { res.render('index', {userId: req.session.userId}) }); app.use('/users', users()) app.use('/sessions', sessions()) app.listen(app.get('port'), () => { console.log("listening on port " + app.get('port')); });
[WO-927] Clear file input after key import
'use strict'; var ngModule = angular.module('woDirectives'); ngModule.directive('keyfileInput', function() { return function(scope, elm) { elm.on('change', function(e) { for (var i = 0; i < e.target.files.length; i++) { importKey(e.target.files.item(i)); } elm.val(null); // clear input }); function importKey(file) { var reader = new FileReader(); reader.onload = function(e) { scope.importKey(e.target.result); }; reader.readAsText(file); } }; });
'use strict'; var ngModule = angular.module('woDirectives'); ngModule.directive('keyfileInput', function() { return function(scope, elm) { elm.on('change', function(e) { for (var i = 0; i < e.target.files.length; i++) { importKey(e.target.files.item(i)); } }); function importKey(file) { var reader = new FileReader(); reader.onload = function(e) { scope.importKey(e.target.result); }; reader.readAsText(file); } }; });
Make documentation generator strip copyright header from inline examples
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import codecs import sys import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="."), autoescape=True) def myinclude(filename): with codecs.open(filename, 'r', 'utf-8') as f: lines = f.readlines() # Strip copyright header, if it has one. if lines[1][0:10] == "Copyright ": lines = lines[16:] return "".join(lines) env.globals['myinclude'] = myinclude if len(sys.argv) != 3: sys.stderr.write("Usage: %s <filename.html.jinja> <output.html>\n" % sys.argv[0]) sys.exit(1) html = env.get_template(sys.argv[1]).render() myfile = codecs.open(sys.argv[2], 'w', 'utf-8') myfile.write(html) myfile.close()
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import codecs import sys import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="."), autoescape=True) def myinclude(filename): with codecs.open(filename, 'r', 'utf-8') as f: return f.read() env.globals['myinclude'] = myinclude if len(sys.argv) != 3: sys.stderr.write("Usage: %s <filename.html.jinja> <output.html>\n" % sys.argv[0]) sys.exit(1) html = env.get_template(sys.argv[1]).render() myfile = codecs.open(sys.argv[2], 'w', 'utf-8') myfile.write(html) myfile.close()
Allow flags to pass through object validations.
// Validation for bookmark payloads. 'use strict'; var Hoek = require('hoek'); var Joi = require('joi'); var validators = {}; validators.bookmarkID = Joi.string().guid(); // Bookmark without ID. Used for the update and save payloads. validators.bookmarkWithoutID = { id: validators.bookmarkID.allow(null), url: Joi.string() .required() .uri({ scheme: [ 'http', 'https', ] }), title: Joi.string() .max(200, 'utf-8') .allow(null), description: Joi.string().allow(null), added_at: Joi.date().iso().allow(null), created_at: Joi.date().iso().allow(null), updated_at: Joi.date().iso().allow(null), 'private': Joi.boolean(), to_read: Joi.boolean(), }; // The full bookmark payload, requiring the ID. validators.bookmark = Hoek.clone(validators.bookmarkWithoutID); validators.bookmark.id = validators.bookmarkID.required(); module.exports = validators;
// Validation for bookmark payloads. 'use strict'; var Hoek = require('hoek'); var Joi = require('joi'); var validators = {}; validators.bookmarkID = Joi.string().guid(); // Bookmark without ID. Used for the update and save payloads. validators.bookmarkWithoutID = { id: validators.bookmarkID.allow(null), url: Joi.string() .required() .uri({ scheme: [ 'http', 'https', ] }), title: Joi.string() .max(200, 'utf-8') .allow(null), description: Joi.string().allow(null), added_at: Joi.date().iso().allow(null), created_at: Joi.date().iso().allow(null), updated_at: Joi.date().iso().allow(null), }; // The full bookmark payload, requiring the ID. validators.bookmark = Hoek.clone(validators.bookmarkWithoutID); validators.bookmark.id = validators.bookmarkID.required(); module.exports = validators;
Use void 0 instead of undefined
'use strict'; // MODULES // var tape = require( 'tape' ); var proxyquire = require( 'proxyquire' ); // VARIABLES // var mpath = './../lib/'; // TESTS // tape( 'main export is a function', function test( t ) { var homedir; t.ok( true, __filename ); homedir = require( mpath ); t.strictEqual( typeof homedir, 'function', 'main export is a function' ); t.end(); }); tape( 'the function aliases `os.homedir` if available', function test( t ) { var homedir; var opts; opts = { 'os': { 'homedir': mock } }; homedir = proxyquire( mpath, opts ); t.strictEqual( homedir, mock, 'equals `os.homedir`' ); t.end(); function mock(){} }); tape( 'the function supports older Node versions', function test( t ) { var homedir; var opts; var env; opts = { 'os': { 'homedir': void 0 } }; homedir = proxyquire( mpath, opts ); env = process.env; process.env = { 'HOME': '/Users/beep' }; t.strictEqual( homedir(), '/Users/beep', 'returns home directory' ); process.env = env; t.end(); });
'use strict'; // MODULES // var tape = require( 'tape' ); var proxyquire = require( 'proxyquire' ); // VARIABLES // var mpath = './../lib/'; // TESTS // tape( 'main export is a function', function test( t ) { var homedir; t.ok( true, __filename ); homedir = require( mpath ); t.strictEqual( typeof homedir, 'function', 'main export is a function' ); t.end(); }); tape( 'the function aliases `os.homedir` if available', function test( t ) { var homedir; var opts; opts = { 'os': { 'homedir': mock } }; homedir = proxyquire( mpath, opts ); t.strictEqual( homedir, mock, 'equals `os.homedir`' ); t.end(); function mock(){} }); tape( 'the function supports older Node versions', function test( t ) { var homedir; var opts; var env; opts = { 'os': { 'homedir': undefined } }; homedir = proxyquire( mpath, opts ); env = process.env; process.env = { 'HOME': '/Users/beep' }; t.strictEqual( homedir(), '/Users/beep', 'returns home directory' ); process.env = env; t.end(); });
Make comparison of dates more explicit
from functools import cmp_to_key from django import template from adhocracy4.modules.models import Module from adhocracy4.phases.models import Phase from meinberlin.apps.offlineevents.models import OfflineEvent register = template.Library() @register.assignment_tag def offlineevents_and_modules_sorted(project): modules = list(project.module_set.all()) events = list(OfflineEvent.objects.filter(project=project)) res = modules + events return sorted(res, key=cmp_to_key(_cmp)) def _cmp(x, y): x_date = x.first_phase_start_date if isinstance(x, Module) else x.date if x_date is None: return 1 y_date = y.first_phase_start_date if isinstance(y, Module) else y.date if y_date is None: return -1 if x_date > y_date: return 1 elif x_date == y_date: return 0 else: return -1 @register.filter def is_phase(obj): return isinstance(obj, Phase) @register.filter def is_module(obj): return isinstance(obj, Module) @register.filter def is_offlineevent(obj): return isinstance(obj, OfflineEvent)
from functools import cmp_to_key from django import template from adhocracy4.modules.models import Module from adhocracy4.phases.models import Phase from meinberlin.apps.offlineevents.models import OfflineEvent register = template.Library() @register.assignment_tag def offlineevents_and_modules_sorted(project): modules = list(project.module_set.all()) events = list(OfflineEvent.objects.filter(project=project)) res = modules + events return sorted(res, key=cmp_to_key(_cmp)) def _cmp(x, y): x = x.first_phase_start_date if isinstance(x, Module) else x.date if x is None: return 1 y = y.first_phase_start_date if isinstance(y, Module) else y.date if y is None: return -1 return (x > y) - (y < x) @register.filter def is_phase(obj): return isinstance(obj, Phase) @register.filter def is_module(obj): return isinstance(obj, Module) @register.filter def is_offlineevent(obj): return isinstance(obj, OfflineEvent)
Change temp directory and update tweet message.
import exifread import os class TweetS3Images(object): def __init__(self, twitter, s3_client): self._twitter = twitter self._s3_client = s3_client self._file = None def send_image(self, bucket, image_name, cleanup=False): temp_file = '/tmp/{}'.format(image_name) self._s3_client.download_file(bucket, image_name, temp_file) self._file = open(temp_file, 'rb') status = 'New image {} brought to you by lambda-tweet'.format(image_name) tags = exifread.process_file(self._file) self._twitter.update_with_media(filename=image_name, status=status, file=self._file) if cleanup: self.cleanup(temp_file) def get_file(self): return self._file def cleanup(self, file): os.remove(file)
import exifread import os class TweetS3Images(object): def __init__(self, twitter, s3_client): self._twitter = twitter self._s3_client = s3_client self._file = None def send_image(self, bucket, image_name, cleanup=False): temp_file = './{}'.format(image_name) self._s3_client.download_file(bucket, image_name, temp_file) self._file = open(temp_file, 'rb') status = 'New image {}'.format(image_name) tags = exifread.process_file(self._file) self._twitter.update_with_media(filename=image_name, status=status, file=self._file) if cleanup: self.cleanup(temp_file) def get_file(self): return self._file def cleanup(self, file): os.remove(file)
Update pagination test to work with Laravel 5.5
<?php namespace GeneaLabs\LaravelModelCaching\Tests\Browser; use GeneaLabs\LaravelModelCaching\Tests\FeatureTestCase; use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Book; class PaginationTest extends FeatureTestCase { public function testPaginationProvidesDifferentLinksOnDifferentPages() { $page1ActiveLink = starts_with(app()->version(), "5.5") ? '<li class="active"><span>1</span></li>' : '<li class="page-item active"><span class="page-link">1</span></li>'; $page2ActiveLink = starts_with(app()->version(), "5.5") ? '<li class="active"><span>2</span></li>' : '<li class="page-item active"><span class="page-link">2</span></li>'; $book = (new Book) ->take(11) ->get() ->last(); $page1 = $this->visit("pagination-test"); $page1->see($page1ActiveLink); $page2 = $page1->click("2"); $page2->see($page2ActiveLink); $page2->see($book->title); } }
<?php namespace GeneaLabs\LaravelModelCaching\Tests\Browser; use GeneaLabs\LaravelModelCaching\Tests\FeatureTestCase; use GeneaLabs\LaravelModelCaching\Tests\Fixtures\Book; class PaginationTest extends FeatureTestCase { public function testPaginationProvidesDifferentLinksOnDifferentPages() { $book = (new Book) ->take(11) ->get() ->last(); $page1 = $this->visit("pagination-test"); $this->assertTrue(str_contains($page1->response->getContent(), '<li class="page-item active"><span class="page-link">1</span></li>')); $page2 = $page1->click("2"); $this->assertTrue(str_contains($page2->response->getContent(), '<li class="page-item active"><span class="page-link">2</span></li>')); $page2->see($book->title); } }
Update dsub version to 0.2.4. PiperOrigin-RevId: 225047437
# Copyright 2017 Google Inc. 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. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.2.4'
# Copyright 2017 Google Inc. 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. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.2.4.dev0'
Add test for categorical colors staying around after subsetting
import numpy as np import pandas as pd from anndata import AnnData def test_uns_color_subset(): # Tests for https://github.com/theislab/anndata/issues/257 obs = pd.DataFrame(index=[f"cell{i}" for i in range(5)]) obs["cat1"] = pd.Series(list("aabcd"), index=obs.index, dtype="category") obs["cat2"] = pd.Series(list("aabbb"), index=obs.index, dtype="category") uns = dict( cat1_colors=["red", "green", "blue"], cat2_colors=["red", "green", "blue"], ) adata = AnnData(np.ones((5, 5)), obs=obs, uns=uns) # If number of categories does not match number of colors, # they should be reset v = adata[:, [0, 1]] assert "cat1_colors" not in v.uns assert "cat2_colors" not in v.uns # Otherwise the colors should still match after reseting cat1_colors = ["red", "green", "blue", "yellow"] adata.uns["cat1_colors"] = cat1_colors.copy() v = adata[[0, 1], :] assert len(v.uns["cat1_colors"]) == 1 assert v.uns["cat1_colors"][0] == "red" # But original object should not change assert list(adata.uns["cat1_colors"]) == cat1_colors
import numpy as np import pandas as pd from anndata import AnnData def test_uns_color_subset(): # Tests for https://github.com/theislab/anndata/issues/257 obs = pd.DataFrame(index=[f"cell{i}" for i in range(5)]) obs["cat1"] = pd.Series(list("aabcd"), index=obs.index, dtype="category") obs["cat2"] = pd.Series(list("aabbb"), index=obs.index, dtype="category") uns = dict( cat1_colors=["red", "green", "blue"], cat2_colors=["red", "green", "blue"], ) adata = AnnData(np.ones((5, 5)), obs=obs, uns=uns) # If number of categories does not match number of colors, # they should be reset v = adata[:, [0, 1]] assert "cat1_colors" not in v.uns assert "cat2_colors" not in v.uns # Otherwise the colors should still match after reseting adata.uns["cat1_colors"] = ["red", "green", "blue", "yellow"] v = adata[[0, 1], :] assert len(v.uns["cat1_colors"]) == 1 assert v.uns["cat1_colors"][0] == "red"
Use binary mode to open "wave" files.
from test_support import TestFailed import os, tempfile import wave def check(t, msg=None): if not t: raise TestFailed, msg nchannels = 2 sampwidth = 2 framerate = 8000 nframes = 100 testfile = tempfile.mktemp() f = wave.open(testfile, 'wb') f.setnchannels(nchannels) f.setsampwidth(sampwidth) f.setframerate(framerate) f.setnframes(nframes) output = '\0' * nframes * nchannels * sampwidth f.writeframes(output) f.close() f = wave.open(testfile, 'rb') check(nchannels == f.getnchannels(), "nchannels") check(sampwidth == f.getsampwidth(), "sampwidth") check(framerate == f.getframerate(), "framerate") check(nframes == f.getnframes(), "nframes") input = f.readframes(nframes) check(input == output, "data") f.close() os.remove(testfile)
from test_support import TestFailed import os, tempfile import wave def check(t, msg=None): if not t: raise TestFailed, msg nchannels = 2 sampwidth = 2 framerate = 8000 nframes = 100 testfile = tempfile.mktemp() f = wave.open(testfile, 'w') f.setnchannels(nchannels) f.setsampwidth(sampwidth) f.setframerate(framerate) f.setnframes(nframes) output = '\0' * nframes * nchannels * sampwidth f.writeframes(output) f.close() f = wave.open(testfile, 'r') check(nchannels == f.getnchannels(), "nchannels") check(sampwidth == f.getsampwidth(), "sampwidth") check(framerate == f.getframerate(), "framerate") check(nframes == f.getnframes(), "nframes") input = f.readframes(nframes) check(input == output, "data") f.close() os.remove(testfile)
Remove printing to System.out in test
/* * Copyright 2015 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package org.junit.gen5.commons.util; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; public class FindClassesInPackageTest { @Test public void findAllClassesInThisPackage() throws IOException, ClassNotFoundException { List<Class<?>> classes = Arrays.asList(ReflectionUtils.findAllClassesInPackage("org.junit.gen5.commons")); Assert.assertTrue("Should be at least 20 classes", classes.size() >= 20); Assert.assertTrue(classes.contains(NestedClassToBeFound.class)); Assert.assertTrue(classes.contains(MemberClassToBeFound.class)); } class MemberClassToBeFound { } static class NestedClassToBeFound { } }
/* * Copyright 2015 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package org.junit.gen5.commons.util; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; public class FindClassesInPackageTest { @Test public void findAllClassesInThisPackage() throws IOException, ClassNotFoundException { List<Class<?>> classes = Arrays.asList(ReflectionUtils.findAllClassesInPackage("org.junit.gen5.commons")); System.out.println("Number of classes found: " + classes.size()); for (Class<?> clazz : classes) { System.out.println(clazz.getName()); } Assert.assertTrue("Should be at least 20 classes", classes.size() >= 20); Assert.assertTrue(classes.contains(NestedClassToBeFound.class)); Assert.assertTrue(classes.contains(MemberClassToBeFound.class)); } class MemberClassToBeFound { } static class NestedClassToBeFound { } }
Write the helper functions prepend and call it inside arrayToList
// Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element. function arrayToList(array) { const arrayLength = array.length; let list = null; for (let i = array.length - 1; i >= 0; i-- ) { list = prepend(array[i], list); } return list; } function listToArray(list) { let array = []; for (let currentNode = list; currentNode; currentNode = currentNode.rest) { array.push(currentNode.value); } return array; } function prepend(element, list) { let newList = { value: element, rest: list }; return newList; } const theArray = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(arrayToList(theArray)); const theList = arrayToList([1, 2, 3, 4, 5, 6, 7, 8]); console.log(listToArray(theList));
// Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element. function arrayToList(array) { const arrayLength = array.length; let list = null; for (let i = array.length - 1; i >= 0; i-- ) { list = { value: array[i], rest: list }; } return list; } const theArray = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(arrayToList(theArray)); function listToArray(list) { let array = []; for (let currentNode = list; currentNode; currentNode = currentNode.rest) { array.push(currentNode.value); } return array; } const theList = arrayToList([1, 2, 3, 4, 5, 6, 7, 8]); console.log(listToArray(theList)); // write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list function prepend(element, list) { let newList; // do some stuff here return newList; }
Copy command uses safe's Get method
package commands import ( "fmt" "os" "github.com/bndw/pick/utils" "github.com/spf13/cobra" ) func init() { RootCmd.AddCommand(&cobra.Command{ Use: "cp [name]", Short: "Copy a credential to the clipboard", Long: `The copy command is used to copy a credential's password to the clipboard. `, Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { fmt.Println("USAGE: copy [name]") os.Exit(1) } os.Exit(Copy(args...)) }, }) } func Copy(args ...string) int { safe, err := loadSafe() if err != nil { return handleError(err) } account, err := safe.Get(args[0]) if err != nil { return handleError(err) } if err := utils.CopyToClipboard(account.Password); err != nil { handleError(err) } return 0 }
package commands import ( "fmt" "os" "github.com/spf13/cobra" ) func init() { RootCmd.AddCommand(&cobra.Command{ Use: "cp [name]", Short: "Copy a credential to the clipboard", Long: `The copy command is used to copy a credential's password to the clipboard. `, Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { fmt.Println("USAGE: copy [name]") os.Exit(1) } os.Exit(Copy(args...)) }, }) } func Copy(args ...string) int { safe, err := loadSafe() if err != nil { return handleError(err) } if err := safe.Copy(args[0]); err != nil { return handleError(err) } return 0 }
Set default site string value
from flask import Flask, render_template, jsonify from lanauth.api import load_api class App(Flask): """Web application. Routes: / /login Route to the main page """ def configure_views(self): """Configures core views""" @self.route('/') @self.route('/login') @self.route("/guest/s/<site>/") def login(site = ""): """Route to login (index) page""" return render_template('login.html') def app_factory(app_name, config, blueprints=None): """Build the webappi. :param str app_name: Name of the Flask application :param config: Site configuration :param list blueprints: List of blueprint tuples to load formatted as: (blueprint class, "end point") """ app = App(app_name) app.config.update(config) app.configure_views() if blueprints is not None: for blueprint, prefix in blueprints: app.register_blueprint(blueprint, url_prefix=prefix) load_api(app) return app
from flask import Flask, render_template, jsonify from lanauth.api import load_api class App(Flask): """Web application. Routes: / /login Route to the main page """ def configure_views(self): """Configures core views""" @self.route('/') @self.route('/login') @self.route("/guest/s/<site>") def login(site): """Route to login (index) page""" return render_template('login.html') def app_factory(app_name, config, blueprints=None): """Build the webappi. :param str app_name: Name of the Flask application :param config: Site configuration :param list blueprints: List of blueprint tuples to load formatted as: (blueprint class, "end point") """ app = App(app_name) app.config.update(config) app.configure_views() if blueprints is not None: for blueprint, prefix in blueprints: app.register_blueprint(blueprint, url_prefix=prefix) load_api(app) return app
Add information (url, download url, ...) for packaging
# coding: utf-8 -*- # # Setup file for geocluster # from setuptools import setup, find_packages import os # Get the description file here = os.path.dirname(os.path.abspath(__file__)) long_description = open(os.path.join(here, "DESCRIPTION.rst"), 'r').read() setup( name='geocluster', author=u'RΓ©gis FLORET', author_email='regis@regisblog.fr', version='1.0.1', url='http://www.regisblog.fr/geocluster/', download_url='https://github.com/regisf/geocluster', platforms=['any',], description='GeoCluster is a framework agnostic library to help map clusterization', long_description=long_description, license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Visualization', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Localization' ], keywords='Geocoding map cluster', packages=find_packages('.', exclude=['CModule', 'tests']) )
# coding: utf-8 -*- # # Setup file for geocluster # from setuptools import setup, find_packages import os # Get the description file here = os.path.dirname(os.path.abspath(__file__)) long_description = open(os.path.join(here, "DESCRIPTION.rst"), 'r').read() setup( name='geocluster', author=u'RΓ©gis FLORET', author_email='regis@regisblog.fr', version='1.0.0', description='GeoCluster is a framework agnostic library to help map clusterization', long_description=long_description, license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Visualization', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Localization' ], keywords='Geocoding map cluster', packages=find_packages('.', exclude=['CModule', 'tests']) )
Use SplPriorityQueue to store resolver with priority
<?php /* * This file is part of the Wheels package. * * (c) Maxime Colin <contact@maximecolin.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Wheels; use Wheels\Resolver\ResolverInterface; use Wheels\Exception\NoHandlerFoundException; class CommandBus { private $resolvers; public function __construct() { $this->resolvers = new \SplPriorityQueue(); } public function execute(CommandInterface $command) { return $this->getHandler($command)->handle($command); } private function getHandler(CommandInterface $command) { foreach ($this->resolvers as $resolver) { $handler = $resolver->getHandler($command); if ($handler) { return $handler; } } throw new NoHandlerFoundException('No handler found'); } public function addResolver(ResolverInterface $resolver, $priority = 0) { $this->resolvers->insert($resolver, $priority); } }
<?php /* * This file is part of the Wheels package. * * (c) Maxime Colin <contact@maximecolin.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Wheels; use Wheels\Resolver\ResolverInterface; use Wheels\Exception\NoHandlerFoundException; class CommandBus { private $resolvers = array(); public function execute($command) { return $this->getHandler($command)->handle($command); } private function getHandler(CommandInterface $command) { foreach ($this->resolvers as $resolver) { $handler = $resolver->getHandler($command); if ($handler) { return $handler; } } throw new NoHandlerFoundException('No handler found'); } public function addResolver(ResolverInterface $resolver, $priority = 0) { $this->resolvers[] = $resolver; } }
Use primitive memoization in isGitRoot
'use strict'; var resolve = require('path').resolve , memoize = require('es5-ext/lib/Function/prototype/memoize') , promisify = require('deferred').promisify , lstat = promisify(require('fs').lstat) , watch = require('./watch-path'); var isRoot = memoize.call(function (path) { var watcher, promise, gPath; gPath = resolve(path, '.git'); promise = lstat(gPath)(function (stat) { return stat.isDirectory(); }, false); watch(gPath).on('change', function (event) { if (event.type === 'create') { promise.value = true; } else if (event.type == 'remove') { promise.value = false; } else { return; } promise.emit('change', promise.value, path); }); return promise; }, { primitive: true }); module.exports = function (path) { return isRoot(resolve(String(path))).cb(arguments[1]); };
'use strict'; var resolve = require('path').resolve , memoize = require('es5-ext/lib/Function/prototype/memoize') , promisify = require('deferred').promisify , lstat = promisify(require('fs').lstat) , watch = require('./watch-path'); var isRoot = memoize.call(function (path) { var watcher, promise, gPath; gPath = resolve(path, '.git'); promise = lstat(gPath)(function (stat) { return stat.isDirectory(); }, false); watch(gPath).on('change', function (event) { if (event.type === 'create') { promise.value = true; } else if (event.type == 'remove') { promise.value = false; } else { return; } promise.emit('change', promise.value, path); }); return promise; }); module.exports = function (path) { return isRoot(resolve(String(path))).cb(arguments[1]); };
Change default view to client common layout
<?php /** * This <server-gardu-reporter> project created by : * Name : syafiq * Date / Time : 20 June 2017, 3:07 PM. * Email : syafiq.rezpector@gmail.com * Github : syafiqq */ defined('BASEPATH') OR exit('No direct script access allowed'); class Landing extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function __construct() { parent::__construct(); // Your own constructor code } public function index() { $this->load->helper('url'); $meta = []; $meta['retriever'] = site_url('api/find/'); $this->load->view('landing/index/landing_index_client_common_layout', compact('meta')); } } ?>
<?php /** * This <server-gardu-reporter> project created by : * Name : syafiq * Date / Time : 20 June 2017, 3:07 PM. * Email : syafiq.rezpector@gmail.com * Github : syafiqq */ defined('BASEPATH') OR exit('No direct script access allowed'); class Landing extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function __construct() { parent::__construct(); // Your own constructor code } public function index() { $this->load->helper('url'); $meta = []; $meta['retriever'] = site_url('api/find/'); $this->load->view('landing/index/landing_index_layout', compact('meta')); } } ?>
Add simplejson as a required module https://mediawiki.org/wiki/Special:Code/pywikipedia/11666
# -*- coding: utf-8 -*- """installer script for pywikibot 2.0 framework""" # # (C) Pywikipedia team, 2009-2012 # __version__ = '$Id$' # # Distributed under the terms of the MIT license. # import sys from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages if sys.version_info[0] != 2: raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2") if sys.version_info[1] < 6: raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher") else: depend = ['httplib2>=0.6.0', 'simplejson'] setup(name='Pywikipediabot', version='2.0alpha', description='Python Wikipedia Bot Framework', license='MIT', packages=find_packages(), install_requires=depend, test_suite="tests", ) # automatically launch generate_user_files.py import subprocess python = sys.executable python = python.replace("pythonw.exe", "python.exe") # for Windows ignore = subprocess.call([python, "generate_user_files.py"])
# -*- coding: utf-8 -*- """installer script for pywikibot 2.0 framework""" # # (C) Pywikipedia team, 2009-2012 # __version__ = '$Id$' # # Distributed under the terms of the MIT license. # import sys from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages if sys.version_info[0] != 2: raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2") if sys.version_info[1] < 6: raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher") else: depend = ['httplib2>=0.6.0'] setup(name='Pywikipediabot', version='2.0alpha', description='Python Wikipedia Bot Framework', license='MIT', packages=find_packages(), install_requires=depend, test_suite="tests", ) # automatically launch generate_user_files.py import subprocess python = sys.executable python = python.replace("pythonw.exe", "python.exe") # for Windows ignore = subprocess.call([python, "generate_user_files.py"])
Use env variable for account id in tests.
import os from unittest import TestCase from dnsimple2.client import DNSimple from dnsimple2.resources import ( AccountResource, DomainResource ) from dnsimple2.tests.utils import get_test_domain_name class BaseServiceTestCase(TestCase): @classmethod def setUpClass(cls): access_token = os.getenv('DNSIMPLE_V2_ACCESS_TOKEN') cls.client = DNSimple(access_token) account_id = os.getenv('DNSIMPLE_ACCOUNT_ID') cls.account = AccountResource(id=account_id) cls.domain = cls.client.domains.create( cls.account, DomainResource(name=get_test_domain_name(), account=cls.account) ) cls.invalid_domain = DomainResource( id=1, name='invalid-domain', account=cls.account )
import os from unittest import TestCase from dnsimple2.client import DNSimple from dnsimple2.resources import ( AccountResource, DomainResource ) from dnsimple2.tests.utils import get_test_domain_name class BaseServiceTestCase(TestCase): @classmethod def setUpClass(cls): access_token = os.getenv('DNSIMPLE_V2_ACCESS_TOKEN') cls.client = DNSimple(access_token) cls.account = AccountResource(id=424) cls.domain = cls.client.domains.create( cls.account, DomainResource(name=get_test_domain_name(), account=cls.account) ) cls.invalid_domain = DomainResource( id=1, name='invalid-domain', account=cls.account )
Set zip_safe to False, as it causes problems when creating executables for Windows of apps using it.
import sys import os.path as op from setuptools import setup from distutils.extension import Extension exts = [] if sys.platform == 'darwin': exts.append(Extension( '_send2trash_osx', [op.join('modules', 'send2trash_osx.c')], extra_link_args=['-framework', 'CoreServices'], )) if sys.platform == 'win32': exts.append(Extension( '_send2trash_win', [op.join('modules', 'send2trash_win.c')], extra_link_args = ['shell32.lib'], )) setup( name='Send2Trash', version='1.0.0', author='Hardcoded Software', author_email='hsoft@hardcoded.net', packages=['send2trash'], scripts=[], ext_modules = exts, url='http://hg.hardcoded.net/send2trash/', license='LICENSE', description='Send file to trash natively under Mac OS X, Windows and Linux.', zip_safe=False, )
import sys import os.path as op from setuptools import setup from distutils.extension import Extension exts = [] if sys.platform == 'darwin': exts.append(Extension( '_send2trash_osx', [op.join('modules', 'send2trash_osx.c')], extra_link_args=['-framework', 'CoreServices'], )) if sys.platform == 'win32': exts.append(Extension( '_send2trash_win', [op.join('modules', 'send2trash_win.c')], extra_link_args = ['shell32.lib'], )) setup( name='Send2Trash', version='1.0.0', author='Hardcoded Software', author_email='hsoft@hardcoded.net', packages=['send2trash'], scripts=[], ext_modules = exts, url='http://hg.hardcoded.net/send2trash/', license='LICENSE', description='Send file to trash natively under Mac OS X, Windows and Linux.', )
Fix bug in The Echo Nest API call
from django.conf import settings from purl import Template import requests from .models import SimilarResponse API_URL = Template("http://developer.echonest.com/api/v4/artist/similar" "?api_key=%s&results=100&name={name}" % settings.ECHONEST_API_KEY) def get_similar_from_api(name): url = API_URL.expand({'name': name}) r = requests.get(str(url)) r.raise_for_status() return SimilarResponse.objects.create(name=name, response=r.json()) def get_similar_from_db(name): return SimilarResponse.objects.get(normalized_name=name.upper()) def get_similar(name): try: response = get_similar_from_db(name) except SimilarResponse.DoesNotExist: response = get_similar_from_api(name) return response.artist_names
from django.conf import settings from purl import Template import requests from .models import SimilarResponse API_URL = Template("http://developer.echonest.com/api/v4/artist/similar" "?api_key=%s&results=100&name={name}" % settings.ECHONEST_API_KEY) def get_similar_from_api(name): url = API_URL.expand({'name': name}) r = requests.get(url) r.raise_for_status() return SimilarResponse.objects.create(name=name, response=r.json()) def get_similar_from_db(name): return SimilarResponse.objects.get(normalized_name=name.upper()) def get_similar(name): try: response = get_similar_from_db(name) except SimilarResponse.DoesNotExist: response = get_similar_from_api(name) return response.artist_names
Fix acceptance timeouts on newer Ember versions
import { module, test, skip } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { visit } from '@ember/test-helpers'; import { run } from '@ember/runloop'; import { gte } from 'ember-compatibility-helpers'; import RSVP from 'rsvp'; import DocsController from 'dummy/docs/controller'; let Promise = RSVP.Promise; if (gte("3.4.0")) { Promise = window.Promise; } module('Acceptance | root', function(hooks) { setupApplicationTest(hooks); DocsController.proto().get('flatContents').forEach(page => { if (!page.route) { return; } let testMethod = page.skipTest ? skip : test; testMethod(`visiting ${page.route}`, async function(assert) { assert.expect(0); let url = page.route.replace(/\./g, '/'); visit(url); await new Promise(r => { setTimeout(() => { run.cancelTimers(); r(); }, 200); }); run.cancelTimers(); }); }); });
import { module, test, skip } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { visit } from '@ember/test-helpers'; import { run } from '@ember/runloop'; import RSVP from 'rsvp'; import DocsController from 'dummy/docs/controller'; module('Acceptance | root', function(hooks) { setupApplicationTest(hooks); DocsController.proto().get('flatContents').forEach(page => { if (!page.route) { return; } let testMethod = page.skipTest ? skip : test; testMethod(`visiting ${page.route}`, async function(assert) { assert.expect(0); let url = page.route.replace(/\./g, '/'); visit(url); await new RSVP.Promise(r => { setTimeout(() => { run.cancelTimers(); r(); }, 200); }); run.cancelTimers(); }); }); });
Fix excessive fields in conversion
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. del fields['valid'] # We only store valid weather data, hence. return cls(**fields)
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. return cls(**fields)
Add dependency to jest transform
module.exports = { setupFilesAfterEnv: ['./jest.setup.js'], moduleDirectories: ['<rootDir>/node_modules', 'node_modules'], collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'], transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components|mutex-browser)/)'], transform: { '^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js' }, moduleNameMapper: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': 'react-components/__mocks__/fileMock.js', '\\.(css|scss|less)$': 'react-components/__mocks__/styleMock.js', 'sieve.js': 'react-components/__mocks__/sieve.js' } };
module.exports = { setupFilesAfterEnv: ['./jest.setup.js'], moduleDirectories: ['<rootDir>/node_modules', 'node_modules'], collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'], transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components)/)'], transform: { '^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js' }, moduleNameMapper: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': 'react-components/__mocks__/fileMock.js', '\\.(css|scss|less)$': 'react-components/__mocks__/styleMock.js', 'sieve.js': 'react-components/__mocks__/sieve.js' } };
Use new rating values. It is recommended to always send the new ones, so removed Love and Hate and modified Unrate to be 0 instead of 'unrate'.
package com.jakewharton.trakt.enumerations; import java.util.HashMap; import java.util.Map; import com.jakewharton.trakt.TraktEnumeration; public enum Rating implements TraktEnumeration { WeakSauce("1"), Terrible("2"), Bad("3"), Poor("4"), Meh("5"), Fair("6"), Good("7"), Great("8"), Superb("9"), TotallyNinja("10"), Unrate("0"); private final String value; private Rating(String value) { this.value = value; } @Override public String toString() { return this.value; } private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); static { for (Rating via : Rating.values()) { STRING_MAPPING.put(via.toString().toUpperCase(), via); } } public static Rating fromValue(String value) { return STRING_MAPPING.get(value.toUpperCase()); } }
package com.jakewharton.trakt.enumerations; import java.util.HashMap; import java.util.Map; import com.jakewharton.trakt.TraktEnumeration; public enum Rating implements TraktEnumeration { Love("love"), Hate("hate"), Unrate("unrate"); private final String value; private Rating(String value) { this.value = value; } @Override public String toString() { return this.value; } private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); static { for (Rating via : Rating.values()) { STRING_MAPPING.put(via.toString().toUpperCase(), via); } } public static Rating fromValue(String value) { return STRING_MAPPING.get(value.toUpperCase()); } }
Fix bug in primitive name string put -> insert
package org.spoofax.interpreter.library.ssl; import io.usethesource.capsule.BinaryRelation; import org.spoofax.interpreter.core.IContext; import org.spoofax.interpreter.library.AbstractPrimitive; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoTerm; public class SSL_immutable_relation_insert extends AbstractPrimitive { protected SSL_immutable_relation_insert() { super("SSL_immutable_relation_insert", 0, 2); } @Override public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) { if(!(env.current() instanceof StrategoImmutableRelation)) { return false; } final StrategoImmutableRelation map = (StrategoImmutableRelation) env.current(); final IStrategoTerm key = targs[0]; final IStrategoTerm value = targs[1]; env.setCurrent(new StrategoImmutableRelation( (BinaryRelation.Immutable<IStrategoTerm, IStrategoTerm>) map.backingRelation.__insert(key, value))); return true; } }
package org.spoofax.interpreter.library.ssl; import io.usethesource.capsule.BinaryRelation; import org.spoofax.interpreter.core.IContext; import org.spoofax.interpreter.library.AbstractPrimitive; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoTerm; public class SSL_immutable_relation_insert extends AbstractPrimitive { protected SSL_immutable_relation_insert() { super("SSL_immutable_relation_put", 0, 2); } @Override public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) { if(!(env.current() instanceof StrategoImmutableRelation)) { return false; } final StrategoImmutableRelation map = (StrategoImmutableRelation) env.current(); final IStrategoTerm key = targs[0]; final IStrategoTerm value = targs[1]; env.setCurrent(new StrategoImmutableRelation( (BinaryRelation.Immutable<IStrategoTerm, IStrategoTerm>) map.backingRelation.__insert(key, value))); return true; } }
[console] Set text format to welcome message
<?php /** * @file * Contains \Drupal\Console\EventSubscriber\ShowWelcomeMessageListener. */ namespace Drupal\Console\EventSubscriber; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\Console\Event\ConsoleCommandEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Drupal\Console\Style\DrupalStyle; class ShowWelcomeMessageListener implements EventSubscriberInterface { /** * @param ConsoleCommandEvent $event */ public function showMessage(ConsoleCommandEvent $event) { /** * @var \Drupal\Console\Command\Command $command */ $command = $event->getCommand(); $input = $event->getInput(); $output = $event->getOutput(); $output = new DrupalStyle($input, $output); $application = $command->getApplication(); $translatorHelper = $application->getTranslator(); $welcomeMessageKey = 'commands.'.str_replace(':', '.', $command->getName()).'.welcome'; $welcomeMessage = $translatorHelper->trans($welcomeMessageKey); if ($welcomeMessage != $welcomeMessageKey) { $output->text($welcomeMessage); } } /** * @{@inheritdoc} */ public static function getSubscribedEvents() { return [ConsoleEvents::COMMAND => 'showMessage']; } }
<?php /** * @file * Contains \Drupal\Console\EventSubscriber\ShowWelcomeMessageListener. */ namespace Drupal\Console\EventSubscriber; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\Console\Event\ConsoleCommandEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Drupal\Console\Style\DrupalStyle; class ShowWelcomeMessageListener implements EventSubscriberInterface { /** * @param ConsoleCommandEvent $event */ public function showMessage(ConsoleCommandEvent $event) { /** * @var \Drupal\Console\Command\Command $command */ $command = $event->getCommand(); $input = $event->getInput(); $output = $event->getOutput(); $output = new DrupalStyle($input, $output); $application = $command->getApplication(); $translatorHelper = $application->getTranslator(); $welcomeMessageKey = 'commands.'.str_replace(':', '.', $command->getName()).'.welcome'; $welcomeMessage = $translatorHelper->trans($welcomeMessageKey); if ($welcomeMessage != $welcomeMessageKey) { $output->title($welcomeMessage); } } /** * @{@inheritdoc} */ public static function getSubscribedEvents() { return [ConsoleEvents::COMMAND => 'showMessage']; } }
Add temp dependency on josepy until acme adds it
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup(name='django-autocert', version='0.1.4', packages=['autocert'], include_package_data=True, license='MIT', description="Automatic SSL certificates from Let's Encrypt for Django projects", long_description=README, author='Patrick Farrell', author_email='p@farrell.io', url='https://github.com/farrepa/django-autocert/', keywords='django ssl certificate acme', install_requires=['acme>=0.9.3', 'Django>=1.8', 'urllib3', 'josepy'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], )
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup(name='django-autocert', version='0.1.4', packages=['autocert'], include_package_data=True, license='MIT', description="Automatic SSL certificates from Let's Encrypt for Django projects", long_description=README, author='Patrick Farrell', author_email='p@farrell.io', url='https://github.com/farrepa/django-autocert/', keywords='django ssl certificate acme', install_requires=['acme>=0.9.3', 'Django>=1.8', 'urllib3'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], )
Access first element of the response first We know that there will be at least one because otherwise we take the other branch. We know that there will be only one because nicks are primary keys and we're selecting nicks
var irc = require('irc'); var knex = require('knex')({ client: process.env.CLIENT || 'sqlite3', connection: process.env.DATABASE_URL || { filename: 'dev.sqlite3' } }); console.log(process.env.NC_CHANNEL_LIST.split(',')); var client = new irc.Client(process.env.NC_SERVER || 'chat.freenode.net', process.env.NC_NICK || 'nick-counter-bot', { channels:process.env.NC_CHANNEL_LIST.split(',') } ); client.addListener('message', function (from, to, message) { knex.select('num_messages') .from('messages') .where( { nick:from } ) .then(function(resp) { if (resp.length) { knex('messages').where({nick:from}) .update({nick:from, num_messages: resp[0].num_messages + 1}) .catch(function (error) { console.log(error); }); } else { knex('messages') .insert({nick:from, num_messages: 1}) .catch(function (error) { console.log(error); }); } }); });
var irc = require('irc'); var knex = require('knex')({ client: process.env.CLIENT || 'sqlite3', connection: process.env.DATABASE_URL || { filename: 'dev.sqlite3' } }); console.log(process.env.NC_CHANNEL_LIST.split(',')); var client = new irc.Client(process.env.NC_SERVER || 'chat.freenode.net', process.env.NC_NICK || 'nick-counter-bot', { channels:process.env.NC_CHANNEL_LIST.split(',') } ); client.addListener('message', function (from, to, message) { console.log(from, to, message); knex.select('num_messages') .from('messages') .where( { nick:from } ) .then(function(resp) { console.log(resp); if (resp.length) { knex('messages').where({nick:from}) .update({nick:from, num_messages: resp.num_messages + 1}) .catch(function (error) { console.log(error); }); } else { knex('messages') .insert({nick:from, num_messages: 1}) .catch(function (error) { console.log(error); }); } }); });
Save the session on SaveSession
import sublime import sublime_plugin from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session class SaveSession(sublime_plugin.ApplicationCommand): def run(self): settings.load() sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): return "placeholder" def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) serialize.dump(session_name, session) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data())
import sublime import sublime_plugin from .modules import messages from .modules import settings class SaveSession(sublime_plugin.ApplicationCommand): def run(self): settings.load() sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): return "placeholder" def save_session(self, session_name): pass def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data())
Fix bug with account additions using old Entity API
#!/usr/bin/python from awsom.entity import Entity, Factory from awsom.config import AccountEntity, config class ModelRootFactory(Factory): def __init__(self, entity): super(ModelRootFactory, self).__init__(entity) def populate(self): # Attach all configuration-defined accounts as children of the entity for account in config.get_account_names(): self.entity._add_child(account, AccountEntity(parent=self.entity, **config.get_account(account))) return True class ModelRootEntity(Entity): def __init__(self, name): super(ModelRootEntity, self).__init__(factory=ModelRootFactory(self),name=name) def add_account(self, name, **attrs): self._add_child(name, AccountEntity(parent=self, name=name, **attrs)) # Upon import, the registered accounts should be loaded into the model root, so the # recommended usage would be something like: # from awsom import model as aws # So you can do something like: # aws.add_account('devel_ls', access_key_id=xxxx, secret_access_key=yyyy) # and then: # aws.devel_ls.ec2.instances model = ModelRootEntity(name='model')
#!/usr/bin/python from awsom.entity import Entity, Factory from awsom.config import AccountEntity, config class ModelRootFactory(Factory): def __init__(self, entity): super(ModelRootFactory, self).__init__(entity) def populate(self): # Attach all configuration-defined accounts as children of the entity for account in config.get_account_names(): self.entity._add_child(account, AccountEntity(parent=self.entity, **config.get_account(account))) return True class ModelRootEntity(Entity): def __init__(self, name): super(ModelRootEntity, self).__init__(factory=ModelRootFactory(self),name=name) def add_account(self, name, **attrs): self[name] = AccountEntity(name, **attrs) # Upon import, the registered accounts should be loaded into the model root, so the # recommended usage would be something like: # from awsom import model as aws # So you can do something like: # aws.add_account('devel_ls', access_key_id=xxxx, secret_access_key=yyyy) # and then: # aws.devel_ls.ec2.instances model = ModelRootEntity(name='model')
Fix a bug when you could start an already running task
import _ from 'lodash' import { TASK__PROGRESS, TASK__ERROR, TASK__SUCCESS, TASK__CLEAR, } from '../../actions' const setTaskState = (state, { name, id, ...action }, status, omit) => { const currentTaskGroup = state[name] || {} const currentTask = currentTaskGroup[id] return { ...state, [name]: { ...currentTaskGroup, [id]: { ..._.omit(currentTask, omit), ...action, status, }, }, } } export default (state = {}, { type, ...action }) => { switch (type) { case TASK__PROGRESS: return setTaskState(state, action, 'progress') case TASK__SUCCESS: return setTaskState(state, action, 'success', [ 'payload', 'successActionType', ]) case TASK__ERROR: return setTaskState(state, action, 'error') case TASK__CLEAR: return _.omit(state, `${action.name}.${action.id}`) default: return state } }
import _ from 'lodash' import { TASK__START, TASK__PROGRESS, TASK__ERROR, TASK__SUCCESS, TASK__CLEAR, } from '../../actions' const setTaskState = (state, { name, id, ...action }, status, omit) => { const currentTaskGroup = state[name] || {} const currentTask = currentTaskGroup[id] return { ...state, [name]: { ...currentTaskGroup, [id]: { ..._.omit(currentTask, omit), ...action, status, }, }, } } export default (state = {}, { type, ...action }) => { switch (type) { case TASK__START: return setTaskState(state, action, 'starting') case TASK__PROGRESS: return setTaskState(state, action, 'progress') case TASK__SUCCESS: return setTaskState(state, action, 'success', [ 'payload', 'successActionType', ]) case TASK__ERROR: return setTaskState(state, action, 'error') case TASK__CLEAR: return _.omit(state, `${action.name}.${action.id}`) default: return state } }
Use 4 spaces as indentation
var request=require('request'); var BASE_URL='https://kat.cr'; /** * {String|Object} query string or options f.x {} * avaliable options are any url options that kickass.to accepts * f.x. {field:'seeders', order:'desc', q: 'test',page: 2} * http://kickass.to/json.php?q=test&field=seeders&order=desc&page=2 */ module.exports=function(options, callback){ var url=(options.url || BASE_URL) + '/json.php'; options.url = null; var params = { qs: options, url: url }; request(params, function(err, response, raw){ if(err) { return callback(err, null); } try { var data = JSON.parse(raw); } catch(err) { return callback(err, null); } callback(null, data); }); }
var request=require('request'); var BASE_URL='https://kat.cr'; /** * {String|Object} query string or options f.x {} * avaliable options are any url options that kickass.to accepts * f.x. {field:'seeders', order:'desc', q: 'test',page: 2} * http://kickass.to/json.php?q=test&field=seeders&order=desc&page=2 */ module.exports=function(options, callback){ var url=(options.url || BASE_URL) + '/json.php'; options.url = null; var params = { qs: options, url: url }; request(params, function(err, response, raw){ if(err) { return callback(err, null); } try { var data = JSON.parse(raw); } catch(err) { return callback(err, null); } callback(null, data); }); }
Make sure `WP_CLI_VENDOR_DIR` is always defined. As a last resort, the folder is guessed.
<?php // Can be used by plugins/themes to check if WP-CLI is running or not define( 'WP_CLI', true ); define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) ); define( 'WP_CLI_START_MICROTIME', microtime( true ) ); if ( file_exists( WP_CLI_ROOT . '/vendor/autoload.php' ) ) { define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' ); } elseif ( file_exists( dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php' ) ) { define( 'WP_CLI_VENDOR_DIR', dirname( dirname( WP_CLI_ROOT ) ) ); } else { define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' ); } // Set common headers, to prevent warnings from plugins $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0'; $_SERVER['HTTP_USER_AGENT'] = ''; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; require_once WP_CLI_ROOT . '/php/bootstrap.php'; \WP_CLI\bootstrap();
<?php // Can be used by plugins/themes to check if WP-CLI is running or not define( 'WP_CLI', true ); define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) ); define( 'WP_CLI_START_MICROTIME', microtime( true ) ); if ( file_exists( WP_CLI_ROOT . '/vendor/autoload.php' ) ) { define( 'WP_CLI_VENDOR_DIR' , WP_CLI_ROOT . '/vendor' ); } elseif ( file_exists( dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php' ) ) { define( 'WP_CLI_VENDOR_DIR' , dirname( dirname( WP_CLI_ROOT ) ) ); } // Set common headers, to prevent warnings from plugins $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0'; $_SERVER['HTTP_USER_AGENT'] = ''; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; require_once WP_CLI_ROOT . '/php/bootstrap.php'; \WP_CLI\bootstrap();
Update printed message to point to up to date docs Helps with #552
var fs = require('fs-extra'); var path = require('path'); var printMessage = require('print-message'); try { fs.copySync(path.join(__dirname, 'src', 'theme'), path.join(process.cwd(), 'native-base-theme')); printMessage([ 'NativeBase theme has been copied at ' + path.join(process.cwd(), 'native-base-theme'), 'Here\'s how to theme your app', '', 'import getTheme from \'./native-base-theme/components\';', 'export default class ThemeExample extends Component {', 'render() {', ' return (', ' <StyleProvider style={getTheme()}>', ' <Container>', ' <Content>', ' ...', ' </Content>', ' </Container>', ' </StyleProvider>', ' );', '}', '', 'Head over to the docs (http://nativebase.io/docs/v2.0.0/customize) for detailed information on customization', ], { color: 'yellow', borderColor: 'green', }); } catch(err) { console.log('Error: ' + err); }
var fs = require('fs-extra'); var path = require('path'); var printMessage = require('print-message'); try { fs.copySync(path.join(__dirname, 'src', 'theme'), path.join(process.cwd(), 'native-base-theme')); printMessage([ 'NativeBase theme has been copied at ' + path.join(process.cwd(), 'native-base-theme'), 'Here\'s how to theme your app', '', 'import getTheme from \'./native-base-theme/components\';', 'export default class ThemeExample extends Component {', 'render() {', ' return (', ' <StyleProvider style={getTheme()}>', ' <Container>', ' <Content>', ' ...', ' </Content>', ' </Container>', ' </StyleProvider>', ' );', '}', '', 'Head over to the docs(http://docs.nativebase.io/docs/customize/) for detailed information on customization', ], { color: 'yellow', borderColor: 'green', }); } catch(err) { console.log('Error: ' + err); }
Return promise instead of done It appears that if you return a promise to gulp, gulp waits on the promise and catches the failed promise. By return the promise AND calling done, task completion was getting called twice.
var _ = require('lodash'); var jsonfile = require('jsonfile'); var thenify = require('thenify'); var args = require('yargs') .alias('v', 'version') .argv; var readJson = thenify(jsonfile.readFile); var writeJson = thenify(jsonfile.writeFile); var packageFile = 'package.json'; exports.config = function(gulp) { if (_.isUndefined(gulp)) { gulp = require('gulp'); } gulp.task('version', () => { var versionStr = args.version; return exports.version(versionStr) .then(() => { console.log('Version changed to ' + versionStr); }); }); }; exports.version = (version) => { return readJson(packageFile) .then(package => { package.version = version; return writeJson(packageFile, package, { spaces: 2 }); }); };
var _ = require('lodash'); var jsonfile = require('jsonfile'); var thenify = require('thenify'); var args = require('yargs') .alias('v', 'version') .argv; var readJson = thenify(jsonfile.readFile); var writeJson = thenify(jsonfile.writeFile); var packageFile = 'package.json'; exports.config = function(gulp) { if (_.isUndefined(gulp)) { gulp = require('gulp'); } gulp.task('version', (done) => { var versionStr = args.version; return exports.version(versionStr) .then(() => { console.log('Version changed to ' + versionStr); done(); }) .catch(err => done(err)); }); }; exports.version = (version) => { return readJson(packageFile) .then(package => { package.version = version; return writeJson(packageFile, package, { spaces: 2 }); }); };
Add test for surnames with apostrophes
<?php require_once(dirname(__FILE__) . '/../classes/newuser.php'); class GenerateUsernameTest extends PHPUnit_Framework_TestCase { public function setUp() { $this -> user = new NewUser(); } public function testOneWordEach() { $this -> user -> setName('John', 'Smith'); $uid = $this -> user -> username(); $this -> assertEquals($uid, 'jsmith'); } public function testTwoWordSurname() { $this -> user -> setName('james', 'Van der Beek'); $uid = $this -> user -> username(); $this -> assertEquals($uid, 'jvanderbeek'); } public function testDoubleBarrelled() { $this -> user -> setName('John', 'Smith-Doe'); $uid = $this -> user -> username(); $this -> assertEquals($uid, 'jsmith-doe'); } public function testApostrophes() { $this -> user -> setName('Paddy', 'O'Mally'); $uid = $this -> user -> username(); $this -> assertEquals($uid, 'pomally'); } }
<?php require_once(dirname(__FILE__) . '/../classes/newuser.php'); class GenerateUsernameTest extends PHPUnit_Framework_TestCase { public function setUp() { $this -> user = new NewUser(); } public function testOneWordEach() { $this -> user -> setName('John', 'Smith'); $uid = $this -> user -> username(); $this -> assertEquals($uid, 'jsmith'); } public function testTwoWordSurname() { $this -> user -> setName('james', 'Van der Beek'); $uid = $this -> user -> username(); $this -> assertEquals($uid, 'jvanderbeek'); } public function testDoubleBarrelled() { $this -> user -> setName('John', 'Smith-Doe'); $uid = $this -> user -> username(); $this -> assertEquals($uid, 'jsmith-doe'); } }
Make path variable working for server side
import feedparser import pickle import requests import sys hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites feed = feedparser.parse( hub ) stored = [] path = sys.argv[0] try: stored = pickle.load( open( path + '/.history' , 'r' ) ) except: pass out = open( path + '/urls.txt' , 'a') for item in feed['items']: link = item['links'][0]['href'] _id = link.split('?id=')[1] if _id not in stored: r = requests.head( link ) url = r.headers.get('location') out.write( _id + ',' + url + '\n' ) stored.append( _id ) pickle.dump( stored, open( path + '/.history' , 'w' ) )
import feedparser import pickle import requests hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites feed = feedparser.parse( hub ) stored = [] try: stored = pickle.load( open( '.history' , 'r' ) ) except: pass stored = [] out = open( 'urls.txt' , 'a') for item in feed['items']: link = item['links'][0]['href'] _id = link.split('?id=')[1] if _id not in stored: r = requests.head( link ) url = r.headers.get('location') out.write( _id + ',' + url + '\n' ) stored.append( _id ) pickle.dump( stored, open( '.history' , 'w' ) )
Support for HTTPS in XHR proxy.
// Copyright (c) Microsoft Corporation. All rights reserved. var http = require('http'), https = require('https'), url = require('url'); module.exports.attach = function (app) { app.all('/xhr_proxy', function proxyXHR(request, response) { var requestURL = url.parse(unescape(request.query.rurl)); request.headers.host = requestURL.host; // fixes encoding issue delete request.headers['accept-encoding']; var options = { host: requestURL.host, path: requestURL.path, port: requestURL.port, method: request.method, headers: request.headers }; var proxyCallback = function (proxyReponse) { proxyReponse.pipe(response); }; if (requestURL.protocol === "https:") { https.request(options, proxyCallback).end(); } else { http.request(options, proxyCallback).end(); } }); };
// Copyright (c) Microsoft Corporation. All rights reserved. var http = require('http'), url = require('url'); module.exports.attach = function (app) { app.all('/xhr_proxy', function proxyXHR(request, response) { var requestURL = url.parse(unescape(request.query.rurl)); request.headers.host = requestURL.host; // fixes encoding issue delete request.headers['accept-encoding']; var options = { host: requestURL.host, path: requestURL.path, port: requestURL.port, method: request.method, headers: request.headers }; var proxyCallback = function (proxyReponse) { proxyReponse.pipe(response); }; http.request(options, proxyCallback).end(); }); };
Use category layout if available in the category generator In case a category layout is defined use it over archive and index layouts. Built from f3ac57b2c6cb8ce85da49515309c0f34f8227e40.
var pagination = require('hexo-pagination'); var _ = require('lodash'); hexo.extend.generator.register('category', function(locals){ var config = this.config; var categories = locals.data.categories; if (config.category_generator) { var perPage = config.category_generator.per_page; } else { var perPage = 10; } var paginationDir = config.pagination_dir || 'page'; var result = []; _.each(categories, function(data, title) { _.each(data, function(data, lang) { result = result.concat({ path: lang + '/' + data.slug + '/index.html', data: { posts: getCategoryByName(locals.categories, data.category).posts }, layout: ['category', 'archive', 'index'] }); }); }); return result; }); function getCategoryByName(categories, name) { return categories.toArray().filter(function(category){ return category.name == name; })[0]; }
var pagination = require('hexo-pagination'); var _ = require('lodash'); hexo.extend.generator.register('category', function(locals){ var config = this.config; var categories = locals.data.categories; if (config.category_generator) { var perPage = config.category_generator.per_page; } else { var perPage = 10; } var paginationDir = config.pagination_dir || 'page'; var result = []; _.each(categories, function(data, title) { _.each(data, function(data, lang) { result = result.concat({ path: lang + '/' + data.slug + '/index.html', data: { posts: getCategoryByName(locals.categories, data.category).posts }, layout: ['archive', 'index'] }); }); }); return result; }); function getCategoryByName(categories, name) { return categories.toArray().filter(function(category){ return category.name == name; })[0]; }
Fix Elk versions for upgrade files
<?php /** * @name ElkArte Forum * @copyright ElkArte Forum contributors * @license BSD http://opensource.org/licenses/BSD-3-Clause * * @version 1.1 beta 1 * */ // Version Constants const CURRENT_VERSION = '1.1 beta 1'; const CURRENT_LANG_VERSION = '1.1'; const DB_SCRIPT_VERSION = '1-1'; const REQUIRED_PHP_VERSION = '5.3.3'; // String constants const SITE_SOFTWARE = 'http://www.elkarte.net'; function getUpgradeFiles() { global $db_type; return array( array('upgrade_1-0.php', '1.0', '1.0'), array('upgrade_1-0_' . $db_type . '.php', '1.0', '1.0'), array('upgrade_1-1.php', '1.1 beta 1', CURRENT_VERSION), array('upgrade_1-1_' . $db_type . '.php', '1.1 beta 1', CURRENT_VERSION), ); }
<?php /** * @name ElkArte Forum * @copyright ElkArte Forum contributors * @license BSD http://opensource.org/licenses/BSD-3-Clause * * @version 1.1 beta 1 * */ // Version Constants const CURRENT_VERSION = '1.1'; const CURRENT_LANG_VERSION = '1.1'; const DB_SCRIPT_VERSION = '1-1'; const REQUIRED_PHP_VERSION = '5.3.3'; // String constants const SITE_SOFTWARE = 'http://www.elkarte.net'; function getUpgradeFiles() { global $db_type; return array( array('upgrade_1-0.php', '1.0', CURRENT_VERSION), array('upgrade_1-0_' . $db_type . '.php', '1.0', CURRENT_VERSION), array('upgrade_1-1.php', '1.1', CURRENT_VERSION), array('upgrade_1-1_' . $db_type . '.php', '1.1', CURRENT_VERSION), ); }
Fix compilation in Java 6
package org.jetbrains.haskell.debugger.history; import com.intellij.ui.components.JBList; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class FramesPanel extends JBList { private DefaultListModel listModel = new DefaultListModel(); public FramesPanel(final HistoryManager manager) { setModel(listModel); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setValueIsAdjusting(true); addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { manager.indexSelected(getSelectedIndex()); } }); } @Override public ListModel getModel() { return listModel; } public void addElement(String line) { listModel.addElement(line); if (listModel.size() == 1) { setSelectedIndex(0); } } public void clear() { listModel.clear(); } public int getIndexCount() { return listModel.size(); } public boolean isFrameUnknown() { return getSelectedIndex() < 0 || listModel.get(getSelectedIndex()).equals("..."); } }
package org.jetbrains.haskell.debugger.history; import com.intellij.ui.components.JBList; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class FramesPanel extends JBList { private DefaultListModel<String> listModel = new DefaultListModel<String>(); public FramesPanel(final HistoryManager manager) { setModel(listModel); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setValueIsAdjusting(true); addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { manager.indexSelected(getSelectedIndex()); } }); } @Override public ListModel<String> getModel() { return listModel; } public void addElement(String line) { listModel.addElement(line); if (listModel.size() == 1) { setSelectedIndex(0); } } public void clear() { listModel.clear(); } public int getIndexCount() { return listModel.size(); } public boolean isFrameUnknown() { return getSelectedIndex() < 0 || listModel.get(getSelectedIndex()).equals("..."); } }
Fix outputMsiPath to be absolute
const electronInstaller = require('electron-winstaller') const config = require('../package.json') const format = require('string-template') const fs = require('fs') const path = require('path') const outputDirectory = './dist' const appName = 'KioskDemoElectron' let resultPromise = electronInstaller.createWindowsInstaller({ appDirectory: path.join(outputDirectory, `${appName}-win32-x64`), outputDirectory: outputDirectory, authors: config.author, noMsi: true //we'll do it with msi wrapper }) resultPromise.then(() => { const setupName = `${appName}Setup` const setupExePath = path.resolve(path.join(outputDirectory, `${setupName}.exe`)) const encoding = 'utf-8' const msiTemplate = fs.readFileSync('./installer/msi-wrapper-template.xml', encoding) const finalMsiXml = format(msiTemplate, { msiOutputPath: path.resolve(path.join(outputDirectory, `${setupName}.msi`)), setupExePath: setupExePath, author: config.author, appVersion: config.version, productName: config.productName }) console.log(finalMsiXml) fs.writeFileSync(path.join(outputDirectory, 'msi-wrapper.xml'), finalMsiXml, encoding) }, (e) => console.log(`Error: ${e.message}`))
const electronInstaller = require('electron-winstaller') const config = require('../package.json') const format = require('string-template') const fs = require('fs') const path = require('path') const outputDirectory = './dist' let resultPromise = electronInstaller.createWindowsInstaller({ appDirectory: path.join(outputDirectory, 'KioskDemoElectron-win32-x64'), outputDirectory: outputDirectory, authors: config.author, noMsi: true //we'll do it with msi wrapper }) resultPromise.then(() => { const setupName = 'KioskDemoElectronSetup' const setupExePath = path.resolve(path.join(outputDirectory, `${setupName}.exe`)) const encoding = 'utf-8' const msiTemplate = fs.readFileSync('./installer/msi-wrapper-template.xml', encoding) const finalMsiXml = format(msiTemplate, { msiOutputPath: path.join(outputDirectory, `${setupName}.msi`), setupExePath: setupExePath, author: config.author, appVersion: config.version, productName: config.productName }) console.log(finalMsiXml) fs.writeFileSync(path.join(outputDirectory, 'msi-wrapper.xml'), finalMsiXml, encoding) }, (e) => console.log(`Error: ${e.message}`))
Refactor compaction strategy to use snapshot API.
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kuujo.copycat.spi; import net.kuujo.copycat.CopycatContext; import net.kuujo.copycat.log.Log; import net.kuujo.copycat.log.SnapshotManager; /** * Log compaction strategy. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ public interface CompactionStrategy { /** * Compacts the given log. * * @param log The log to compact. * @param manager The Copycat snapshot manager. * @param context The current Copycat context. */ void compact(Log log, SnapshotManager manager, CopycatContext context); /** * Recovers the given log. * * @param log The log to recover. * @param manager The Copycat snapshot manager. * @param context The current Copycat context. */ void recover(Log log, SnapshotManager manager, CopycatContext context); }
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kuujo.copycat.spi; import net.kuujo.copycat.log.Log; /** * Log compaction strategy. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ public interface CompactionStrategy { /** * Compacts the given log. * * @param log The log to compact. */ void compact(Log log); }
Remove var command declaration (failing jshint test)
'use strict'; var Command = require('../models/command'); var lookupCommand = require('../cli/lookup-command'); var string = require('../utilities/string'); module.exports = Command.extend({ name: 'help', works: 'everywhere', description: 'Outputs the usage instructions for all commands or the provided command', aliases: [undefined, 'h', 'help', '-h', '--help'], _displayHelpForCommand: function(commandName) { var Command = this.commands[string.classify(commandName)] || lookupCommand(this.commands, commandName); new Command({ ui: this.ui, project: this.project, commands: this.commands }).printUsageInstructions(); }, run: function(commandOptions, rawArgs) { if (rawArgs.length === 0) { // Display usage for all commands. this.ui.write('Available commands in ember-cli:\n'); Object.keys(this.commands).forEach(this._displayHelpForCommand.bind(this)); } else { // If args were passed to the help command, // attempt to look up the command for each of them. this.ui.write('Requested ember-cli commands:\n\n'); // Iterate through each arg beyond the initial 'help' command, // and try to display usage instructions. rawArgs.forEach(this._displayHelpForCommand.bind(this)); } }, usageInstructions: function() { return { anonymousOptions: '<command-name (Default: all)>' }; } });
'use strict'; var Command = require('../models/command'); var lookupCommand = require('../cli/lookup-command'); var string = require('../utilities/string'); module.exports = Command.extend({ name: 'help', works: 'everywhere', description: 'Outputs the usage instructions for all commands or the provided command', aliases: [undefined, 'h', 'help', '-h', '--help'], _displayHelpForCommand: function(commandName) { var Command = this.commands[string.classify(commandName)] || lookupCommand(this.commands, commandName); var command = new Command({ ui: this.ui, project: this.project, commands: this.commands }).printUsageInstructions(); }, run: function(commandOptions, rawArgs) { if (rawArgs.length === 0) { // Display usage for all commands. this.ui.write('Available commands in ember-cli:\n'); Object.keys(this.commands).forEach(this._displayHelpForCommand.bind(this)); } else { // If args were passed to the help command, // attempt to look up the command for each of them. this.ui.write('Requested ember-cli commands:\n\n'); // Iterate through each arg beyond the initial 'help' command, // and try to display usage instructions. rawArgs.forEach(this._displayHelpForCommand.bind(this)); } }, usageInstructions: function() { return { anonymousOptions: '<command-name (Default: all)>' }; } });
Check whether liftedStore is initiated
export default function createDevToolsStore(onDispatch) { let currentState = { committedState: {}, stagedActions: [], computedStates: [], skippedActions: {}, currentStateIndex: 0 }; let listeners = []; let initiated = false; function dispatch(action) { if (action.type[0] !== '@') onDispatch(action); return action; } function getState() { return currentState; } function isSet() { return initiated; } function setState(state) { currentState = state; listeners.forEach(listener => listener()); initiated = true; } function subscribe(listener) { listeners.push(listener); return function unsubscribe() { const index = listeners.indexOf(listener); listeners.splice(index, 1); }; } return { dispatch, getState, subscribe, liftedStore: { dispatch, getState, setState, subscribe, isSet } }; }
export default function createDevToolsStore(onDispatch) { let currentState = { committedState: {}, stagedActions: [], computedStates: [], skippedActions: {}, currentStateIndex: 0 }; let listeners = []; function dispatch(action) { if (action.type[0] !== '@') onDispatch(action); return action; } function getState() { return currentState; } function setState(state) { currentState = state; listeners.forEach(listener => listener()); } function subscribe(listener) { listeners.push(listener); return function unsubscribe() { const index = listeners.indexOf(listener); listeners.splice(index, 1); }; } return { dispatch, getState, subscribe, liftedStore: { dispatch, getState, setState, subscribe } }; }
: Create documentation of DataSource Settings Task-Url:
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.show( t1 ) print '\n\n' AdminConfig.showall( t1 )
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
Remove a redundant blank line
//= require ace-builds/src/ace //= require ace-builds/src/theme-tomorrow //= require ace-builds/src/mode-markdown //= require ace-builds/src/ext-language_tools //= require bootstrap-markdown-editor //= require marked $(document).ready(function() { var content = $('#post_body').val(); $('#post_body').hide(); $('#post_body').after('<div id="editor"></div>'); $('div#editor').markdownEditor({ preview: true, imageUpload: false, width: 'calc(80% - 22px)', onPreview: function(content, callback) { callback(marked(content)); } }); $('div#editor').markdownEditor('setContent', content); $('form#edit_post').submit(function(event) { var content = $('div#editor').markdownEditor('content'); $('#post_body').val(content); }); });
//= require ace-builds/src/ace //= require ace-builds/src/theme-tomorrow //= require ace-builds/src/mode-markdown //= require ace-builds/src/ext-language_tools //= require bootstrap-markdown-editor //= require marked $(document).ready(function() { var content = $('#post_body').val(); $('#post_body').hide(); $('#post_body').after('<div id="editor"></div>'); $('div#editor').markdownEditor({ preview: true, imageUpload: false, width: 'calc(80% - 22px)', onPreview: function(content, callback) { callback(marked(content)); } }); $('div#editor').markdownEditor('setContent', content); $('form#edit_post').submit(function(event) { var content = $('div#editor').markdownEditor('content'); $('#post_body').val(content); }); });
Stop creating the regex everytime
/* * JS-Watson * * Copyright 2012, Shyam Habarakada * Licensed under MIT. * */ (function(global) { var _i = this; // Try to initialize with the default google analytics async queue var _gaq = window._gaq; // Based on http://bit.ly/ILq9ak var _pathExtractRegEx = /^[a-z]+:\/\/\/?[^\/]+(\/[^?]*)/i; // default path under which errors page-views will be reported var _pathPrefix = "/javascript_error"; // Override the google analytics async queue object used for reporting _i.setGaq = function(gaQueue) { _gaq = gaQueue; } // Override the path under which error page-views are reported _i.setBasePath = function(path) { _pathPrefix = path; } // Function to register as a callback for window.onerror (or invoke from // within a window.onerror handler. _i.trackUnhandledError = function(message, url, linenumber) { try { if(_gaq && _gaq.push && typeof(_gaq.push) == "function") { var url = _pathPrefix + (_pathExtractRegEx.exec(url))[1] + "?line=" + linenumber + "&message=" + encodeURIComponent(message); _gaq.push(['_trackPageview',url]); } } catch(e) {}; }; global["JsWatson"] = _i; })(this);
/* * JS-Watson * * Copyright 2012, Shyam Habarakada * Licensed under MIT. * */ (function(global) { var _i = this; // Try to initialize with the default google analytics async queue var _gaq = window._gaq; // default path under which errors page-views will be reported var _pathPrefix = "/javascript_error"; // Override the google analytics async queue object used for reporting _i.setGaq = function(gaQueue) { _gaq = gaQueue; } // Override the path under which error page-views are reported _i.setBasePath = function(path) { _pathPrefix = path; } // Function to register as a callback for window.onerror (or invoke from // within a window.onerror handler. _i.trackUnhandledError = function(message, url, linenumber) { try { if(_gaq && _gaq.push && typeof(_gaq.push) == "function") { var pathExtractRegEx = /^[a-z]+:\/\/\/?[^\/]+(\/[^?]*)/i; // http://bit.ly/ILq9ak var url = _pathPrefix + (pathExtractRegEx.exec(url))[1] + "?line=" + linenumber + "&message=" + encodeURIComponent(message); _gaq.push(['_trackPageview',url]); } } catch(e) {}; }; global["JsWatson"] = _i; })(this);
Add wsgi handler by default
#!/usr/bin/env python """ Copyright (c) 2008-2011, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import config import steam steam.set_api_key(config.api_key) from optf2.backend import openid from optf2.frontend import render openid.set_session(render.session) import web # wsgi application = render.application.wsgifunc() if config.enable_fastcgi: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) if __name__ == "__main__": render.application.run()
#!/usr/bin/env python """ Copyright (c) 2008-2011, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import config import steam steam.set_api_key(config.api_key) from optf2.backend import openid from optf2.frontend import render openid.set_session(render.session) import web if config.enable_fastcgi: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) if __name__ == "__main__": render.application.run()
Use context manager to read syntax file
from collections import OrderedDict import ruamel.yaml yaml = ruamel.yaml.YAML() class Operation(): def __init__(self, extension): self.extension = extension class Merge(Operation): def apply(self, base): ret = base.copy() for key, value in self.extension.items(): if key in base and isinstance(value, Operation): ret[key] = value.apply(base[key]) else: ret[key] = value return ret class Prepend(Operation): def apply(self, base): return self.extension + base def merge(*items): return Merge(OrderedDict(items)) def prepend(*items): return Prepend(list(items)) def extend(*items): extension = OrderedDict(items) base = extension['_base'] del extension['_base'] with open(base, 'r') as base_file: syntax = yaml.load(base_file) return Merge(extension).apply(syntax)
from collections import OrderedDict import ruamel.yaml yaml = ruamel.yaml.YAML() class Operation(): def __init__(self, extension): self.extension = extension class Merge(Operation): def apply(self, base): ret = base.copy() for key, value in self.extension.items(): if key in base and isinstance(value, Operation): ret[key] = value.apply(base[key]) else: ret[key] = value return ret class Prepend(Operation): def apply(self, base): return self.extension + base def merge(*items): return Merge(OrderedDict(items)) def prepend(*items): return Prepend(list(items)) def extend(*items): extension = OrderedDict(items) base = extension['_base'] del extension['_base'] syntax = yaml.load( open(base, 'r') ) return Merge(extension).apply(syntax)
Fix Gulp task not closing
'use strict'; const process = require('process'); const { promisify } = require('util'); const { watch, series, parallel } = require('gulp'); const FILES = require('../files'); // Returns a watch task // E.g. with `tasks` `{ FORMAT: format }`, the `format` task will be fired // everytime `FILES.FORMAT` is changed. // If specified, `initialTask` is fired first const getWatchTask = function (tasks, initialTask) { const watchTask = getWatchTasks(tasks); if (initialTask === undefined) { return watchTask; } // Runs the task before watching // Using `ignoreInitial` chokidar option does not work because the task would // be marked as complete before the initial run. return series(initialTask, watchTask); }; const getWatchTasks = tasks => function watchTasks () { const promises = Object.entries(tasks) .map(([type, task]) => watchByType({ type, task })); return Promise.all(promises); }; const watchByType = async function ({ type, task }) { const taskA = Array.isArray(task) ? parallel(task) : task; const watcher = watch(FILES[type], taskA); // Otherwise the task will hang when fired through npm scripts process.on('SIGINT', watcher.close.bind(watcher)); // Wait for watching to be setup to mark the `watch` task as complete await promisify(watcher.on.bind(watcher))('ready'); }; module.exports = { getWatchTask, };
'use strict'; const { promisify } = require('util'); const { watch, series, parallel } = require('gulp'); const FILES = require('../files'); // Returns a watch task // E.g. with `tasks` `{ FORMAT: format }`, the `format` task will be fired // everytime `FILES.FORMAT` is changed. // If specified, `initialTask` is fired first const getWatchTask = function (tasks, initialTask) { const watchTask = getWatchTasks(tasks); if (initialTask === undefined) { return watchTask; } // Runs the task before watching // Using `ignoreInitial` chokidar option does not work because the task would // be marked as complete before the initial run. return series(initialTask, watchTask); }; const getWatchTasks = tasks => function watchTasks () { const promises = Object.entries(tasks) .map(([type, task]) => watchByType({ type, task })); return Promise.all(promises); }; const watchByType = async function ({ type, task }) { const taskA = Array.isArray(task) ? parallel(task) : task; const watcher = watch(FILES[type], taskA); // Wait for watching to be setup to mark the `watch` task as complete await promisify(watcher.on.bind(watcher))('ready'); }; module.exports = { getWatchTask, };
Add a MathML namespace so that the detection works in XML too.
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /*jslint browser: true*/ "use strict"; (function () { window.addEventListener("load", function () { // Insert mathml.css if the <mspace> element is not supported. var box, div, link; div = document.createElement("div"); div.innerHTML = "<math xmlns='http://www.w3.org/1998/Math/MathML'><mspace height='23px' width='77px'/></math>"; document.body.appendChild(div); box = div.firstChild.firstChild.getBoundingClientRect(); document.body.removeChild(div); if (Math.abs(box.height - 23) > 1 || Math.abs(box.width - 77) > 1) { link = document.createElement("link"); link.href = "http://fred-wang.github.io/mathml.css/mathml.css"; link.rel = "stylesheet"; document.head.appendChild(link); } }); }());
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /*jslint browser: true*/ "use strict"; (function () { window.addEventListener("load", function () { // Insert mathml.css if the <mspace> element is not supported. var box, div, link; div = document.createElement("div"); div.innerHTML = "<math><mspace height='23px' width='77px'/></math>"; document.body.appendChild(div); box = div.firstChild.firstChild.getBoundingClientRect(); document.body.removeChild(div); if (Math.abs(box.height - 23) > 1 || Math.abs(box.width - 77) > 1) { link = document.createElement("link"); link.href = "http://fred-wang.github.io/mathml.css/mathml.css"; link.rel = "stylesheet"; document.head.appendChild(link); } }); }());
Add a stable url for the current API version
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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 django.views.generic import TemplateView from django.conf.urls import patterns, url, include from rest_framework import routers from apiv1 import views router = routers.DefaultRouter() router.register(r'rna', views.RnaViewSet) router.register(r'accession', views.AccessionViewSet) urlpatterns = patterns('', url(r'^v1/', include(router.urls)), url(r'^v1/', include('rest_framework.urls', namespace='rest_framework_v1')), url(r'^current/', include(router.urls)), url(r'^current/', include('rest_framework.urls', namespace='rest_framework_v1')), )
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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 django.views.generic import TemplateView from django.conf.urls import patterns, url, include from rest_framework import routers from apiv1 import views router = routers.DefaultRouter() router.register(r'rna', views.RnaViewSet) router.register(r'accession', views.AccessionViewSet) urlpatterns = patterns('', url(r'^v1/', include(router.urls)), url(r'^v1/', include('rest_framework.urls', namespace='rest_framework_v1')), )
Use fs to output file.
var fs = require('fs'); var utils = require('./tools/utils'); var shellRunner = require('./tools/shellRunner').setCommand('wkhtmltoimage'); var getFilePath = function (url, options) { var imagesPath = 'public/snapshots/'; var format = '.jpg'; return imagesPath + utils.getMd5(url) + format; }; var take = function (url, options) { var options = options || { quality: 100 }; var filePath = getFilePath(url, options); var childProcess; console.log('Start snapshot', url, options, filePath); childProcess = shellRunner.run(url, options); childProcess.stdout.pipe(fs.createWriteStream(filePath)); // childProcess.stdout.on('data', (data) => { // console.log(`stdout: ${data}`); // }); childProcess.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); childProcess.on('close', (code) => { console.log(`child process exited with code ${code}`); }); return childProcess; }; module.exports = { take: take };
var utils = require('./tools/utils') var shellRunner = require('./tools/shellRunner').setCommand('wkhtmltoimage'); var imagesPath = 'public/snapshots/'; var take = function (url) { var options = { output: imagesPath + utils.getMd5(url) + '.jpg', quality: 100 }; console.log('run', url, options); var wkhtmltoimage = shellRunner.run(url, options); wkhtmltoimage.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); wkhtmltoimage.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); wkhtmltoimage.on('close', (code) => { console.log(`child process exited with code ${code}`); }); return child; }; module.exports = { take: take };
Set wrapping to soft on textareas
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles')
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles')
Fix PHPDoc wrong type annotation
<?php /* * This file is part of the PhpTabs package. * * Copyright (c) landrok at github.com/landrok * * For the full copyright and license information, please see * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>. */ namespace PhpTabs\Share; class ChannelRoute { const PARAMETER_CHANNEL_1 = "channel-1"; const PARAMETER_CHANNEL_2 = "channel-2"; const NULL_VALUE = -1; private $channelId; private $channel1; private $channel2; /** * @param int $channelId */ public function __construct($channelId) { $this->channelId = $channelId; } /** * @return int */ public function getChannelId() { return $this->channelId; } /** * @return int */ public function getChannel1() { return $this->channel1; } /** * @param int $channel1 */ public function setChannel1($channel1) { $this->channel1 = $channel1; } /** * @return int */ public function getChannel2() { return $this->channel2; } /** * @param int $channel2 */ public function setChannel2($channel2) { $this->channel2 = $channel2; } }
<?php /* * This file is part of the PhpTabs package. * * Copyright (c) landrok at github.com/landrok * * For the full copyright and license information, please see * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>. */ namespace PhpTabs\Share; class ChannelRoute { const PARAMETER_CHANNEL_1 = "channel-1"; const PARAMETER_CHANNEL_2 = "channel-2"; const NULL_VALUE = -1; private $channelId; private $channel1; private $channel2; /** * @param int $channelId */ public function __construct($channelId) { $this->channelId = $channelId; } /** * @return int */ public function getChannelId() { return $this->channelId; } /** * @return \PhpTabs\Music\Channel */ public function getChannel1() { return $this->channel1; } /** * @param \PhpTabs\Music\Channel $channel1 */ public function setChannel1($channel1) { $this->channel1 = $channel1; } /** * @return \PhpTabs\Music\Channel */ public function getChannel2() { return $this->channel2; } /** * @param \PhpTabs\Music\Channel $channel2 */ public function setChannel2($channel2) { $this->channel2 = $channel2; } }
Connect to psql on server
import os from flask import Flask import psycopg2 import urlparse urlparse.uses_netloc.append("postgres") url = urlparse.urlparse(os.environ["DATABASE_URL"]) conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) app = Flask(__name__) basedir = os.path.abspath(os.path.dirname('data')) basedir_img = os.path.abspath(os.path.dirname('angular_flask')) app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e" #app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db') #app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://admin:111111@localhost:5432/posts' app.config["DEBUG"] = True app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img') import angular_flask.core import angular_flask.models import angular_flask.controllers
import os from flask import Flask app = Flask(__name__) basedir = os.path.abspath(os.path.dirname('data')) basedir_img = os.path.abspath(os.path.dirname('angular_flask')) app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e" #app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db') app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://admin:111111@localhost:5432/posts' app.config["DEBUG"] = True app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img') import angular_flask.core import angular_flask.models import angular_flask.controllers
Fix callback and version check
import { offline } from 'redux-offline'; import offlineConfig from 'redux-offline/lib/defaults'; import detectNetwork from 'redux-offline/lib/defaults/detectNetwork.native'; import { AsyncStorage } from 'react-native'; // eslint-disable-line import/no-unresolved import { persistStore } from 'redux-persist'; import { version } from 'package.json'; import effect from './effect'; const persistNative = (store, options, callback) => { AsyncStorage.getItem('reduxPersist:app', (err, appData) => { const getPersistedStore = () => persistStore(store, { storage: AsyncStorage, ...options }, callback); let app = null; if (!err) { app = JSON.parse(appData); } if (app && app.version !== version) { getPersistedStore().purge(); } else { getPersistedStore(); // .purge to clean the offline data } }); }; const config = params => ({ ...offlineConfig, effect, detectNetwork, persist: persistNative, persistOptions: { blacklist: ['setup'] }, persistCallback: params.persistCallback }); export default params => offline(config(params));
import { offline } from 'redux-offline'; import offlineConfig from 'redux-offline/lib/defaults'; import detectNetwork from 'redux-offline/lib/defaults/detectNetwork.native'; import { AsyncStorage } from 'react-native'; // eslint-disable-line import/no-unresolved import { persistStore } from 'redux-persist'; import { version } from 'package.json'; import effect from './effect'; const persistNative = (store, options, callback) => { AsyncStorage.getItem('reduxPersist:app', (app) => { const getPersistedStore = () => persistStore(store, { storage: AsyncStorage, ...options }, callback); if (app && app.version !== version) { getPersistedStore().purge(); } else { getPersistedStore(); // .purge to clean the offline data } }); }; const config = params => ({ ...offlineConfig, effect, detectNetwork, persist: persistNative, persistOptions: { blacklist: ['setup'] }, persistCallback: params.persistCallback }); export default params => offline(config(params));
Use v as a selector arther than views
package controllers import ( v "github.com/anonx/sunplate/skeleton/assets/views" "github.com/anonx/sunplate/action" ) // App is a sample controller that is used for demonstration purposes. type App struct { *Controller } // Before is a magic method that is executed before every request. func (c *App) Before(name string, pages []int) action.Result { return nil } // Index is an action that is used for generation of a greeting form. func (c *App) Index() action.Result { return c.RenderTemplate(v.Paths.App.IndexHTML) } // PostGreet prints received user fullname. If it is not valid, // user is redirected back to index page. func (c *App) PostGreet(name string) action.Result { c.Context["name"] = name return c.RenderTemplate(v.Paths.App.GreetHTML) } // After is a magic method that is executed after every request. func (c *App) After() action.Result { return nil } // Finally is a magic method that is executed after every request // no matter what. func (c *App) Finally(name string) action.Result { return nil }
package controllers import ( "github.com/anonx/sunplate/skeleton/assets/views" "github.com/anonx/sunplate/action" ) // App is a sample controller that is used for demonstration purposes. type App struct { *Controller } // Before is a magic method that is executed before every request. func (c *App) Before(name string, pages []int) action.Result { return nil } // Index is an action that is used for generation of a greeting form. func (c *App) Index() action.Result { return c.RenderTemplate(views.Paths.App.IndexHTML) } // PostGreet prints received user fullname. If it is not valid, // user is redirected back to index page. func (c *App) PostGreet(name string) action.Result { c.Context["name"] = name return c.RenderTemplate(views.Paths.App.GreetHTML) } // After is a magic method that is executed after every request. func (c *App) After() action.Result { return nil } // Finally is a magic method that is executed after every request // no matter what. func (c *App) Finally(name string) action.Result { return nil }
Add -, -, ., to allowed characters in table names
package main // Validate the provided user and database name func validateUserDB(user string, db string) error { errs := validate.Var(user, "required,alphanum,min=3,max=63") if errs != nil { return errs } errs = validate.Var(db, "required,alphanum|contains=.,min=1,max=1024") if errs != nil { return errs } return nil } // Validate the provided user, database, and table name func validateUserDBTable(user string, db string, table string) error { errs := validateUserDB(user, db) if errs != nil { return errs } // TODO: Improve this to work with all valid SQLite identifiers // TODO Not seeing a definitive reference page for SQLite yet, so using the PostgreSQL one is // TODO probably ok as a fallback: // TODO https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS // TODO: Should we exclude SQLite internal tables too? (eg "sqlite_*" https://sqlite.org/lang_createtable.html) errs = validate.Var(table, "required,alphanum|contains=-|contains=_|contains=.,max=63") if errs != nil { return errs } return nil }
package main // Validate the provided user and database name func validateUserDB(user string, db string) error { errs := validate.Var(user, "required,alphanum,min=3,max=63") if errs != nil { return errs } errs = validate.Var(db, "required,alphanum|contains=.,min=1,max=1024") if errs != nil { return errs } return nil } // Validate the provided user, database, and table name func validateUserDBTable(user string, db string, table string) error { errs := validateUserDB(user, db) if errs != nil { return errs } // TODO: Improve this to work with all valid PostgreSQL identifiers // https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS errs = validate.Var(table, "required,alphanum,max=63") if errs != nil { return errs } return nil }
Raise error on unknown job type
import yaml from ssbench.constants import * class Worker: def __init__(self, queue): queue.use(STATS_TUBE) self.queue = queue def go(self): job = self.queue.reserve() while job: job.delete() # avoid any job-timeout nonsense self.handle_job(job) job = self.queue.reserve() def handle_job(self, job): job_data = yaml.load(job.body) if job_data['type'] == UPLOAD_OBJECT: print "WOO" # magic goes here else: raise NameError("Unknown job type %r" % (job_data['type'],))
import yaml from ssbench.constants import * class Worker: def __init__(self, queue): queue.use(STATS_TUBE) self.queue = queue def go(self): job = self.queue.reserve() while job: job.delete() # avoid any job-timeout nonsense self.handle_job(job) job = self.queue.reserve() def handle_job(self, job): job_data = yaml.load(job.body) if job_data['type'] == UPLOAD_OBJECT: print "WOO" # magic goes here else: print "BOO"
Fix possible uncaught exception in retreiving messages
define([ 'underscore', 'controller' ], function (_, Controller) { var AccountController = Controller.extend({ handers: { 'account:add' : 'createAccount' }, initialize: function (opts) { this.collection.on('change:connected', this.accountConnected.bind(this)); }, createAccount: function (options) { return this.collection.create(arguments, {parse:true}); }, accountConnected: function (account) { var self = this; account.getMessages('Inbox').then(function (messages) { self.radio.vent.trigger('mailbox:update', {mailbox:'INBOX', account: account, messages: messages}); }).then(null, function (err) { // TODO console.log('Error getting inbox messages', err); }); } }); return AccountController; });
define([ 'underscore', 'controller' ], function (_, Controller) { var AccountController = Controller.extend({ handers: { 'account:add' : 'createAccount' }, initialize: function (opts) { this.collection.on('change:connected', this.accountConnected.bind(this)); }, createAccount: function (options) { return this.collection.create(arguments, {parse:true}); }, accountConnected: function (account) { var self = this; account.getMessages('Inbox').then(function (messages) { self.radio.vent.trigger('mailbox:update', {mailbox:'INBOX', account: account, messages: messages}); }, function (err) { // TODO console.log('Error getting inbox messages', err); }); } }); return AccountController; });
Use verbose array syntax for PHP 5.3
<?php namespace Stripe; class BankAccountTest extends TestCase { public function testVerify() { self::authorizeFromEnv(); $customer = self::createTestCustomer(); $bankAccount = $customer->sources->create(array( 'source' => array( 'object' => 'bank_account', 'account_number' => '000123456789', 'routing_number' => '110000000', 'country' => 'US' ) )); $this->assertSame($bankAccount->status, 'new'); $bankAccount = $bankAccount->verify(array( 'amounts' => array(32, 45) )); $this->assertSame($bankAccount->status, 'verified'); } }
<?php namespace Stripe; class BankAccountTest extends TestCase { public function testVerify() { self::authorizeFromEnv(); $customer = self::createTestCustomer(); $bankAccount = $customer->sources->create([ 'source' => [ 'object' => 'bank_account', 'account_number' => '000123456789', 'routing_number' => '110000000', 'country' => 'US' ] ]); $this->assertSame($bankAccount->status, 'new'); $bankAccount = $bankAccount->verify([ 'amounts' => [32, 45] ]); $this->assertSame($bankAccount->status, 'verified'); } }
Add TODO for clear loading upon refresh
/* * Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved. * * This file is part of BoxCharter. * * BoxCharter is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * BoxCharter is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with BoxCharter. If not, see <http://www.gnu.org/licenses/>. * */ /** * Action creators for loading state. * @module * loadingActions */ import { CANCEL_ALL_LOADING } from './loadingActionTypes'; // TODO: call this upon page refresh // (where? get funny routing errors if I make App a connected component...) /** * Return CANCEL_ALL_LOADING action. * @function clearLoadingEvents * @returns {object} - CANCEL_ALL_LOADING action. */ const clearLoadingEvents = () => ({ type: CANCEL_ALL_LOADING }); module.exports = { clearLoadingEvents, };
/* * Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved. * * This file is part of BoxCharter. * * BoxCharter is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * BoxCharter is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with BoxCharter. If not, see <http://www.gnu.org/licenses/>. * */ /** * Action creators for loading state. * @module * loadingActions */ import { CANCEL_ALL_LOADING } from './loadingActionTypes'; /** * Return CANCEL_ALL_LOADING action. * @function clearLoadingEvents * @returns {object} - CANCEL_ALL_LOADING action. */ const clearLoadingEvents = () => ({ type: CANCEL_ALL_LOADING }); module.exports = { clearLoadingEvents, };
Fix unit error, improve precision
from astropy import units as u from numpy.testing import assert_almost_equal from poliastro.bodies import Earth from edelbaum import extra_quantities def test_leo_geo_time_and_delta_v(): a_0 = 7000.0 # km a_f = 42166.0 # km i_f = 0.0 # rad i_0 = (28.5 * u.deg).to(u.rad).value # rad f = 3.5e-7 # km / s2 k = Earth.k.decompose([u.km, u.s]).value expected_t_f = 191.26295 # s expected_delta_V = 5.78378 # km / s delta_V, t_f = extra_quantities(k, a_0, a_f, i_f - i_0, f) assert_almost_equal(t_f / 86400, expected_t_f, decimal=2) assert_almost_equal(delta_V, expected_delta_V, decimal=4)
from astropy import units as u from numpy.testing import assert_almost_equal from poliastro.bodies import Earth from edelbaum import extra_quantities def test_leo_geo_time_and_delta_v(): a_0 = 7000.0 # km a_f = 42166.0 # km i_f = 0.0 # deg i_0 = 28.5 # deg f = 3.5e-7 # km / s2 k = Earth.k.decompose([u.km, u.s]).value expected_t_f = 191.26295 # s expected_delta_V = 5.78378 # km / s delta_V, t_f = extra_quantities(k, a_0, a_f, i_f - i_0, f) assert_almost_equal(t_f / 86400, expected_t_f, decimal=0) assert_almost_equal(delta_V, expected_delta_V, decimal=1)
Add program modal PROGRAM_REQUISITION modal key
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { modalStrings } from '../localization'; export const MODAL_KEYS = { SELECT_CUSTOMER: 'selectCustomer', COMMENT_EDIT: 'commentEdit', THEIR_REF_EDIT: 'theirRefEdit', ITEM_SELECT: 'itemSelect', SELECT_CUSTOMER: 'selectCustomer', SELECT_SUPPLIER: 'selectSupplier', PROGRAM_REQUISITION: 'programRequisition', }; export const getModalTitle = modalKey => { switch (modalKey) { default: case MODAL_KEYS.ITEM_SELECT: return modalStrings.search_for_an_item_to_add; case MODAL_KEYS.COMMENT_EDIT: return modalStrings.edit_the_invoice_comment; case MODAL_KEYS.THEIR_REF_EDIT: return modalStrings.edit_their_reference; case MODAL_KEYS.SELECT_CUSTOMER: return modalStrings.search_for_the_customer; case MODAL_KEYS.SELECT_SUPPLIER: return modalStrings.search_for_the_supplier; } };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { modalStrings } from '../localization'; export const MODAL_KEYS = { SELECT_CUSTOMER: 'selectCustomer', COMMENT_EDIT: 'commentEdit', THEIR_REF_EDIT: 'theirRefEdit', ITEM_SELECT: 'itemSelect', SELECT_CUSTOMER: 'selectCustomer', SELECT_SUPPLIER: 'selectSupplier', }; export const getModalTitle = modalKey => { switch (modalKey) { default: case MODAL_KEYS.ITEM_SELECT: return modalStrings.search_for_an_item_to_add; case MODAL_KEYS.COMMENT_EDIT: return modalStrings.edit_the_invoice_comment; case MODAL_KEYS.THEIR_REF_EDIT: return modalStrings.edit_their_reference; case MODAL_KEYS.SELECT_CUSTOMER: return modalStrings.search_for_the_customer; case MODAL_KEYS.SELECT_SUPPLIER: return modalStrings.search_for_the_supplier; } };
Fix producer count on publication admin
import React from 'react' import PropTypes from 'prop-types' import withFetch from '../../hoc/with-fetch' import Link from '../../link' const SourceProducers = ({organization}) => ( <div> {organization.producers && organization.producers.length > 0 ? ( <div> <strong>{organization.producers.length}</strong> producteurs sont associΓ©s Γ  votre organisation <ul> {organization.producers.map(producer => ( <li key={producer._id}>{producer._id}</li> ))} </ul> </div> ) : ( <p> Aucun producteur n’est associΓ© Γ  votre organisation. </p> )} <Link prefetch href={`/publication/producers?oid=${organization._id}`} as={`/publication/${organization._id}/producers`}> <a> Associer des producteurs </a> </Link> </div> ) SourceProducers.propTypes = { organization: PropTypes.shape({ _id: PropTypes.string.isRequired, producers: PropTypes.arrayOf(PropTypes.shape({ _id: PropTypes.string.isRequired })).isRequired }).isRequired } export default withFetch( data => ({ organization: data }) )(SourceProducers)
import React from 'react' import PropTypes from 'prop-types' import withFetch from '../../hoc/with-fetch' import Link from '../../link' const SourceProducers = ({organization}) => ( <div> {organization.producers ? <div> <strong>{organization.producers && organization.producers.length > 0}</strong> producteurs sont associΓ©s Γ  votre organisation <ul> {organization.producers.map(producer => ( <li key={producer._id}>{producer._id}</li> ))} </ul> </div> : <div> Aucun producteur n’est associΓ© Γ  votre organisation. </div> } <Link prefetch href={`/publication/producers?oid=${organization._id}`} as={`/publication/${organization._id}/producers`}> <a> Associer des producteurs </a> </Link> </div> ) SourceProducers.propTypes = { organization: PropTypes.shape({ _id: PropTypes.string.isRequired, producers: PropTypes.arrayOf(PropTypes.shape({ _id: PropTypes.string.isRequired })).isRequired }).isRequired } export default withFetch( data => ({ organization: data }) )(SourceProducers)
Fix on function generate random solution
from abc import ABC, abstractmethod import random as random class AbstractHeuristic(ABC): @abstractmethod def calculate(self, solution): pass def calculateCost(self, dataset, solution): cost = 0 i = 0 cost += dataset.getValueXY(0, solution[0]) for i in range(0, len(solution)-1): cost += dataset.getValueXY(solution[i], solution[i + 1]) i += 1 cost += dataset.getValueXY(i,solution[0]) return cost def generateRandomSolution(self, dataset): length = len(dataset[-1])-1 solution = [] for i in range(length): value = random.randint(1, length) while value in solution: value = (value + 1) % (length + 1) if value == 0: value = 1 solution.append(value) return solution
from abc import ABC, abstractmethod import random as random class AbstractHeuristic(ABC): @abstractmethod def calculate(self, solution): pass def calculateCost(self, dataset, solution): cost = 0 i = 0 cost += dataset.getValueXY(0, solution[0]) for i in range(0, len(solution)-1): cost += dataset.getValueXY(solution[i], solution[i + 1]) i += 1 cost += dataset.getValueXY(i,solution[0]) return cost def generateRandomSolution(self, dataset): length = len(dataset[-1])-1 solution = [] for i in range(length): value = random.randint(1, length) while value in solution: value = (value + 1) % length + 1 solution.append(value) return solution
Fix asset picker input focus
import React, { PropTypes, PureComponent } from 'react'; import { findDOMNode } from 'react-dom'; import { InputGroup } from 'binary-components'; import { isMobile } from 'binary-utils'; import { actions } from '../_store'; import MarketSubmarketPickerContainer from './MarketSubmarketPickerContainer'; export default class AssetPickerFilter extends PureComponent { static propTypes = { filter: PropTypes.object.isRequired, }; componentDidMount() { const assetSearchNode = findDOMNode(this); if (!isMobile()) { setTimeout(() => assetSearchNode.firstChild && assetSearchNode.firstChild.firstChild && assetSearchNode.firstChild.firstChild.focus(), 100); } } onSearchQueryChange = e => { actions.updateAssetPickerSearchQuery(e.target.value); } onFilterChange = e => { actions.updateAssetPickerFilter(e); } render() { const { filter } = this.props; return ( <div className="asset-picker-filter"> <InputGroup className="asset-search" defaultValue={filter.query} type="search" placeholder="Search for assets" onChange={this.onSearchQueryChange} /> <MarketSubmarketPickerContainer onChange={this.onFilterChange} allOptionShown value={filter.filter} /> </div> ); } }
import React, { PropTypes, PureComponent } from 'react'; import { findDOMNode } from 'react-dom'; import { InputGroup } from 'binary-components'; import { isMobile } from 'binary-utils'; import { actions } from '../_store'; import MarketSubmarketPickerContainer from './MarketSubmarketPickerContainer'; export default class AssetPickerFilter extends PureComponent { static propTypes = { filter: PropTypes.object.isRequired, }; componentDidMount() { const assetSearchNode = findDOMNode(this); if (!isMobile()) { setTimeout(() => assetSearchNode.firstChild.focus(), 300); } } onSearchQueryChange = e => { actions.updateAssetPickerSearchQuery(e.target.value); } onFilterChange = e => { actions.updateAssetPickerFilter(e); } render() { const { filter } = this.props; return ( <div className="asset-picker-filter"> <InputGroup className="asset-search" defaultValue={filter.query} type="search" placeholder="Search for assets" onChange={this.onSearchQueryChange} /> <MarketSubmarketPickerContainer onChange={this.onFilterChange} allOptionShown value={filter.filter} /> </div> ); } }
Set FIPS code from command line
import datetime import pymongo import os import sys from courtreader import readers # Connect to database client = pymongo.MongoClient(os.environ['DISTRICT_DB']) db = client.va_district_court_cases # Connect to District Court Reader reader = readers.DistrictCourtReader() reader.connect() # Fill in cases while True: case = db.cases.find_one({ 'FIPSCode': sys.argv[1], 'date_collected': {'$exists': False} }) if case is None: break print case['CaseNumber'] case_details = reader.get_case_details_by_number( \ case['FIPSCode'], case['CaseNumber']) case_details['date_collected'] = datetime.datetime.utcnow() updated_case = dict(case.items() + case_details.items()) db.cases.replace_one({'_id': case['_id']}, updated_case) print 'Finished'
import datetime import pymongo import os from courtreader import readers # Connect to database client = pymongo.MongoClient(os.environ['DISTRICT_DB']) db = client.va_district_court_cases # Connect to District Court Reader reader = readers.DistrictCourtReader() reader.connect() # Fill in cases while True: case = db.cases.find_one({ 'FIPSCode': '702', \ 'date_collected': {'$exists': False} \ }) if case is None: break print case['CaseNumber'] case_details = reader.get_case_details_by_number( \ case['FIPSCode'], case['CaseNumber']) case_details['date_collected'] = datetime.datetime.utcnow() updated_case = dict(case.items() + case_details.items()) db.cases.replace_one({'_id': case['_id']}, updated_case) print 'Finished'
Support if skill group/types are changed
from celery.decorators import task from eve_proxy.models import CachedDocument from eve_api.utils import basic_xml_parse_doc from eve_api.models import EVESkill, EVESkillGroup @task() def import_eve_skills(): """ Imports the skill tree and groups """ char_doc = CachedDocument.objects.api_query('/eve/SkillTree.xml.aspx') d = basic_xml_parse_doc(char_doc)['eveapi'] if 'error' in d: return values = d['result'] for group in values['skillGroups']: gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID']) if created or not gobj.name or not gobj.name == group['groupName']: gobj.name = group['groupName'] gobj.save() for skill in group['skills']: skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID']) if created or not skillobj.name or not skillobj.group or not skillobj.name == skill['typeName']: skillobj.name = skill['typeName'] skillobj.group = gobj skillobj.save()
from celery.decorators import task from eve_proxy.models import CachedDocument from eve_api.utils import basic_xml_parse_doc from eve_api.models import EVESkill, EVESkillGroup @task() def import_eve_skills(): """ Imports the skill tree and groups """ char_doc = CachedDocument.objects.api_query('/eve/SkillTree.xml.aspx') d = basic_xml_parse_doc(char_doc)['eveapi'] if 'error' in d: return values = d['result'] for group in values['skillGroups']: gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID']) if created: gobj.name = group['groupName'] gobj.save() for skill in group['skills']: skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID']) if created or not skillobj.name or not skillobj.group: skillobj.name = skill['typeName'] skillobj.group = gobj skillobj.save()
Add toString to dump profile attributes
/* * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.oxauth.client.auth.user; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * User profile retrieved from oxAuth after successful authentication * * @author Yuriy Movchan 11/14/2014 */ public class UserProfile implements Serializable { private static final long serialVersionUID = 4570636703916315314L; private String id; private final Map<String, Object> attributes = new HashMap<String, Object>(); public String getId() { return id; } public void setId(final String id) { this.id = id; } public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(this.attributes); } public Object getAttribute(final String name) { return this.attributes.get(name); } public void addAttribute(final String key, final Object value) { if (value != null) { this.attributes.put(key, value); } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("UserProfile [id=").append(id).append(", attributes=").append(attributes).append("]"); return builder.toString(); } }
/* * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.oxauth.client.auth.user; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * User profile retrieved from oxAuth after successful authentication * * @author Yuriy Movchan 11/14/2014 */ public class UserProfile implements Serializable { private static final long serialVersionUID = 4570636703916315314L; private String id; private final Map<String, Object> attributes = new HashMap<String, Object>(); public String getId() { return id; } public void setId(final String id) { this.id = id; } public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(this.attributes); } public Object getAttribute(final String name) { return this.attributes.get(name); } public void addAttribute(final String key, final Object value) { if (value != null) { this.attributes.put(key, value); } } }
[CleanUp] Store .env file ext into const
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Server */ namespace PH7\Framework\Server; defined('PH7') or exit('Restricted access'); class Environment { const ENV_FILE_EXT = '.env'; const PRODUCTION_MODE = 'production'; const DEVELOPMENT_MODE = 'development'; const MODES = [ self::PRODUCTION_MODE, self::DEVELOPMENT_MODE ]; /** * @param string $sEnvName The chosen environment name. * * @return string The correct config environment filename (without .php ext). */ public static function getFileName($sEnvName) { $sFileName = in_array($sEnvName, self::MODES, true) ? $sEnvName : self::PRODUCTION_MODE; return $sFileName . self::ENV_FILE_EXT; } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Server */ namespace PH7\Framework\Server; defined('PH7') or exit('Restricted access'); class Environment { const PRODUCTION_MODE = 'production'; const DEVELOPMENT_MODE = 'development'; const MODES = [ self::PRODUCTION_MODE, self::DEVELOPMENT_MODE ]; /** * @param string $sEnvName The chosen environment name. * * @return string The correct config environment filename (without .php ext). */ public static function getFileName($sEnvName) { $sFileName = in_array($sEnvName, self::MODES, true) ? $sEnvName : self::PRODUCTION_MODE; return $sFileName . '.env'; } }
Add back download url :/
from setuptools import setup setup( name='pyhunter', packages=['pyhunter'], version='0.1', description='An (unofficial) Python wrapper for the Hunter.io API', author='Quentin Durantay', author_email='quentin.durantay@gmail.com', url='https://github.com/VonStruddle/PyHunter', download_url='https://github.com/VonStruddle/PyHunter/archive/0.1.tar.gz', install_requires=['requests'], keywords=['hunter', 'hunter.io', 'lead generation', 'lead enrichment'], classifiers=[ 'Development Status :: 3 - Alpha', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities' ], )
from setuptools import setup setup( name='pyhunter', packages=['pyhunter'], version='0.1', description='An (unofficial) Python wrapper for the Hunter.io API', author='Quentin Durantay', author_email='quentin.durantay@gmail.com', url='https://github.com/VonStruddle/PyHunter', install_requires=['requests'], keywords=['hunter', 'hunter.io', 'lead generation', 'lead enrichment'], classifiers=[ 'Development Status :: 3 - Alpha', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities' ], )
Write to bouncer config file
#!/usr/bin/env python import sys import yaml def read_parts_from_stdin(): data = sys.stdin.read() parts_string = data.split("----") parts_parsed = [] for part in parts_string: part_parsed = yaml.safe_load(part) parts_parsed.append(part_parsed) return parts_parsed def assemble_bouncer_config(parts): merged_parts = { } for part in parts: merged_parts.update(part) bouncer_config = { 'collector': merged_parts } return yaml.dump(bouncer_config) def write_bouncer_config(path, bouncer_config_contents): try: f = open(path, 'w') f.write(bouncer_config_contents) f.close() except IOError: print "Couldn't write to bouncer config file." exit(1) bouncer_config_path = '/home/mlab/data/bouncer.yaml' if len(sys.argv) >= 2: bouncer_config_path = sys.argv[1] # FIXME: Read from the mlab-ns simulator. parts = read_parts_from_stdin() bouncer_config = assemble_bouncer_config(parts) write_bouncer_config(bouncer_config_path, bouncer_config)
#!/usr/bin/env python import sys import yaml def read_parts_from_stdin(): data = sys.stdin.read() parts_string = data.split("----") parts_parsed = [] for part in parts_string: part_parsed = yaml.safe_load(part) parts_parsed.append(part_parsed) return parts_parsed def assemble_bouncer_config(parts): merged_parts = { } for part in parts: merged_parts.update(part) bouncer_config = { 'collector': merged_parts } return yaml.dump(bouncer_config) def write_bouncer_config(bouncer_config, path): print bouncer_config parts = read_parts_from_stdin() bouncer_config = assemble_bouncer_config(parts) write_bouncer_config(bouncer_config, '/home/mlab/data/bouncer.yaml')
Fix 'cant import from .django'
################################################################### # # Copyright (c) 2013 Miing.org <samuel.miing@gmail.com> # # This software is licensed under the GNU Affero General Public # License version 3 (AGPLv3), as published by the Free Software # Foundation, and may be copied, distributed, and modified under # those terms. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # file LICENSE for more details. # ################################################################### from .postgresql import ( pgsql_createuser, pgsql_dropdb, pgsql_createdb, pgsql_dropuser, ) from .django import syncdb, grantuser def setup_pgsql_database(): """Setup PostgreSQL database""" pgsql_createuser() pgsql_createdb() syncdb() grantuser() def drop_pgsql_database(): """Clean PostgreSQL database""" pgsql_dropdb() pgsql_dropuser()
################################################################### # # Copyright (c) 2013 Miing.org <samuel.miing@gmail.com> # # This software is licensed under the GNU Affero General Public # License version 3 (AGPLv3), as published by the Free Software # Foundation, and may be copied, distributed, and modified under # those terms. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # file LICENSE for more details. # ################################################################### from .postgresql import ( pgsql_createuser, pgsql_dropdb, pgsql_createdb, pgsql_dropuser, ) from .django import syncdb grantuser def setup_pgsql_database(): """Setup PostgreSQL database""" pgsql_createuser() pgsql_createdb() syncdb() grantuser() def drop_pgsql_database(): """Clean PostgreSQL database""" pgsql_dropdb() pgsql_dropuser()
Use EC2 metadata for credentials.
var Promise = require('bluebird'); var AWS = require('aws-sdk'); AWS.config.credentials = new AWS.EC2MetadataCredentials(); AWS.config.region = 'us-west-2'; // See aws/aws-sdk-js#473 var lambda = new AWS.Lambda({apiVersion: '2015-03-31'}); module.exports = { compile: function(key, body, version) { version = (version === 'unstable') ? 'unstable' : 'stable'; return new Promise(function (fulfill, reject) { lambda.invoke({ FunctionName: 'lilybin-' + version, Payload: JSON.stringify({ body : body, key : key }) }, function (err, data) { if (err) return reject(err); var payload = JSON.parse(data.Payload); if (data.FunctionError) { return reject(new Error(payload.errorMessage)); } fulfill(payload); }); }); }, };
var Promise = require('bluebird'); var AWS = require('aws-sdk'); var credentials = new AWS.SharedIniFileCredentials({profile: 'lilybin'}); AWS.config.credentials = credentials; AWS.config.region = 'us-west-2'; // See aws/aws-sdk-js#473 var lambda = new AWS.Lambda({apiVersion: '2015-03-31'}); module.exports = { compile: function(key, body, version) { version = (version === 'unstable') ? 'unstable' : 'stable'; return new Promise(function (fulfill, reject) { lambda.invoke({ FunctionName: 'lilybin-' + version, Payload: JSON.stringify({ body : body, key : key }) }, function (err, data) { if (err) return reject(err); var payload = JSON.parse(data.Payload); if (data.FunctionError) { return reject(new Error(payload.errorMessage)); } fulfill(payload); }); }); }, };
Make primary-color consistent with image.
package background import ( "image" "os/exec" "os/user" "path/filepath" ) // Set the background on windows. func Set(img image.Image) error { // Get the absolute path of the directory. usr, err := user.Current() if err != nil { return err } imgPath := filepath.Join(usr.HomeDir, ".local", "share", "himawari", "background.png") // Create the file. if err := createFile(img, imgPath); err != nil { return err } // Darken background area err = exec.Command( "gsettings", "set", "org.gnome.desktop.background", "primary-color", "#000000", ).Run() // Set the background (gnome3 only atm) err = exec.Command( "gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://"+imgPath, ).Run() // Set background mode (again, testing on gnome3) err = exec.Command( "gsettings", "set", "org.gnome.desktop.background", "picture-options", "scaled", ).Run() return err }
package background import ( "image" "os/exec" "os/user" "path/filepath" ) // Set the background on windows. func Set(img image.Image) error { // Get the absolute path of the directory. usr, err := user.Current() if err != nil { return err } imgPath := filepath.Join(usr.HomeDir, ".local", "share", "himawari", "background.png") // Create the file. if err := createFile(img, imgPath); err != nil { return err } // Set the background (gnome3 only atm) err = exec.Command( "gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://"+imgPath, ).Run() // Set background mode (again, testing on gnome3) err = exec.Command( "gsettings", "set", "org.gnome.desktop.background", "picture-options", "scaled", ).Run() return err }
Remove leading empty line in multiline test
import os from textwrap import dedent from autosort.sorting import sort_imports def test_regular(): path = os.path.abspath('test.py') rv = sort_imports(dedent('''\ from tokenize import COMMENT, INDENT, ENDMARKER from tokenize import (DEDENT, # noqa NEWLINE, STRING, NAME) '''), path) assert rv == dedent('''\ from tokenize import (COMMENT, DEDENT, ENDMARKER, # noqa INDENT, NAME, NEWLINE, STRING) # noqa ''')
import os from textwrap import dedent from autosort.sorting import sort_imports def test_regular(): path = os.path.abspath('test.py') rv = sort_imports(dedent(''' from tokenize import COMMENT, INDENT, ENDMARKER from tokenize import (DEDENT, # noqa NEWLINE, STRING, NAME) '''), path) assert rv == dedent('''\ from tokenize import (COMMENT, DEDENT, ENDMARKER, # noqa INDENT, NAME, NEWLINE, STRING) # noqa ''')
Declare package so that "go get" this repo doesn't complain. package github.com/gyuho/goraph/... imports github.com/gyuho/goraph/algorithm/tsdfs imports github.com/gyuho/goraph/algorithm/tsdfs: /usr/local/google/home/samschaevitz/gocode/src/github.com/gyuho/goraph/algorithm/tsdfs/tsdfs_test.go:26:4: expected 'package', found 'EOF'
package tsdfs func main() {} // Output differs every time it runs. /* import ( "testing" "github.com/gyuho/goraph/graph/gs" ) func TestTSDFS(t *testing.T) { g6 := gs.FromJSON("../../files/testgraph.json", "testgraph.006") g6s := TSDFS(g6) g6c := "E β†’ D β†’ C β†’ B β†’ A β†’ F" if g6s != g6c { t.Errorf("Should be same but\n%v\n%v", g6s, g6c) } g7 := gs.FromJSON("../../files/testgraph.json", "testgraph.007") g7s := TSDFS(g7) g7c := "C β†’ B β†’ D β†’ F β†’ A β†’ H β†’ E β†’ G" if g7s != g7c { t.Errorf("Should be same but\n%v\n%v", g7s, g7c) } } */
// Output differs every time it runs. /* package tsdfs import ( "testing" "github.com/gyuho/goraph/graph/gs" ) func TestTSDFS(t *testing.T) { g6 := gs.FromJSON("../../files/testgraph.json", "testgraph.006") g6s := TSDFS(g6) g6c := "E β†’ D β†’ C β†’ B β†’ A β†’ F" if g6s != g6c { t.Errorf("Should be same but\n%v\n%v", g6s, g6c) } g7 := gs.FromJSON("../../files/testgraph.json", "testgraph.007") g7s := TSDFS(g7) g7c := "C β†’ B β†’ D β†’ F β†’ A β†’ H β†’ E β†’ G" if g7s != g7c { t.Errorf("Should be same but\n%v\n%v", g7s, g7c) } } */
Add Python 3.8 to trove classifiers
#!/usr/bin/env python from setuptools import setup setup( name="htmlgen", version="2.0.0", description="HTML 5 Generator", long_description=open("README.md").read(), long_description_content_type="text/markdown", author="Sebastian Rittau", author_email="srittau@rittau.biz", url="https://github.com/srittau/python-htmlgen", packages=["htmlgen", "test_htmlgen"], package_data={"htmlgen": ["*.pyi", "py.typed"]}, python_requires=">=3.5", tests_require=["asserts >= 0.8.0, < 0.11"], license="MIT", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Internet :: WWW/HTTP :: WSGI", "Topic :: Text Processing :: Markup :: HTML", ], )
#!/usr/bin/env python from setuptools import setup setup( name="htmlgen", version="2.0.0", description="HTML 5 Generator", long_description=open("README.md").read(), long_description_content_type="text/markdown", author="Sebastian Rittau", author_email="srittau@rittau.biz", url="https://github.com/srittau/python-htmlgen", packages=["htmlgen", "test_htmlgen"], package_data={"htmlgen": ["*.pyi", "py.typed"]}, python_requires=">=3.5", tests_require=["asserts >= 0.8.0, < 0.11"], license="MIT", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Internet :: WWW/HTTP :: WSGI", "Topic :: Text Processing :: Markup :: HTML", ], )
connection-settings: Add support for macro replacement in file parsing Macro replacement is limited to system properties and environment variables. See https://maven.apache.org/settings.html Signed-off-by: BJ Hargrave <3d26bb3930946e3370762d769a073cece444c2d8@bjhargrave.com>
package aQute.bnd.connection.settings; import java.io.File; import aQute.bnd.osgi.Macro; import aQute.bnd.osgi.Processor; import aQute.lib.xpath.XPathParser; public class SettingsParser extends XPathParser { final SettingsDTO settings = new SettingsDTO(); private final Macro replacer = new Processor().getReplacer(); /* * <proxies> <proxy> <id>example-proxy</id> <active>true</active> * <protocol>http</protocol> <host>proxy.example.com</host> * <port>8080</port> <username>proxyuser</username> * <password>somepassword</password> * <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy> * </proxies> */ public SettingsParser(File file) throws Exception { super(file); parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies); parse("/settings/servers/server", ServerDTO.class, settings.servers); } public SettingsDTO getSettings() { return settings; } @Override protected String processValue(String value) { return replacer.process(value); } }
package aQute.bnd.connection.settings; import java.io.File; import aQute.lib.xpath.XPathParser; public class SettingsParser extends XPathParser { final SettingsDTO settings = new SettingsDTO(); /* * <proxies> <proxy> <id>example-proxy</id> <active>true</active> * <protocol>http</protocol> <host>proxy.example.com</host> * <port>8080</port> <username>proxyuser</username> * <password>somepassword</password> * <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy> * </proxies> */ public SettingsParser(File file) throws Exception { super(file); parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies); parse("/settings/servers/server", ServerDTO.class, settings.servers); } public SettingsDTO getSettings() { return settings; } }
Use arrow function to define rendering methods
import renderer from './mixins/renderer' import rules from './mixins/rules' export default function(md, target, opts = {}) { const options = { incrementalizeDefaultRules: true, ...opts } const incrementalDOM = !target && window ? window.IncrementalDOM : target const mixin = renderer(incrementalDOM) Object.defineProperty(md, 'IncrementalDOMRenderer', { get() { const extended = Object.assign( Object.create(Object.getPrototypeOf(md.renderer)), md.renderer, mixin ) if (options.incrementalizeDefaultRules) { extended.rules = { ...extended.rules, ...rules(incrementalDOM) } } return extended }, }) md.renderToIncrementalDOM = (src, env = {}) => md.IncrementalDOMRenderer.render(md.parse(src, env), md.options, env) md.renderInlineToIncrementalDOM = (src, env = {}) => md.IncrementalDOMRenderer.render(md.parseInline(src, env), md.options, env) }
import renderer from './mixins/renderer' import rules from './mixins/rules' export default function(md, target, opts = {}) { const options = { incrementalizeDefaultRules: true, ...opts } const incrementalDOM = !target && window ? window.IncrementalDOM : target const mixin = renderer(incrementalDOM) Object.defineProperty(md, 'IncrementalDOMRenderer', { get() { const extended = Object.assign( Object.create(Object.getPrototypeOf(this.renderer)), this.renderer, mixin ) if (options.incrementalizeDefaultRules) { extended.rules = { ...extended.rules, ...rules(incrementalDOM) } } return extended }, }) md.renderToIncrementalDOM = function(src, env = {}) { return this.IncrementalDOMRenderer.render( this.parse(src, env), this.options, env ) } md.renderInlineToIncrementalDOM = function(src, env = {}) { return this.IncrementalDOMRenderer.render( this.parseInline(src, env), this.options, env ) } }
feat: Add pagination to build index
from sqlalchemy.orm import joinedload, subqueryload_all from zeus import auth from zeus.models import Build from .base import Resource from ..schemas import BuildSchema builds_schema = BuildSchema(many=True, strict=True) class BuildIndexResource(Resource): def get(self): """ Return a list of builds. """ # tenants automatically restrict this query but we dont want # to include public repos tenant = auth.get_current_tenant() if not tenant.repository_ids: return self.respond([]) query = Build.query.options( joinedload('repository'), joinedload('source'), joinedload('source').joinedload('author'), joinedload('source').joinedload('revision'), joinedload('source').joinedload('patch'), subqueryload_all('stats'), ).filter( Build.repository_id.in_(tenant.repository_ids), ).order_by(Build.date_created.desc()) return self.paginate_with_schema(builds_schema, query)
from sqlalchemy.orm import joinedload, subqueryload_all from zeus import auth from zeus.models import Build from .base import Resource from ..schemas import BuildSchema builds_schema = BuildSchema(many=True, strict=True) class BuildIndexResource(Resource): def get(self): """ Return a list of builds. """ # tenants automatically restrict this query but we dont want # to include public repos tenant = auth.get_current_tenant() if not tenant.repository_ids: return self.respond([]) query = Build.query.options( joinedload('repository'), joinedload('source'), joinedload('source').joinedload('author'), joinedload('source').joinedload('revision'), joinedload('source').joinedload('patch'), subqueryload_all('stats'), ).filter( Build.repository_id.in_(tenant.repository_ids), ).order_by(Build.date_created.desc()).limit(100) return self.respond_with_schema(builds_schema, query)
Add new line after error message
module.exports = handler var debug = require('../debug').server var fs = require('fs') function handler (err, req, res, next) { debug('Error page because of ' + err.message) var ldp = req.app.locals.ldp // If the user specifies this function // then, they can customize the error programmatically if (ldp.errorHandler) { return ldp.errorHandler(err, req, res, next) } // If noErrorPages is set, // then use built-in express default error handler if (ldp.noErrorPages) { return res .status(err.status) .send(err.message + "\n" || '') } // Check if error page exists var errorPage = ldp.errorPages + err.status.toString() + '.html' fs.readFile(errorPage, 'utf8', function (readErr, text) { if (readErr) { return res .status(err.status) .send(err.message || '') } res.status(err.status) res.header('Content-Type', 'text/html') res.send(text) }) }
module.exports = handler var debug = require('../debug').server var fs = require('fs') function handler (err, req, res, next) { debug('Error page because of ' + err.message) var ldp = req.app.locals.ldp // If the user specifies this function // then, they can customize the error programmatically if (ldp.errorHandler) { return ldp.errorHandler(err, req, res, next) } // If noErrorPages is set, // then use built-in express default error handler if (ldp.noErrorPages) { return res .status(err.status) .send(err.message || '') } // Check if error page exists var errorPage = ldp.errorPages + err.status.toString() + '.html' fs.readFile(errorPage, 'utf8', function (readErr, text) { if (readErr) { return res .status(err.status) .send(err.message || '') } res.status(err.status) res.header('Content-Type', 'text/html') res.send(text) }) }
Use console.error for extra severity
/*jslint indent:2, white:true, node:true, sloppy:true*/ var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(process.env.PORT || 8080); app.get('/', function(req, res) { res.status(200).send('Hello; socket.io!\n'); }); // Safe replacement for .bind() that also catches any errors. // This is used to ensure that malformed client messages do not trigger an // uncaught exception. function safe(f, context) { return function() { try { return f.apply(context, arguments); } catch (e) { console.error('Safe error:', e); } }; } var doEmit = safe(function(e) { io.sockets.to(e['room']).emit('message', e['msg']); }); io.on('connection', function(socket) { socket.on('join', safe(socket.join, socket)); socket.on('leave', safe(socket.leave, socket)); socket.on('emit', doEmit); var disconnectMessages = []; socket.on('addDisconnectMessage', function(e) { disconnectMessages.push(e); }); socket.on('disconnect', function() { disconnectMessages.forEach(doEmit); }); // See https://www.joyent.com/developers/node/design/errors socket.on('error', function(err) { console.log('Error:', err); }); });
/*jslint indent:2, white:true, node:true, sloppy:true*/ var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(process.env.PORT || 8080); app.get('/', function(req, res) { res.status(200).send('Hello; socket.io!\n'); }); // Safe replacement for .bind() that also catches any errors. // This is used to ensure that malformed client messages do not trigger an // uncaught exception. function safe(f, context) { return function() { try { return f.apply(context, arguments); } catch (e) { console.log('Safe error:', e); } }; } var doEmit = safe(function(e) { io.sockets.to(e['room']).emit('message', e['msg']); }); io.on('connection', function(socket) { socket.on('join', safe(socket.join, socket)); socket.on('leave', safe(socket.leave, socket)); socket.on('emit', doEmit); var disconnectMessages = []; socket.on('addDisconnectMessage', function(e) { disconnectMessages.push(e); }); socket.on('disconnect', function() { disconnectMessages.forEach(doEmit); }); // See https://www.joyent.com/developers/node/design/errors socket.on('error', function(err) { console.log('Error:', err); }); });
Make stack frame handling more explicit
/* jshint -W027, unused:false */ 'use strict'; var _R; // Return register var _S = []; // Stack frame data var _SP = 0; // Beginning of current stack frame var _SQ = 0; // End of current stack frame var _SR = 0; // Current stack frame reference var _PSP = []; // Beginnings of previous stack frames var _A = []; // Array frame data var _AP = 0; // Beginning of current array frame function idris_pushFrame() { _PSP[_SR] = _SP; _SP = _SQ; _SR += 1; for (var i = 0; i < arguments.length; i += 1, _SQ += 1) { _S[_SQ] = arguments[i]; } } function idris_popFrame() { _SQ = _SP; _SR -= 1; _SP = _PSP[_SR]; } function idris_growFrame(i) { if (_SQ < _SP + i) { _SQ = _SP + i; } } function idris_makeArray() { _R = _AP; for (var i = 0; i < arguments.length; i += 1, _AP += 1) { _A[_AP] = arguments[i]; } } function idris_error(s) { throw s; } function idris_writeStr(s) { console.log(s); }
/* jshint -W027, unused:false */ 'use strict'; var _R; // Return register var _S = []; // Stack frame data var _SP = 0; // Beginning of current stack frame var _SQ = 0; // End of current stack frame var _PSP = []; // Beginnings of previous stack frames var _A = []; // Array frame data var _AP = 0; // Beginning of current array frame function idris_pushFrame() { _PSP.push(_SP); _SP = _SQ; for (var i = 0; i < arguments.length; i += 1, _SQ += 1) { _S[_SQ] = arguments[i]; } } function idris_popFrame() { _SQ = _SP; _SP = _PSP.pop(); } function idris_growFrame(i) { _SQ = Math.max(_SQ, _SP + i); } function idris_makeArray() { _R = _AP; for (var i = 0; i < arguments.length; i += 1, _AP += 1) { _A[_AP] = arguments[i]; } } function idris_error(s) { throw s; } function idris_writeStr(s) { console.log(s); }