text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Check membership when a Member is saved
import datetime from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.db.models.signals import pre_save from django.dispatch import receiver from django.template import loader from django.utils import timezone from simple_email_confirmation import unconfirmed_email_created from members.models import Member @receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation') def send_confirmation_email(sender, email, user=None, **kwargs): member = user context = { 'email': email, 'domain': settings.BASE_URL, 'site_name': settings.WAGTAIL_SITE_NAME, 'token': member.get_confirmation_key(email), } subject = loader.render_to_string( 'members/email_change_subject.txt', context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string('members/email_change_email.html', context) email_message = EmailMultiAlternatives(subject, body, None, [email]) email_message.send() @receiver(pre_save, sender=Member, dispatch_uid='member_check_membership') def check_membership(sender, instance, **kwargs): if timezone.now() - instance.status_changed > datetime.timedelta(1): instance.update_status()
from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.dispatch import receiver from django.template import loader from simple_email_confirmation import unconfirmed_email_created @receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation') def send_confirmation_email(sender, email, user=None, **kwargs): member = user or sender context = { 'email': email, 'domain': settings.BASE_URL, 'site_name': settings.WAGTAIL_SITE_NAME, 'token': member.get_confirmation_key(email), } subject = loader.render_to_string( 'members/email_change_subject.txt', context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string('members/email_change_email.html', context) email_message = EmailMultiAlternatives(subject, body, None, [email]) email_message.send()
Fix compilation on OS X As OS X doesn't have it's own interrupts provider, don't build interrupts_common on OS X as well. Otherwise build fails, because interrupts_common depends on variables provided by platform-specific files. Signed-off-by: Pavel Borzenkov <073b1820d4178210f16262dddeb2ba44fb7467d3@gmail.com>
// Copyright 2015 The Prometheus 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. // +build !nointerrupts // +build !darwin package collector import "github.com/prometheus/client_golang/prometheus" type interruptsCollector struct { metric *prometheus.CounterVec } func init() { Factories["interrupts"] = NewInterruptsCollector } // Takes a prometheus registry and returns a new Collector exposing // interrupts stats func NewInterruptsCollector() (Collector, error) { return &interruptsCollector{ metric: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "interrupts", Help: "Interrupt details.", }, interruptLabelNames, ), }, nil }
// Copyright 2015 The Prometheus 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. // +build !nointerrupts package collector import "github.com/prometheus/client_golang/prometheus" type interruptsCollector struct { metric *prometheus.CounterVec } func init() { Factories["interrupts"] = NewInterruptsCollector } // Takes a prometheus registry and returns a new Collector exposing // interrupts stats func NewInterruptsCollector() (Collector, error) { return &interruptsCollector{ metric: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "interrupts", Help: "Interrupt details.", }, interruptLabelNames, ), }, nil }
Use the png module in test.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest import faint from faint import png import os import py_ext_tests class TestPng(unittest.TestCase): def test_write_png(self): out_dir = py_ext_tests.make_test_dir(self) b1 = faint.Bitmap((5,7)) b1.set_pixel((0,0),(255,0,255)) fn = os.path.join(out_dir, "b1.png") faint.write_png(b1, fn, png.RGB) b2, tEXt = faint.read_png(fn) self.assertEqual(b2.get_size(), (5,7)) self.assertEqual(tEXt, {}) def test_bad_args(self): with self.assertRaises(TypeError): faint.write_png("not a bitmap", py_ext_tests.make_test_dir(self), 0)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest import faint import os import py_ext_tests class TestPng(unittest.TestCase): def test_write_png(self): out_dir = py_ext_tests.make_test_dir(self) b1 = faint.Bitmap((5,7)) b1.set_pixel((0,0),(255,0,255)) fn = os.path.join(out_dir, "b1.png") faint.write_png(b1, fn, 0) b2, tEXt = faint.read_png(fn) self.assertEqual(b2.get_size(), (5,7)) self.assertEqual(tEXt, {}) def test_bad_args(self): with self.assertRaises(TypeError): faint.write_png("not a bitmap", py_ext_tests.make_test_dir(self), 0)
Add update to useReducer comments Co-Authored-By: Chris Petty <637933a5c948ed3d23257417b9455449bf8cfd77@gmail.com>
import { useReducer, useCallback } from 'react'; import getReducer from '../pages/dataTableUtilities/reducer/getReducer'; import getColumns from '../pages/dataTableUtilities/columns'; import { debounce } from '../utilities/index'; /** * useReducer wrapper for pages within the app. Creates a * composed reducer through getReducer for a paraticular * page as well as fetching the required columns and inserting * them into the initial state of the component. * * Returns the current state as well as three dispatchers for * actions to the reducer - a regular dispatch and two debounced * dispatchers - which group sequential calls within the timeout * period, call either the last invocation or the first within * the timeout period. * @param {String} page routeName for the current page. * @param {Object} initialState Initial state of the reducer * @param {Number} debounceTimeout Timeout period for a regular debounce * @param {Number} instantDebounceTimeout Timeout period for an instant debounce */ const usePageReducer = ( page, initialState, debounceTimeout = 250, instantDebounceTimeout = 250 ) => { const columns = getColumns(page); const [state, dispatch] = useReducer(getReducer(page), { ...initialState, columns }); const debouncedDispatch = useCallback(debounce(dispatch, debounceTimeout), []); const instantDebouncedDispatch = useCallback( debounce(dispatch, instantDebounceTimeout, true), [] ); return [state, dispatch, instantDebouncedDispatch, debouncedDispatch]; }; export default usePageReducer;
import { useReducer, useCallback } from 'react'; import getReducer from '../pages/dataTableUtilities/reducer/getReducer'; import getColumns from '../pages/dataTableUtilities/columns'; import { debounce } from '../utilities/index'; /** * useReducer wrapper for pages within the app. Creaates a * composed reducer through getReducer for a paraticular * page as well as fetching the required columns and inserting * them into the initial state of the component. * * Returns the current state as well as three dispatchers for * actions to the reducer - a regular dispatch and two debounced * dispatchers - which group sequential calls within the timeout * period, call either the last invocation or the first within * the timeout period. * @param {String} page routeName for the current page. * @param {Object} initialState Initial state of the reducer * @param {Number} debounceTimeout Timeout period for a regular debounce * @param {Number} instantDebounceTimeout Timeout period for an instant debounce */ const usePageReducer = ( page, initialState, debounceTimeout = 250, instantDebounceTimeout = 250 ) => { const columns = getColumns(page); const [state, dispatch] = useReducer(getReducer(page), { ...initialState, columns }); const debouncedDispatch = useCallback(debounce(dispatch, debounceTimeout), []); const instantDebouncedDispatch = useCallback( debounce(dispatch, instantDebounceTimeout, true), [] ); return [state, dispatch, instantDebouncedDispatch, debouncedDispatch]; }; export default usePageReducer;
Fix up wmata controller tests
/* eslint-env mocha */ const redisMock = require('redis-mock'); const chai = require('chai'); chai.should(); const db = { redis: redisMock.createClient(), }; const fakeRedis = redisMock.createClient(); const wmata = require('../../controllers/wmata.js')(db); describe('WMATA Controllers - ', () => { it('Method get_metadata() should acquire rail metadata.', (done) => { wmata.get_metadata(() => { let value = db.redis.get('wmata_metadata'); done(); }); }); it('Method get_stations_list() should acquire rail metadata.', (done) => { wmata.get_stations_list('RD', () => { let value = db.redis.get('wmata_line_RD'); done(); }); }); it('Method get_stations_status() should acquire rail metadata.', (done) => { wmata.get_stations_status(() => { let value = db.redis.get('wmata_realtime_status'); done(); }); }); });
/* eslint-env mocha */ const redisMock = require('redis-mock'); const chai = require('chai'); chai.should(); const db = { redis: redisMock.createClient(), }; const fakeRedis = redisMock.createClient(); const wmata = require('../../controllers/wmata.js')(db); describe('WMATA Controllers - ', () => { it('Method get_metadata() should acquire rail metadata.', (done) => { wmata.get_metadata(() => { let value = fakeRedis.get('wmata_metadata'); done(); }); }); it('Method get_stations_list() should acquire rail metadata.', (done) => { wmata.get_stations_list('RD', () => { let value = fakeRedis.get('wmata_line_RD'); done(); }); }); it('Method get_stations_status() should acquire rail metadata.', (done) => { wmata.get_stations_status(() => { let value = fakeRedis.get('wmata_metadata'); done(); }); }); });
[KARAF-1109] Update the archetypes itest to reflect the new karaf-command-archetype artifactId git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1214843 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.archetypes; import java.util.Properties; public class CommandArchetypeTest extends AbstractArchetypeTest { public void testCommand() throws Exception { Properties commandArchetypeParameters = new Properties(); commandArchetypeParameters.setProperty("scope", "testscope"); commandArchetypeParameters.setProperty("command", "testcommand"); commandArchetypeParameters.setProperty("description", "testdescription"); testKarafArchetype("karaf-command-archetype", commandArchetypeParameters); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.archetypes; import java.util.Properties; public class CommandArchetypeTest extends AbstractArchetypeTest { public void testCommand() throws Exception { Properties commandArchetypeParameters = new Properties(); commandArchetypeParameters.setProperty("scope", "testscope"); commandArchetypeParameters.setProperty("command", "testcommand"); commandArchetypeParameters.setProperty("description", "testdescription"); testKarafArchetype("archetypes-command", commandArchetypeParameters); } }
docs(gh-pages): Fix refresh 404 with hash URL
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', contentSecurityPolicy: { 'img-src': "'self' data: emberjs.com assets-cdn.github.com", }, EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-bulma'; ENV.locationType = 'hash'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', contentSecurityPolicy: { 'img-src': "'self' data: emberjs.com assets-cdn.github.com", }, EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-bulma'; } return ENV; };
Add message if you're using default settings
# Copyright 2014 0xc0170 # # 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 logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: logging.info("Using default settings.")
# Copyright 2014 0xc0170 # # 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 logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: pass
Update wiki link for new year
import React from 'react'; const Fadder = () => { return ( <div id="fadder"> <div className="component fadder-content"> <div className="fadder-description"> <h1>Fadderukene.</h1> <p> I fadderukene skal du få bli kjent med både linjeforeningen, NTNU og mange medstudenter. Dette er den viktigste portalen for å stifte bekjentskaper som varer studietiden ut. Vi i Online anbefaler alle å ta del i det supre fadderopplegget vårt! </p> <p>Fadderukene starter den 12. august etter immatrikuleringen for både bachelor og master.</p> <p> For praktisk info rundt fadderukene se{' '} <a href="https://online.ntnu.no/wiki/online/fadderukene/2020-/">her</a> </p> </div> </div> </div> ); }; export default Fadder;
import React from 'react'; const Fadder = () => { return ( <div id="fadder"> <div className="component fadder-content"> <div className="fadder-description"> <h1>Fadderukene.</h1> <p> I fadderukene skal du få bli kjent med både linjeforeningen, NTNU og mange medstudenter. Dette er den viktigste portalen for å stifte bekjentskaper som varer studietiden ut. Vi i Online anbefaler alle å ta del i det supre fadderopplegget vårt! </p> <p>Fadderukene starter den 12. august etter immatrikuleringen for både bachelor og master.</p> <p> For praktisk info rundt fadderukene se{' '} <a href="https://online.ntnu.no/wiki/online/fadderukene/2019-/">her</a> </p> </div> </div> </div> ); }; export default Fadder;
Add enum value `start` used for files with pending multipart upload.
package synapticloop.b2; /* * Copyright (c) 2016 synapticloop. * * All rights reserved. * * This code may contain contributions from other parties which, where * applicable, will be listed in the default build file for the project * ~and/or~ in a file named CONTRIBUTORS.txt in the root of the project. * * This source code and any derived binaries are covered by the terms and * conditions of the Licence agreement ("the Licence"). You may not use this * source code or any derived binaries except in compliance with the Licence. * A copy of the Licence is available in the file named LICENSE.txt shipped with * this source code or binaries. */ /** * The action for an associated file, either 'hide' or 'upload', "upload" means * a file that was uploaded to B2 Cloud Storage. "hide" means a file version * marking the file as hidden, so that it will not show up in b2_list_file_names. * * The result of b2_list_file_names will contain only "upload". The result of * b2_list_file_versions may have both. * * @author synapticloop */ public enum Action { hide, upload, start }
package synapticloop.b2; /* * Copyright (c) 2016 synapticloop. * * All rights reserved. * * This code may contain contributions from other parties which, where * applicable, will be listed in the default build file for the project * ~and/or~ in a file named CONTRIBUTORS.txt in the root of the project. * * This source code and any derived binaries are covered by the terms and * conditions of the Licence agreement ("the Licence"). You may not use this * source code or any derived binaries except in compliance with the Licence. * A copy of the Licence is available in the file named LICENSE.txt shipped with * this source code or binaries. */ /** * The action for an associated file, either 'hide' or 'upload', "upload" means * a file that was uploaded to B2 Cloud Storage. "hide" means a file version * marking the file as hidden, so that it will not show up in b2_list_file_names. * * The result of b2_list_file_names will contain only "upload". The result of * b2_list_file_versions may have both. * * @author synapticloop */ public enum Action { hide, upload }
Make doc blocks bc compliant
<?php /** * Copyright 2016 SURFnet B.V. * * 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. */ namespace Surfnet\SamlBundle\SAML2\Attribute; use SAML2_Assertion; interface AttributeSetFactory { /** * @param SAML2_Assertion $assertion * @param AttributeDictionary $attributeDictionary * @return AttributeSet * * @deprecated Will be replaced with different creation implementation */ public static function createFrom(SAML2_Assertion $assertion, AttributeDictionary $attributeDictionary); /** * @param Attribute[] $attributes * @return AttributeSet * * @deprecated Will be replaced with different creation implementation */ public static function create(array $attributes); }
<?php /** * Copyright 2016 SURFnet B.V. * * 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. */ namespace Surfnet\SamlBundle\SAML2\Attribute; use SAML2_Assertion; interface AttributeSetFactory { /** * @param SAML2_Assertion $assertion * @param AttributeDictionary $attributeDictionary * @return AttributeSetInterface * * @deprecated Will be replaced with different creation implementation */ public static function createFrom(SAML2_Assertion $assertion, AttributeDictionary $attributeDictionary); /** * @param Attribute[] $attributes * @return AttributeSetInterface * * @deprecated Will be replaced with different creation implementation */ public static function create(array $attributes); }
Add important withCredentials flag to API calls
import axios from 'axios'; import createApiUrl from 'helpers/createApiUrl'; import queryParams from 'query-params'; const apiUrl = (requestPath) => { const prefix = process.env.API_URL; if (!prefix) { throw new Error('Please define an API_URL in .env'); } return createApiUrl(prefix, requestPath); }; export default { request: (requestPath = '', data = {}, method = 'GET') => { if (method === 'GET') { const requestParams = queryParams.encode(data); if (requestParams.length > 0) { requestPath += `?${requestParams}`; data = {}; } } return axios({ method: method, url: apiUrl(requestPath), data: data, withCredentials: true }); } };
import axios from 'axios'; import createApiUrl from 'helpers/createApiUrl'; import queryParams from 'query-params'; const apiUrl = (requestPath) => { const prefix = process.env.API_URL; if (!prefix) { throw new Error('Please define an API_URL in .env'); } return createApiUrl(prefix, requestPath); }; export default { request: (requestPath = '', data = {}, method = 'GET') => { if (method === 'GET') { const requestParams = queryParams.encode(data); if (requestParams.length > 0) { requestPath += `?${requestParams}`; data = {}; } } return axios({ method: method, url: apiUrl(requestPath), data: data }); } };
Add map argument to PostCSSPlugin constructor And simplify the default options
var PostcssCompiler = require('broccoli-postcss'); var checker = require('ember-cli-version-checker'); // PostCSSPlugin constructor function PostCSSPlugin (options) { this.name = 'ember-cli-postcss'; this.options = options; this.plugins = options.plugins; this.map = options.map; } PostCSSPlugin.prototype.toTree = function (tree, inputPath, outputPath) { var trees = [tree]; if (this.options.includePaths) { trees = trees.concat(this.options.includePaths); } inputPath += '/' + this.options.inputFile; outputPath += '/' + this.options.outputFile; return new PostcssCompiler(trees, inputPath, outputPath, this.plugins, this.map); }; module.exports = { name: 'Ember CLI Postcss', shouldSetupRegistryInIncluded: function() { return !checker.isAbove(this, '0.2.0'); }, included: function included (app) { this.app = app; // Initialize options if none were passed var options = app.options.postcssOptions || {}; // Set defaults if none were passed options.map = options.map || {}; options.plugins = options.plugins || []; options.inputFile = options.inputFile || 'app.css'; options.outputFile = options.outputFile || this.project.name() + '.css'; // Add to registry and pass options app.registry.add('css', new PostCSSPlugin(options)); if (this.shouldSetupRegistryInIncluded()) { this.setupPreprocessorRegistry('parent', app.registry); } } };
var PostcssCompiler = require('broccoli-postcss'); var checker = require('ember-cli-version-checker'); function PostCSSPlugin (plugins, options) { this.name = 'ember-cli-postcss'; options = options || {}; options.inputFile = options.inputFile || 'app.css'; options.outputFile = options.outputFile || 'app.css'; this.options = options; this.plugins = plugins; } PostCSSPlugin.prototype.toTree = function (tree, inputPath, outputPath) { var trees = [tree]; if (this.options.includePaths) { trees = trees.concat(this.options.includePaths); } inputPath += '/' + this.options.inputFile; outputPath += '/' + this.options.outputFile; return new PostcssCompiler(trees, inputPath, outputPath, this.plugins); }; module.exports = { name: 'Ember CLI Postcss', shouldSetupRegistryInIncluded: function() { return !checker.isAbove(this, '0.2.0'); }, included: function included (app) { this.app = app; var options = app.options.postcssOptions || {}; var plugins = this.plugins = options.plugins || []; options.outputFile = options.outputFile || this.project.name() + '.css'; app.registry.add('css', new PostCSSPlugin(plugins, options)); if (this.shouldSetupRegistryInIncluded()) { this.setupPreprocessorRegistry('parent', app.registry); } } };
Test exception handling in `check_database`
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-watchman ------------ Tests for `django-watchman` views module. """ import json import unittest from mock import patch from watchman import views class TestWatchman(unittest.TestCase): def setUp(self): pass @patch('watchman.views.check_databases') def test_response_content_type_json(self, patched_check_databases): patched_check_databases.return_value = [] response = views.status('') self.assertEqual(response['Content-Type'], 'application/json') @patch('watchman.views.check_databases') def test_response_contains_expected_checks(self, patched_check_databases): expected_checks = ['databases'] patched_check_databases.return_value = [] response = views.status('') content = json.loads(response.content) self.assertItemsEqual(expected_checks, content.keys()) def test_check_database_handles_exception(self): response = views.check_database('foo') self.assertFalse(response['foo']['ok']) self.assertEqual(response['foo']['error'], "The connection foo doesn't exist") def tearDown(self): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-watchman ------------ Tests for `django-watchman` views module. """ import json import unittest from mock import patch from watchman import views class TestWatchman(unittest.TestCase): def setUp(self): pass @patch('watchman.views.check_databases') def test_response_content_type_json(self, patched_check_databases): patched_check_databases.return_value = [] response = views.status('') self.assertEqual(response['Content-Type'], 'application/json') @patch('watchman.views.check_databases') def test_response_contains_expected_checks(self, patched_check_databases): expected_checks = ['databases'] patched_check_databases.return_value = [] response = views.status('') content = json.loads(response.content) self.assertItemsEqual(expected_checks, content.keys()) def tearDown(self): pass
Fix Charged Hammer / Lightning Jolt
from ..utils import * ## # Minions # Tuskarr Totemic class AT_046: play = Summon(CONTROLLER, RandomTotem()) # Draenei Totemcarver class AT_047: play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM) # Thunder Bluff Valiant class AT_049: inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e") # The Mistcaller class AT_054: # The Enchantment ID is correct play = Buff(FRIENDLY + (IN_DECK | IN_HAND), "AT_045e") ## # Spells # Healing Wave class AT_048: play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14) # Elemental Destruction class AT_051: play = Hit(ALL_MINIONS, RandomNumber(4, 5)) # Ancestral Knowledge class AT_053: play = Draw(CONTROLLER) * 2 ## # Weapons # Charged Hammer class AT_050: deathrattle = Summon(CONTROLLER, "AT_050t") class AT_050t: activate = Hit(TARGET, 2)
from ..utils import * ## # Hero Powers # Lightning Jolt class AT_050t: play = Hit(TARGET, 2) ## # Minions # Tuskarr Totemic class AT_046: play = Summon(CONTROLLER, RandomTotem()) # Draenei Totemcarver class AT_047: play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM) # Thunder Bluff Valiant class AT_049: inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e") # The Mistcaller class AT_054: # The Enchantment ID is correct play = Buff(FRIENDLY + (IN_DECK | IN_HAND), "AT_045e") ## # Spells # Healing Wave class AT_048: play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14) # Elemental Destruction class AT_051: play = Hit(ALL_MINIONS, RandomNumber(4, 5)) # Ancestral Knowledge class AT_053: play = Draw(CONTROLLER) * 2 ## # Weapons # Charged Hammer class AT_050: deathrattle = Summon(CONTROLLER, "AT_050t")
Add existence check for dash source Safari complains about removing a non-existent child.
import {browser} from '../browser'; export const filterSources = function(playerElement) { if (playerElement.tagName.toLowerCase() !== 'video') { return playerElement; } var changed = false; if (browser.has('mp4 support only')) { // keep only mp4 source playerElement.querySelectorAll('source').forEach(source => { if(source.type !== 'video/mp4') { playerElement.removeChild(source); } }); changed = true; } else if (browser.has('mse and native hls support')) { // remove dash source to ensure hls is used const dashSource = playerElement.querySelector('source[type="application/dash+xml"]'); if(dashSource) { playerElement.removeChild(dashSource); changed = true; } } if (changed) { // the video tags initially in the dom are broken since they "saw" // the other sources. replace with clone var clone = playerElement.cloneNode(true); playerElement.replaceWith(clone); return clone; } else { return playerElement; } };
import {browser} from '../browser'; export const filterSources = function(playerElement) { if (playerElement.tagName.toLowerCase() !== 'video') { return playerElement; } var changed = false; if (browser.has('mp4 support only')) { // keep only mp4 source playerElement.querySelectorAll('source').forEach(source => { if(source.type !== 'video/mp4') { playerElement.removeChild(source); } }); changed = true; } else if (browser.has('mse and native hls support')) { // remove dash source to ensure hls is used const dashSource = playerElement.querySelector('source[type="application/dash+xml"]'); playerElement.removeChild(dashSource); changed = true; } if (changed) { // the video tags initially in the dom are broken since they "saw" // the other sources. replace with clone var clone = playerElement.cloneNode(true); playerElement.replaceWith(clone); return clone; } else { return playerElement; } };
Add entity id to sync message.
package aeronicamc.mods.mxtune.caps; import aeronicamc.mods.mxtune.managers.PlayIdSupplier; import aeronicamc.mods.mxtune.network.PacketDispatcher; import aeronicamc.mods.mxtune.network.messages.LivingEntityModCapSync; import net.minecraft.entity.LivingEntity; import net.minecraft.util.RegistryKey; import net.minecraft.world.World; import javax.annotation.Nullable; public class LivingEntityModCap implements ILivingEntityModCap { private int playId = PlayIdSupplier.PlayType.INVALID.getAsInt(); private final LivingEntity entity; LivingEntityModCap(@Nullable final LivingEntity entity) { this.entity = entity; } @Override public void setPlayId(int playId) { this.playId = playId; synchronize(); } @Override public int getPlayId() { return playId; } @Override public void synchronize() { if (entity == null) return; World world = entity.level; if (world.isClientSide) return; RegistryKey<World> dimension = world.dimension(); PacketDispatcher.sendToDimension(new LivingEntityModCapSync(playId, entity.getId()), dimension); } }
package aeronicamc.mods.mxtune.caps; import aeronicamc.mods.mxtune.managers.PlayIdSupplier; import aeronicamc.mods.mxtune.network.PacketDispatcher; import aeronicamc.mods.mxtune.network.messages.LivingEntityModCapSync; import net.minecraft.entity.LivingEntity; import net.minecraft.util.RegistryKey; import net.minecraft.world.World; import javax.annotation.Nullable; public class LivingEntityModCap implements ILivingEntityModCap { private int playId = PlayIdSupplier.PlayType.INVALID.getAsInt(); private final LivingEntity entity; LivingEntityModCap(@Nullable final LivingEntity entity) { this.entity = entity; } @Override public void setPlayId(int playId) { this.playId = playId; synchronize(); } @Override public int getPlayId() { return playId; } @Override public void synchronize() { if (entity == null) return; World world = entity.level; if (world.isClientSide) return; RegistryKey<World> dimension = world.dimension(); PacketDispatcher.sendToDimension(new LivingEntityModCapSync(playId), dimension); } }
Test all rules but refnames.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check the rules """ import os import pkg_resources import json import re import seabird def test_load_available_rules(): """ Try to read all available rules https://github.com/castelao/seabird/issues/7 """ rules_dir = 'rules' rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir) rule_files = [f for f in rule_files if re.match('^(?!refnames).*json$', f)] for rule_file in rule_files: print("loading rule: %s", (rule_file)) text = pkg_resources.resource_string( seabird.__name__, os.path.join(rules_dir, rule_file)) rule = json.loads(text.decode('utf-8'), encoding="utf-8") assert type(rule) == dict assert len(rule.keys()) > 0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check the rules """ import os import pkg_resources import json import re import seabird def test_load_available_rules(): """ Try to read all available rules https://github.com/castelao/seabird/issues/7 """ rules_dir = 'rules' rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir) rule_files = [f for f in rule_files if re.match('^cnv.*json$', f)] for rule_file in rule_files: print("loading rule: %s", (rule_file)) text = pkg_resources.resource_string( seabird.__name__, os.path.join(rules_dir, rule_file)) rule = json.loads(text.decode('utf-8'), encoding="utf-8") assert type(rule) == dict assert len(rule.keys()) > 0
Use an identity with test data.
package com.facetedworlds.honeydolist.collaboration; import android.app.Activity; import com.facetedworlds.honeydolist.ActivityTaskDispatcher; import com.updatecontrols.correspondence.Community; import com.updatecontrols.correspondence.CorrespondenceException; import com.updatecontrols.correspondence.binary.BinaryHTTPAsynchronousCommunicationStrategy; import com.updatecontrols.correspondence.memory.MemoryStorageStrategy; import facetedworlds.honeydo.model.CorrespondenceModel; import facetedworlds.honeydo.model.Identity; public class SynchronizationService { private static SynchronizationService synchronizationService = new SynchronizationService(); public static SynchronizationService getInstance() { return synchronizationService; } private Identity identity; public void start(Activity context) throws CorrespondenceException { Community community = new Community(new MemoryStorageStrategy(), new ActivityTaskDispatcher(context)) .addAsynchronousCommunicationStrategy(new BinaryHTTPAsynchronousCommunicationStrategy( new HoneyDoHTTPConfigurationProvider() )) .addModule(new CorrespondenceModel()); identity = community.addFact(new Identity("547260202db74f018050e01a6e384112")); community.subscribe(new HoneyDoSubscriptionStrategy(identity)); community.beginReceiving(); } public Identity getIdentity() { return identity; } }
package com.facetedworlds.honeydolist.collaboration; import android.app.Activity; import com.facetedworlds.honeydolist.ActivityTaskDispatcher; import com.updatecontrols.correspondence.Community; import com.updatecontrols.correspondence.CorrespondenceException; import com.updatecontrols.correspondence.binary.BinaryHTTPAsynchronousCommunicationStrategy; import com.updatecontrols.correspondence.memory.MemoryStorageStrategy; import facetedworlds.honeydo.model.CorrespondenceModel; import facetedworlds.honeydo.model.Identity; public class SynchronizationService { private static SynchronizationService synchronizationService = new SynchronizationService(); public static SynchronizationService getInstance() { return synchronizationService; } private Identity identity; public void start(Activity context) throws CorrespondenceException { Community community = new Community(new MemoryStorageStrategy(), new ActivityTaskDispatcher(context)) .addAsynchronousCommunicationStrategy(new BinaryHTTPAsynchronousCommunicationStrategy( new HoneyDoHTTPConfigurationProvider() )) .addModule(new CorrespondenceModel()); identity = community.addFact(new Identity("c48b1883978543b5baa0eb89cb2516f9")); community.subscribe(new HoneyDoSubscriptionStrategy(identity)); community.beginReceiving(); } public Identity getIdentity() { return identity; } }
Send & read off a channel
package main import ( "fmt" "github.com/kidoman/embd" "bufio" "os" "strconv" "strings" "time" ) var blinker Blinker func output(c chan int) { seconds := <-c fmt.Printf("Outputting Hi for %d s\n", seconds) time.Sleep(time.Duration(seconds) * time.Second) fmt.Println("Finished outputting Hi") } func main() { var blinker Blinker c := make(chan int) go output(c) err := embd.InitGPIO() if err != nil { blinker = new (MockBlinker) } else { blinker = new (GPIOBlinker) } reader := bufio.NewReader(os.Stdin) for { fmt.Print("Enter number: ") text, _ := reader.ReadString('\n') intValue, err := strconv.Atoi(strings.TrimRight(text, "\n")) if err != nil { fmt.Println(err) } //fmt.Println(intValue) c <- intValue fmt.Println(blinker.Blink(intValue)) } } type Blinker interface { Blink(number int) string } type MockBlinker struct { } type GPIOBlinker struct { } func(mb MockBlinker) Blink(number int) string { return fmt.Sprintf("Mock Blink (%v)", number) } func(b GPIOBlinker) Blink(number int) string { return fmt.Sprintf("Sending signal to GPIO pin %d", number); }
package main import ( "fmt" "github.com/kidoman/embd" "bufio" "os" "strconv" "strings" ) var blinker Blinker func main() { var blinker Blinker err := embd.InitGPIO() if err != nil { blinker = new (MockBlinker) } else { blinker = new (GPIOBlinker) } reader := bufio.NewReader(os.Stdin) fmt.Print("Enter number: ") text, _ := reader.ReadString('\n') intValue, err := strconv.Atoi(strings.TrimRight(text, "\n")) if err != nil { fmt.Println(err) } fmt.Println(intValue) fmt.Println(blinker.Blink(intValue)) } type Blinker interface { Blink(number int) string } type MockBlinker struct { } type GPIOBlinker struct { } func(mb MockBlinker) Blink(number int) string { return fmt.Sprintf("Mock Blink (%v)", number) } func(b GPIOBlinker) Blink(number int) string { return fmt.Sprintf("Sending signal to GPIO pin %d", number); }
Add istanbul ignore. Line is tested. Istanbul isn't picking it up.
// @flow import type { MessageThemeContext } from './types' import React, { PureComponent } from 'react' import styled from '../styled' import Chat from './Chat' import classNames from '../../utilities/classNames' import css from './styles/Embed.css.js' type Props = { className?: string, html: string, } type Context = MessageThemeContext class Embed extends PureComponent<Props, Context> { static displayName = 'Message.Embed' render() { const { className, html, ...rest } = this.props const { theme } = this.context const componentClassName = classNames( 'c-MessageEmbed', /* istanbul ignore next */ // Tested, but Istanbul isn't picking it up. theme && `is-theme-${theme}`, className ) return ( <Chat {...rest} bubbleClassName="c-MessageEmbed__bubble" className={componentClassName} > <div dangerouslySetInnerHTML={{ __html: html }} className="c-MessageEmbed__html" /> </Chat> ) } } export default styled(Embed)(css)
// @flow import type { MessageThemeContext } from './types' import React, { PureComponent } from 'react' import styled from '../styled' import Chat from './Chat' import classNames from '../../utilities/classNames' import css from './styles/Embed.css.js' type Props = { className?: string, html: string, } type Context = MessageThemeContext class Embed extends PureComponent<Props, Context> { static displayName = 'Message.Embed' render() { const { className, html, ...rest } = this.props const { theme } = this.context const componentClassName = classNames( 'c-MessageEmbed', theme && `is-theme-${theme}`, className ) return ( <Chat {...rest} bubbleClassName="c-MessageEmbed__bubble" className={componentClassName} > <div dangerouslySetInnerHTML={{ __html: html }} className="c-MessageEmbed__html" /> </Chat> ) } } export default styled(Embed)(css)
Change My Library auth url
(function () { Polymer({ is: 'uql-apps-button', properties: { /** Whether to display title of the button */ showTitle: { type: Boolean, value: true }, /** Button title text */ buttonTitle: { type: String, value: "My Library" }, /** Value of redirect URL */ redirectUrl: { type: String, value: "https://www..library.uq.edu.au/mylibrary" } }, /** Redirects to the specified URL */ _myLibraryClicked: function() { window.location.href = this.redirectUrl; } }); })();
(function () { Polymer({ is: 'uql-apps-button', properties: { /** Whether to display title of the button */ showTitle: { type: Boolean, value: true }, /** Button title text */ buttonTitle: { type: String, value: "My Library" }, /** Value of redirect URL */ redirectUrl: { type: String, value: "https://app.library.uq.edu.au/auth/mylibrary" } }, /** Redirects to the specified URL */ _myLibraryClicked: function() { window.location.href = this.redirectUrl; } }); })();
Change progress callback to a function instead of null
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bcrypt = require('bcrypt-nodejs'); const userSchema = new Schema({ username: { type: String, lowercase: true, unique: true }, password: String, classes: [ { type: Schema.Types.ObjectId, ref: 'user-class' } ] }); // Generate a hash userSchema.pre('save', function(next) { let user = this; if( this.isModified('password') || this.isNew ) { bcrypt.genSalt(10, (err, salt) => { if(err) { return next(err); } bcrypt.hash(user.password, salt, () => {}, (err, hash) => { if(err) { return next(err); } user.password = hash; next(); }); }); } else { return next(); } }); // Method to compare password input to password saved in DB userSchema.methods.comparePassword = function(pw, cb) { bcrypt.compare(pw, this.password, (err, isMatch) => { if(err) { return cb(err); } cb(null, isMatch); }); }; module.exports = mongoose.model('user', userSchema);
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bcrypt = require('bcrypt-nodejs'); const userSchema = new Schema({ username: { type: String, lowercase: true, unique: true }, password: String, classes: [ { type: Schema.Types.ObjectId, ref: 'user-class' } ] }); // Generate a hash userSchema.pre('save', function(next) { let user = this; if( this.isModified('password') || this.isNew ) { bcrypt.genSalt(10, (err, salt) => { if(err) { return next(err); } bcrypt.hash(user.password, salt, null,(err, hash) => { if(err) { return next(err); } user.password = hash; next(); }); }); } else { return next(); } }); // Method to compare password input to password saved in DB userSchema.methods.comparePassword = function(pw, cb) { bcrypt.compare(pw, this.password, (err, isMatch) => { if(err) { return cb(err); } cb(null, isMatch); }); }; module.exports = mongoose.model('user', userSchema);
Remove an unnecessary use of the ProverMachineState rather than the MachineState. git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@280 716a755e-b13f-cedc-210d-596dafc6fb9b
package apps.server.visualization; import javax.swing.JPanel; import util.game.Game; import util.statemachine.MachineState; import util.xhtml.GameStateRenderPanel; public class RenderThread extends Thread { private final Game theGame; private final MachineState s; private final VisualizationPanel parent; private final int stepNum; public RenderThread(Game theGame, MachineState s, VisualizationPanel parent, int stepNum) { this.theGame = theGame; this.s = s; this.parent = parent; this.stepNum = stepNum; } @Override public void run() { JPanel newPanel = null; try { String XML = s.toXML(); String XSL = GameStateRenderPanel.getXSLfromFile(theGame.getKey(), 1); //1 because machinestate XMLs only ever have 1 state // TODO: Figure out a way to render visualizations using the web stylesheets. //String XSL = theGame.getStylesheet(); newPanel = new VizContainerPanel(XML, XSL, parent); } catch(Exception ex) {} if(newPanel != null) parent.addVizPanel(newPanel, stepNum); } }
package apps.server.visualization; import javax.swing.JPanel; import util.game.Game; import util.statemachine.implementation.prover.ProverMachineState; import util.xhtml.GameStateRenderPanel; public class RenderThread extends Thread { private final Game theGame; private final ProverMachineState s; private final VisualizationPanel parent; private final int stepNum; public RenderThread(Game theGame, ProverMachineState s, VisualizationPanel parent, int stepNum) { this.theGame = theGame; this.s = s; this.parent = parent; this.stepNum = stepNum; } @Override public void run() { JPanel newPanel = null; try { String XML = s.toXML(); String XSL = GameStateRenderPanel.getXSLfromFile(theGame.getKey(), 1); //1 because machinestate XMLs only ever have 1 state // TODO: Figure out a way to render visualizations using the web stylesheets. //String XSL = theGame.getStylesheet(); newPanel = new VizContainerPanel(XML, XSL, parent); } catch(Exception ex) {} if(newPanel != null) parent.addVizPanel(newPanel, stepNum); } }
Update CORS: fix cross-source cookie
package com.awesometickets.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * Cross-Origin Resource Sharing filter. */ public class CORSFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse)response; res.setHeader("Access-Control-Allow-Origin", "http://119.29.152.169"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); res.setHeader("Access-Control-Max-Age", "3600"); res.setHeader("Access-Control-Allow-Headers", "x-requested-with"); res.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response); } public void destroy() {} }
package com.awesometickets.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * Cross-Origin Resource Sharing filter. */ public class CORSFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse)response; res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); res.setHeader("Access-Control-Max-Age", "3600"); res.setHeader("Access-Control-Allow-Headers", "x-requested-with"); res.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response); } public void destroy() {} }
Index only FoiRequests marked is_foi
from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import FoiRequest class FoiRequestIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) title = indexes.CharField(model_attr='title') description = indexes.CharField(model_attr='description') resolution = indexes.CharField(model_attr='resolution', default="") status = indexes.CharField(model_attr='status') readable_status = indexes.CharField(model_attr='readable_status') first_message = indexes.DateTimeField(model_attr='first_message') last_message = indexes.DateTimeField(model_attr='last_message') url = indexes.CharField(model_attr='get_absolute_url') public_body_name = indexes.CharField(model_attr='public_body__name', default="") def get_model(self): return FoiRequest def index_queryset(self): """Used when the entire index for model is updated.""" return self.get_model().published.get_for_search_index() def should_update(self, instance, **kwargs): return instance.visibility > 1 and instance.is_foi
from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import FoiRequest class FoiRequestIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) title = indexes.CharField(model_attr='title') description = indexes.CharField(model_attr='description') resolution = indexes.CharField(model_attr='resolution', default="") status = indexes.CharField(model_attr='status') readable_status = indexes.CharField(model_attr='readable_status') first_message = indexes.DateTimeField(model_attr='first_message') last_message = indexes.DateTimeField(model_attr='last_message') url = indexes.CharField(model_attr='get_absolute_url') public_body_name = indexes.CharField(model_attr='public_body__name', default="") def get_model(self): return FoiRequest def index_queryset(self): """Used when the entire index for model is updated.""" return self.get_model().published.get_for_search_index() def should_update(self, instance, **kwargs): return instance.visibility > 1
Add bed_type to cnes_establishment model
from sqlalchemy import Column, Integer, String, func from app import db class CnesBed(db.Model): __tablename__ = 'cnes_bed' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) bed_type = Column(String(7), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', ] @classmethod def aggregate(cls, value): return { 'beds': func.count() }[value] @classmethod def values(cls): return ['beds']
from sqlalchemy import Column, Integer, String, func from app import db class CnesBed(db.Model): __tablename__ = 'cnes_bed' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', ] @classmethod def aggregate(cls, value): return { 'beds': func.count(cls.cnes) }[value] @classmethod def values(cls): return ['beds']
Use preg_replace_callback instead of \e to avoid an E_DEPRECATED on php-5.5alpha
<?php namespace mageekguy\atoum; class configurator { protected $script = null; protected $methods = array(); public function __construct(scripts\runner $script) { $this->script = $script; foreach ($this->script->getHelp() as $help) { list($arguments, $values) = $help; foreach ($arguments as $argument) { $this->methods[preg_replace_callback('/-(.)/', function($matches) { return ucfirst($matches[1]); }, ltrim($argument, '-'))] = $argument; } } } public function __call($method, $arguments) { if (isset($this->methods[$method]) === true) { $this->script->getArgumentsParser()->invokeHandlers($this->script, $this->methods[$method], $arguments); return $this; } else { if (method_exists($this->script, $method) === false) { throw new exceptions\runtime\unexpectedValue('Method \'' . $method . '\' is unavailable'); } $return = call_user_func_array(array($this->script, $method), $arguments); return ($return === $this->script ? $this : $return); } } public function getScript() { return $this->script; } }
<?php namespace mageekguy\atoum; class configurator { protected $script = null; protected $methods = array(); public function __construct(scripts\runner $script) { $this->script = $script; foreach ($this->script->getHelp() as $help) { list($arguments, $values) = $help; foreach ($arguments as $argument) { $this->methods[preg_replace('/-(.)/e', 'ucfirst(\'\1\')', ltrim($argument, '-'))] = $argument; } } } public function __call($method, $arguments) { if (isset($this->methods[$method]) === true) { $this->script->getArgumentsParser()->invokeHandlers($this->script, $this->methods[$method], $arguments); return $this; } else { if (method_exists($this->script, $method) === false) { throw new exceptions\runtime\unexpectedValue('Method \'' . $method . '\' is unavailable'); } $return = call_user_func_array(array($this->script, $method), $arguments); return ($return === $this->script ? $this : $return); } } public function getScript() { return $this->script; } }
Add mock as a test dependency if running as python2 Test dependencies only get used if running as python setup.py test, so need to add test_suite
# -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages IS_PY3 = sys.version_info > (3,) install_requires = [ 'jinja2', 'lxml', ] tests_require = [ ] extras_require = { 'test': tests_require, } description = "Library for building and paring Connexions' EPUBs." if not IS_PY3: tests_require.append('mock') setup( name='cnx-epub', version='0.1', author='Connexions team', author_email='info@cnx.org', url="https://github.com/connexions/cnx-epub", license='LGPL, See also LICENSE.txt', description=description, install_requires=install_requires, tests_require=tests_require, extras_require=extras_require, packages=find_packages(), include_package_data=False, entry_points="""\ [console_scripts] """, test_suite='cnxepub.tests', zip_safe=False, )
# -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages IS_PY3 = sys.version_info > (3,) install_requires = [ 'jinja2', 'lxml', ] tests_require = [ ] extras_require = { 'test': tests_require, } description = "Library for building and paring Connexions' EPUBs." if IS_PY3: tests_require.append('mock') setup( name='cnx-epub', version='0.1', author='Connexions team', author_email='info@cnx.org', url="https://github.com/connexions/cnx-epub", license='LGPL, See also LICENSE.txt', description=description, install_requires=install_requires, tests_require=tests_require, extras_require=extras_require, packages=find_packages(), include_package_data=False, entry_points="""\ [console_scripts] """, zip_safe=False, )
Update test case for FileManager
import Vue from 'vue'; import FileManager from 'src/components/file-manager/FileManager'; describe('FileManager.vue', () => { const Constructor = Vue.extend(FileManager); const vm = new Constructor().$mount(); it('should render userInputs navbar component', () => { expect(vm.$el.querySelector('.navbar')) .to.not.equal(null); }); it('should render userInputs userActions component', () => { expect(vm.$el.querySelector('.userActions')) .to.not.equal(null); }); it('should render create folder button', () => { expect(vm.$el.querySelector('.userActions #button-create-folder')) .to.not.equal(null); }); it('should render download button', () => { expect(vm.$el.querySelector('.userActions #button-file-download')) .to.not.equal(null); }); it('should render delete button', () => { expect(vm.$el.querySelector('.userActions #button-delete')) .to.not.equal(null); }); it('should render icon view button', () => { expect(vm.$el.querySelector('#button-icon-view')) .to.not.equal(null); }); it('should render list view button', () => { expect(vm.$el.querySelector('#button-list-view')) .to.not.equal(null); }); it('should render Documents component', () => { expect(vm.$el.querySelector('.documents')) .to.not.equal(null); }); });
import Vue from 'vue'; import FileManager from 'src/components/file-manager/FileManager'; describe('FileManager.vue', () => { const Constructor = Vue.extend(FileManager); const vm = new Constructor().$mount(); it('should render userInputs navbar component', () => { expect(vm.$el.querySelector('.navbar')) .to.not.equal(null); }); it('should render userInputs userActions component', () => { expect(vm.$el.querySelector('.userActions')) .to.not.equal(null); }); it('should render create folder button', () => { expect(vm.$el.querySelector('.userActions #button-create-folder')) .to.not.equal(null); }); it('should render download button', () => { expect(vm.$el.querySelector('.userActions #button-file-download')) .to.not.equal(null); }); it('should render delete button', () => { expect(vm.$el.querySelector('.userActions #button-delete')) .to.not.equal(null); }); it('should render icon view button', () => { expect(vm.$el.querySelector('.userActions #button-icon-view')) .to.not.equal(null); }); it('should render list view button', () => { expect(vm.$el.querySelector('.userActions #button-list-view')) .to.not.equal(null); }); it('should render Documents component', () => { expect(vm.$el.querySelector('.documents')) .to.not.equal(null); }); });
Increase list concurrency to 16 Summary: Too slow in IRN, causes nginx to timeout. Reviewers: O1553 Project kraken: Add blocking reviewers, evelynl Reviewed By: O1553 Project kraken: Add blocking reviewers, evelynl Subscribers: jenkins Differential Revision: https://code.uberinternal.com/D2311711
package hdfsbackend import "code.uber.internal/infra/kraken/lib/backend/hdfsbackend/webhdfs" // Config defines configuration for all HDFS clients. type Config struct { NameNodes []string `yaml:"namenodes"` UserName string `yaml:"username"` RootDirectory string `yaml:"root_directory"` // ListConcurrency is the number of threads used for listing. ListConcurrency int `yaml:"list_concurrency"` // NamePath identifies which namepath.Pather to use. NamePath string `yaml:"name_path"` // UploadDirectory is scratch space, relative to RootDirectory, used for // uploading files before moving them to content-addressable storage. Avoids // partial uploads corrupting the content-addressable storage space. UploadDirectory string `yaml:"upload_directory"` WebHDFS webhdfs.Config `yaml:"webhdfs"` // Enables test-only behavior. testing bool } func (c *Config) applyDefaults() { if c.RootDirectory == "" { c.RootDirectory = "/infra/dockerRegistry/" } if c.ListConcurrency == 0 { c.ListConcurrency = 16 } if c.UploadDirectory == "" { c.UploadDirectory = "_uploads" } }
package hdfsbackend import "code.uber.internal/infra/kraken/lib/backend/hdfsbackend/webhdfs" // Config defines configuration for all HDFS clients. type Config struct { NameNodes []string `yaml:"namenodes"` UserName string `yaml:"username"` RootDirectory string `yaml:"root_directory"` // ListConcurrency is the number of threads used for listing. ListConcurrency int `yaml:"list_concurrency"` // NamePath identifies which namepath.Pather to use. NamePath string `yaml:"name_path"` // UploadDirectory is scratch space, relative to RootDirectory, used for // uploading files before moving them to content-addressable storage. Avoids // partial uploads corrupting the content-addressable storage space. UploadDirectory string `yaml:"upload_directory"` WebHDFS webhdfs.Config `yaml:"webhdfs"` // Enables test-only behavior. testing bool } func (c *Config) applyDefaults() { if c.RootDirectory == "" { c.RootDirectory = "/infra/dockerRegistry/" } if c.ListConcurrency == 0 { c.ListConcurrency = 4 } if c.UploadDirectory == "" { c.UploadDirectory = "_uploads" } }
Fix Jaxb bug on XmlIdRef.
package com.mkl.eu.client.service.vo; import javax.xml.bind.annotation.XmlID; import java.io.Serializable; /** * Mother class of all VOs. * * @author MKL */ public abstract class EuObject implements Serializable { /** Id of the object. */ private Long id; /** @return the id. */ public Long getId() { return id; } /** @param id the id to set. */ public void setId(Long id) { this.id = id; } /** * Method added because jaxb stores all the idRef in the same Map, * whatever the class is. So if two different classes have the same id, * there will be a collision. * * @return id for jaxb. */ @XmlID public String getIdForJaxb() { return getClass().getSimpleName() + "_" + getId(); } /** * So that jaxb works... */ public void setIdForJaxb(String id) { } }
package com.mkl.eu.client.service.vo; import javax.xml.bind.annotation.XmlID; import java.io.Serializable; /** * Mother class of all VOs. * * @author MKL */ public abstract class EuObject implements Serializable { /** Id of the object. */ private Long id; /** @return the id. */ public Long getId() { return id; } /** @param id the id to set. */ public void setId(Long id) { this.id = id; } /** * Method added because jaxb stores all the idRef in the same Map, * whatever the class is. So if two different classes have the same id, * there will be a collision. * * @return id for jaxb. */ @XmlID public String getIdForJaxb() { return getClass().toString() + "_" + getId(); } /** * So that jaxb works... */ public void setIdForJaxb(String id) { } }
APVS-0020: Change to minimum claim amount to allow claims of £0.00 or greater.
const config = require('../../../config') /** * This file defines all generic validation tests used in the application. This file can and should be used by the * three higher level validators: FieldValidator, FieldSetValidator, and UrlPathValidator. */ const validator = require('validator') exports.isNullOrUndefined = function (value) { return !value } exports.isNumeric = function (value) { return validator.isNumeric(value) || validator.isDecimal(value) } exports.isCurrency = function (value) { return validator.isCurrency(value) } exports.isGreaterThanZero = function (value) { return value > 0 } exports.isGreaterThanOrEqualToZero = function (value) { return value >= 0 } exports.isGreaterThanMinimumClaim = function (value) { return value >= 0 } exports.isLessThanMaximumDifferentApprovedAmount = function (value) { return value <= parseInt(config.MAX_APPROVED_DIFFERENT_AMOUNT) && value !== null } exports.isEmail = function (value) { return validator.isEmail(value) } exports.isLessThanLength = function (value, length) { return validator.isLength(value, { max: length }) }
const config = require('../../../config') /** * This file defines all generic validation tests used in the application. This file can and should be used by the * three higher level validators: FieldValidator, FieldSetValidator, and UrlPathValidator. */ const validator = require('validator') exports.isNullOrUndefined = function (value) { return !value } exports.isNumeric = function (value) { return validator.isNumeric(value) || validator.isDecimal(value) } exports.isCurrency = function (value) { return validator.isCurrency(value) } exports.isGreaterThanZero = function (value) { return value > 0 } exports.isGreaterThanOrEqualToZero = function (value) { return value >= 0 } exports.isGreaterThanMinimumClaim = function (value) { return value > 1 } exports.isLessThanMaximumDifferentApprovedAmount = function (value) { return value <= parseInt(config.MAX_APPROVED_DIFFERENT_AMOUNT) && value !== null } exports.isEmail = function (value) { return validator.isEmail(value) } exports.isLessThanLength = function (value, length) { return validator.isLength(value, { max: length }) }
Comment out testing for delete file as delete file failed in this branch
function deleteDoc(browser, docType) { const devServer = browser.globals.devServerURL; browser.url(`${devServer}/`); browser.expect.element('#app').to.be.visible.before(5000); const createButton = `#button-create-${docType}`; browser .click(createButton) .pause(500); browser.execute((data) => { const className = `.${data}`; const currentNumDocs = document.querySelectorAll(className).length; return currentNumDocs; }, [docType], (result) => { const previousNumDocs = result.value; const expectedNumDocs = previousNumDocs - 1; const className = `.${docType}`; const deleteButton = '#button-delete'; browser .click(className) .pause(700) .click(deleteButton) .pause(500); browser .assert.elementCount(className, expectedNumDocs); }); } describe('FileManager\'s delete file/folder button', function() { after((browser, done) => { browser.end(() => done()); }); // it('should delete a file', (browser) => { // deleteDoc(browser, 'file'); // }); it('should delete a folder', (browser) => { deleteDoc(browser, 'folder'); }); });
function deleteDoc(browser, docType) { const devServer = browser.globals.devServerURL; browser.url(`${devServer}/`); browser.expect.element('#app').to.be.visible.before(5000); const createButton = `#button-create-${docType}`; browser .click(createButton) .pause(500); browser.execute((data) => { const className = `.${data}`; const currentNumDocs = document.querySelectorAll(className).length; return currentNumDocs; }, [docType], (result) => { const previousNumDocs = result.value; const expectedNumDocs = previousNumDocs - 1; const className = `.${docType}`; const deleteButton = '#button-delete'; browser .click(className) .pause(700) .click(deleteButton) .pause(500); browser .assert.elementCount(className, expectedNumDocs); }); } describe('FileManager\'s delete file/folder button', function() { after((browser, done) => { browser.end(() => done()); }); it('should delete a file', (browser) => { deleteDoc(browser, 'file'); }); it('should delete a folder', (browser) => { deleteDoc(browser, 'folder'); }); });
Fix using wrong component in ColumnBackButtonSlim
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import Icon from 'flavours/glitch/components/icon'; export default class ColumnBackButtonSlim extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = (event) => { // if history is exhausted, or we would leave mastodon, just go to root. if (window.history.state) { const state = this.context.router.history.location.state; if (event.shiftKey && state && state.mastodonBackSteps) { this.context.router.history.go(-state.mastodonBackSteps); } else { this.context.router.history.goBack(); } } else { this.context.router.history.push('/'); } } render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <Icon id='chevron-left' className='column-back-button__icon' fixedWidth /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import Icon from 'mastodon/components/icon'; export default class ColumnBackButtonSlim extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = (event) => { // if history is exhausted, or we would leave mastodon, just go to root. if (window.history.state) { const state = this.context.router.history.location.state; if (event.shiftKey && state && state.mastodonBackSteps) { this.context.router.history.go(-state.mastodonBackSteps); } else { this.context.router.history.goBack(); } } else { this.context.router.history.push('/'); } } render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <Icon id='chevron-left' className='column-back-button__icon' fixedWidth /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
Remove strict currency code checking
<?php /** * This file is part of the Money library * * Copyright (c) 2011-2013 Mathias Verraes * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Money; class Currency { /** @var string */ private $name; /** @var array */ private static $currencies; /** * @param string $name * @throws UnknownCurrencyException */ public function __construct($name) { if (!preg_match('/^[A-Z]{3}$/', $name)) { throw new UnknownCurrencyException($name); } $this->name = $name; } /** * @return string */ public function getName() { return $this->name; } /** * @param \Money\Currency $other * @return bool */ public function equals(Currency $other) { return $this->name === $other->name; } /** * @return string */ public function __toString() { return $this->getName(); } }
<?php /** * This file is part of the Money library * * Copyright (c) 2011-2013 Mathias Verraes * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Money; class Currency { /** @var string */ private $name; /** @var array */ private static $currencies; /** * @param string $name * @throws UnknownCurrencyException */ public function __construct($name) { if(!isset(static::$currencies)) { static::$currencies = require __DIR__.'/currencies.php'; } if (!array_key_exists($name, static::$currencies)) { throw new UnknownCurrencyException($name); } $this->name = $name; } /** * @return string */ public function getName() { return $this->name; } /** * @param \Money\Currency $other * @return bool */ public function equals(Currency $other) { return $this->name === $other->name; } /** * @return string */ public function __toString() { return $this->getName(); } }
Use Fontawesome 4 for default icon. [rev: matthew.gordon]
define([ 'js-whatever/js/base-page', 'text!about-page/templates/about-page.html', 'datatables.net-bs' ], function(BasePage, template) { return BasePage.extend({ template: _.template(template), initialize: function(options) { this.options = options; this.options.icon = this.options.icon || 'fa fa-cog'; }, render: function() { this.$el.html(this.template(this.options)); this.$('table.table').dataTable({ autoWidth: false, language: { search: '' } }); this.$('.dataTables_filter input') .prop('placeholder', this.options.strings.search); }, getTemplateParameters: $.noop }); });
define([ 'js-whatever/js/base-page', 'text!about-page/templates/about-page.html', 'datatables.net-bs' ], function(BasePage, template) { return BasePage.extend({ template: _.template(template), initialize: function(options) { this.options = options; this.options.icon = this.options.icon || 'icon icon-cog'; }, render: function() { this.$el.html(this.template(this.options)); this.$('table.table').dataTable({ autoWidth: false, language: { search: '' } }); this.$('.dataTables_filter input') .prop('placeholder', this.options.strings.search); }, getTemplateParameters: $.noop }); });
Fix crash on empty DB.
from collections import deque, defaultdict from random import choice class SequenceGenerator: def __init__(self, order): self.order = order self.table = defaultdict(list) def addSample(self, sequence): st = deque([None] * self.order, self.order) len = 0 for v in sequence: self.table[tuple(st)].append(v) st.append(v) len += 1 self.table[tuple(st)].append(None) def next(self, state): return choice(self.table.get(tuple(state), [None])) def generate(self): state = deque([None] * self.order, self.order) while True: nt = self.next(state) if nt is None: raise StopIteration() state.append(nt) yield nt
from collections import deque, defaultdict from random import choice class SequenceGenerator: def __init__(self, order): self.order = order self.table = defaultdict(list) def addSample(self, sequence): st = deque([None] * self.order, self.order) len = 0 for v in sequence: self.table[tuple(st)].append(v) st.append(v) len += 1 self.table[tuple(st)].append(None) def next(self, state): return choice(self.table.get(tuple(state))) def generate(self): state = deque([None] * self.order, self.order) while True: nt = self.next(state) if nt is None: raise StopIteration() state.append(nt) yield nt
Update serialVersionUID for updated public API
/** Copyright 2017 Carlos Macasaet Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.macasaet.fernet; /** * This exception indicates that a Fernet token could not be created because one or more of the parameters was invalid. * * <p>Copyright &copy; 2017 Carlos Macasaet.</p> * * @author Carlos Macasaet */ public class IllegalTokenException extends IllegalArgumentException { private static final long serialVersionUID = -1794971941479648725L; public IllegalTokenException(final String message) { super(message); } public IllegalTokenException(final String message, final Throwable cause) { super(message, cause); } }
/** Copyright 2017 Carlos Macasaet Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.macasaet.fernet; /** * This exception indicates that a Fernet token could not be created because one or more of the parameters was invalid. * * <p>Copyright &copy; 2017 Carlos Macasaet.</p> * * @author Carlos Macasaet */ public class IllegalTokenException extends IllegalArgumentException { private static final long serialVersionUID = 8019898267609912205L; public IllegalTokenException(final String message) { super(message); } public IllegalTokenException(final String message, final Throwable cause) { super(message, cause); } }
Fix error in file path of where images are loaded from in load_image()
# Defining a function to load images def load_image(image_name, fade_enabled=False): """fade_enabled should be True if you want images to be able to fade""" try: #! Add stuff for loading images of the correct resolution # depending on the player's resolution settings if not fade_enabled: return pygame.image.load("".join(( file_directory, "assets\\images\\", image_name, ".png" ))).convert_alpha() # Fixes per pixel alphas permanently else: return pygame.image.load("".join(( file_directory, "assets\\images\\", image_name, ".png" ))).convert() except Exception as error: log("".join(("Failed to load image: ", image_name, ".png")))
# Defining a function to load images def load_image(image_name, fade_enabled=False): """fade_enabled should be True if you want images to be able to fade""" try: #! Add stuff for loading images of the correct resolution # depending on the player's resolution settings if not fade_enabled: return pygame.image.load("".join(( file_directory, "Image Files\\", image_name, ".png" ))).convert_alpha() # Fixes per pixel alphas permanently else: return pygame.image.load("".join(( file_directory, "Image Files\\", image_name, ".png" ))).convert() except Exception as error: log("".join(("Failed to load image: ", image_name, ".png")))
Remove go 1.8 build tag for compatibility structs and constants
package avatica import ( "database/sql/driver" "fmt" ) type namedValue struct { Name string Ordinal int Value driver.Value } func driverValueToNamedValue(values []driver.Value) []namedValue { list := make([]namedValue, len(values)) for i, v := range values { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return list } func driverNamedValueToNamedValue(values []driver.NamedValue) ([]namedValue, error) { list := make([]namedValue, len(values)) for i, nv := range values { list[i] = namedValue(nv) if nv.Name != "" { return list, fmt.Errorf("named paramters are not supported: %s given", nv.Name) } } return list, nil } type isoLevel int32 const ( isolationUseCurrent isoLevel = -1 isolationNone isoLevel = 0 isolationReadUncommitted isoLevel = 1 isolationReadComitted isoLevel = 2 isolationRepeatableRead isoLevel = 4 isolationSerializable isoLevel = 8 )
// +build go1.8 package avatica import ( "database/sql/driver" "fmt" ) type namedValue struct { Name string Ordinal int Value driver.Value } func driverValueToNamedValue(values []driver.Value) []namedValue { list := make([]namedValue, len(values)) for i, v := range values { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return list } func driverNamedValueToNamedValue(values []driver.NamedValue) ([]namedValue,error ) { list := make([]namedValue, len(values)) for i, nv := range values { list[i] = namedValue(nv) if nv.Name != ""{ return list,fmt.Errorf("named paramters are not supported: %s given", nv.Name) } } return list, nil } type isoLevel int32 const ( isolationUseCurrent isoLevel = -1 isolationNone isoLevel = 0 isolationReadUncommitted isoLevel = 1 isolationReadComitted isoLevel = 2 isolationRepeatableRead isoLevel = 4 isolationSerializable isoLevel = 8 )
Add a CompilationUnit getter on the model Unit (to avoid testing for null each time)
package com.redhat.ceylon.eclipse.core.model; import java.lang.ref.WeakReference; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.eclipse.core.typechecker.IdePhasedUnit; public abstract class CeylonUnit extends IdeUnit { public CeylonUnit() { phasedUnitRef = null; } protected WeakReference<IdePhasedUnit> phasedUnitRef; final protected void createPhasedUnitRef(IdePhasedUnit phasedUnit) { phasedUnitRef = new WeakReference<IdePhasedUnit>(phasedUnit); } protected abstract void setPhasedUnitIfNecessary(); public IdePhasedUnit getPhasedUnit() { setPhasedUnitIfNecessary(); return phasedUnitRef.get(); } public Tree.CompilationUnit getCompilationUnit() { IdePhasedUnit pu = getPhasedUnit(); if (pu == null) { return null; } return pu.getCompilationUnit(); } }
package com.redhat.ceylon.eclipse.core.model; import java.lang.ref.WeakReference; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.eclipse.core.typechecker.IdePhasedUnit; public abstract class CeylonUnit extends IdeUnit { public CeylonUnit() { phasedUnitRef = null; } protected WeakReference<IdePhasedUnit> phasedUnitRef; final protected void createPhasedUnitRef(IdePhasedUnit phasedUnit) { phasedUnitRef = new WeakReference<IdePhasedUnit>(phasedUnit); } protected abstract void setPhasedUnitIfNecessary(); public IdePhasedUnit getPhasedUnit() { setPhasedUnitIfNecessary(); return phasedUnitRef.get(); } }
Remove setTimeout in favor of process.nextTick() According to [process.nextTick() documentation](http://nodejs.org/api/process.html#process_process_nexttick_callback), using setTimeout is not recommended: On the next loop around the event loop call this callback. This is not a simple alias to setTimeout(fn, 0), it's much more efficient. I'm not sure why you didn't use `nextTick()` yet, so if it was intended, please close :) I'm currently testing this change and it seems to work better than with setTimeout. What I'm unsure is the run function - it's not needed anymore imho.
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this return this } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this // delay the function call and return the emitter setTimeout(function(){ self.fct.call(self, self) }, 1) return this } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
Fix reference to oldAncestors in labelSelector
"use strict"; angular.module('arethusa.relation').directive('labelSelector', [ 'relation', '$timeout', function(relation, $timeout) { return { restrict: 'A', scope: { obj: '=', change: '&' }, link: function(scope, element, attrs) { scope.plugin = relation; scope.showMenu = true; scope.$watch('plugin.mode', function(newVal, oldVal) { scope.showMenu = relation.canEdit(); }); scope.$on('nestedMenuSelection', function(event, obj) { var oldAncestors = angular.copy(obj.ancestors); $timeout(function() { relation.changeState(obj, oldAncestors); }); }); }, templateUrl: 'templates/arethusa.relation/label_selector.html' }; } ]);
"use strict"; angular.module('arethusa.relation').directive('labelSelector', [ 'relation', '$timeout', function(relation, $timeout) { return { restrict: 'A', scope: { obj: '=', change: '&' }, link: function(scope, element, attrs) { scope.plugin = relation; scope.showMenu = true; scope.$watch('plugin.mode', function(newVal, oldVal) { scope.showMenu = relation.canEdit(); }); scope.$on('nestedMenuSelection', function(event, obj) { $timeout(function() { relation.changeState(obj); }); }); }, templateUrl: 'templates/arethusa.relation/label_selector.html' }; } ]);
Exit phantomJS after every screenshot to kill phantom process
var http = require('http'); var phantom=require('node-phantom-simple'); http.createServer(function (req, res) { phantom.create(function(err,ph) { return ph.createPage(function(err, page) { return page.open(req.url.slice(1), function(err, status) { //Wait for a bit for AJAX content to load on the page. Better solution? setTimeout(function() { page.renderBase64("PNG", function(error, result){ var imageBuffer = new Buffer(result, 'base64'); res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': imageBuffer.length}); res.end(imageBuffer); ph.exit() }); }, 2000); }); }); }); }).listen(1337, '127.0.0.1'); console.log('Server running at port 1337');
var http = require('http'); var phantom=require('node-phantom-simple'); http.createServer(function (req, res) { phantom.create(function(err,ph) { return ph.createPage(function(err, page) { return page.open(req.url.slice(1), function(err, status) { //Wait for a bit for AJAX content to load on the page. Better solution? setTimeout(function() { page.renderBase64("PNG", function(error, result){ var imageBuffer = new Buffer(result, 'base64'); res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': imageBuffer.length}); res.end(imageBuffer); }); }, 2000); }); }); }); }).listen(1337, '127.0.0.1'); console.log('Server running at port 1337');
Bump version number in preparation for next release.
#!/usr/bin/env python """Django/PostgreSQL implementation of the Meteor DDP service.""" import os.path from setuptools import setup, find_packages setup( name='django-ddp', version='0.2.1', description=__doc__, long_description=open('README.rst').read(), author='Tyson Clugg', author_email='tyson@clugg.net', url='https://github.com/commoncode/django-ddp', packages=find_packages(), include_package_data=True, install_requires=[ 'Django>=1.7', 'psycopg2>=2.5.4', 'gevent>=1.0', 'gevent-websocket>=0.9', 'meteor-ejson>=1.0', 'psycogreen>=1.0', 'django-dbarray>=0.2', ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Internet :: WWW/HTTP", ], )
#!/usr/bin/env python """Django/PostgreSQL implementation of the Meteor DDP service.""" import os.path from setuptools import setup, find_packages setup( name='django-ddp', version='0.2.0', description=__doc__, long_description=open('README.rst').read(), author='Tyson Clugg', author_email='tyson@clugg.net', url='https://github.com/commoncode/django-ddp', packages=find_packages(), include_package_data=True, install_requires=[ 'Django>=1.7', 'psycopg2>=2.5.4', 'gevent>=1.0', 'gevent-websocket>=0.9', 'meteor-ejson>=1.0', 'psycogreen>=1.0', 'django-dbarray>=0.2', ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Internet :: WWW/HTTP", ], )
Revert "use argument passed instead of this.app" This reverts commit 6353e4b2acbe5be66f67de00c5bea473ce4d2a22.
/* jshint node: true */ module.exports = { name: 'ember-cli-dotenv', config: function(){ var path = require('path'); var fs = require('fs'); var dotenv = require('dotenv'); var app = this.app; var project = this.project; var loadedConfig; var config = {}; var hasOwn = Object.prototype.hasOwnProperty; if (app.options.dotEnv && hasOwn.call(app.options.dotEnv, 'allow')){ console.warn("[EMBER-CLI-DOTENV] app.options.allow has been deprecated. Please use clientAllowedKeys instead. Support will be removed in the next major version"); } var allowedKeys = (app.options.dotEnv && (app.options.dotEnv.clientAllowedKeys || app.options.dotEnv.allow) || []); var configFilePath = path.join(project.root, '.env'); if (fs.existsSync(configFilePath)){ // Load all server side keys dotenv._getKeyAndValueFromLine(configFilePath); dotenv._setEnvs(); dotenv.load(); loadedConfig = dotenv.parse(fs.readFileSync(configFilePath)); } else { loadedConfig = {}; } allowedKeys.forEach(function(key){ config[key] = loadedConfig[key]; }); return config; } };
/* jshint node: true */ module.exports = { name: 'ember-cli-dotenv', config: function(env, appConfig){ var path = require('path'); var fs = require('fs'); var dotenv = require('dotenv'); var app = this.app; var project = this.project; var loadedConfig; var config = {}; var hasOwn = Object.prototype.hasOwnProperty; if (appConfig.dotEnv && hasOwn.call(appConfig.dotEnv, 'allow')){ console.warn("[EMBER-CLI-DOTENV] appConfig.allow has been deprecated. Please use clientAllowedKeys instead. Support will be removed in the next major version"); } var allowedKeys = (appConfig.dotEnv && (appConfig.dotEnv.clientAllowedKeys || appConfig.dotEnv.allow) || []); var configFilePath = path.join(project.root, '.env'); if (fs.existsSync(configFilePath)){ // Load all server side keys dotenv._getKeyAndValueFromLine(configFilePath); dotenv._setEnvs(); dotenv.load(); loadedConfig = dotenv.parse(fs.readFileSync(configFilePath)); } else { loadedConfig = {}; } allowedKeys.forEach(function(key){ config[key] = loadedConfig[key]; }); return config; } };
Support new gist ID format
package gogist import ( "fmt" "net/http" "github.com/gorilla/mux" ) const t = ` <html> <head> <meta name="go-import" content="%s git https://gist.github.com/%s.git" /> <script>window.location='https://github.com/ImJasonH/go-gist/';</script> </head> </html> ` func init() { r := mux.NewRouter() h := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"]))) } r.HandleFunc("/{username}/{gistID:[0-9a-f]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET") r.HandleFunc("/{username}/{gistID:[0-9a-f]+}", h).Methods("GET") r.HandleFunc("/{gistID:[0-9a-f]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET") r.HandleFunc("/{gistID:[0-9a-f]+}", h).Methods("GET") r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther)) http.Handle("/", r) }
package gogist import ( "fmt" "net/http" "github.com/gorilla/mux" ) const t = ` <html> <head> <meta name="go-import" content="%s git https://gist.github.com/%s.git" /> <script>window.location='https://github.com/ImJasonH/go-gist/';</script> </head> </html> ` func init() { r := mux.NewRouter() h := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"]))) } r.HandleFunc("/{username}/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET") r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET") r.HandleFunc("/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET") r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET") r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther)) http.Handle("/", r) }
Replace short array syntax to compatible with PHP 5.3
<?php class BodyTest extends PHPUnit_Framework_TestCase { /** * @var \HieuLe\BodyClasses\Body */ private $_obj; public function setUp() { parent::setUp(); $this->_obj = new \HieuLe\BodyClasses\Body(); } public function testAddClassesAsString() { $this->_obj->addClasses('foo'); $this->assertEquals(array('foo'), $this->_obj->getClassArray()); $this->assertEquals('foo', $this->_obj->getClasses()); } public function testAddClassesAsArray() { $this->_obj->addClasses(array('bar', 'baz')); $this->assertEquals(array('bar', 'baz'), $this->_obj->getClassArray()); $this->assertEquals('bar baz', $this->_obj->getClasses()); } public function testAddDuplicatedClasses() { $this->_obj->addClasses('foo'); $this->_obj->addClasses('bar'); $this->_obj->addClasses(array('foo')); $this->assertEquals(array('foo', 'bar'), $this->_obj->getClassArray()); $this->assertEquals('foo bar', $this->_obj->getClasses()); } }
<?php class BodyTest extends PHPUnit_Framework_TestCase { /** * @var \HieuLe\BodyClasses\Body */ private $_obj; public function setUp() { parent::setUp(); $this->_obj = new \HieuLe\BodyClasses\Body(); } public function testAddClassesAsString() { $this->_obj->addClasses('foo'); $this->assertEquals(['foo'], $this->_obj->getClassArray()); $this->assertEquals('foo', $this->_obj->getClasses()); } public function testAddClassesAsArray() { $this->_obj->addClasses(['bar', 'baz']); $this->assertEquals(['bar', 'baz'], $this->_obj->getClassArray()); $this->assertEquals('bar baz', $this->_obj->getClasses()); } public function testAddDuplicatedClasses() { $this->_obj->addClasses('foo'); $this->_obj->addClasses('bar'); $this->_obj->addClasses(['foo']); $this->assertEquals(['foo', 'bar'], $this->_obj->getClassArray()); $this->assertEquals('foo bar', $this->_obj->getClasses()); } }
Fix inner model id do not automatic set when set a inner model.
/** * Created by dungvn3000 on 3/14/14. * The model automatic update mapping field when set associations table. */ Ext.define('sunerp.model.BaseModel', { extend: 'Ext.data.Model', set: function (fieldName, newValue) { var me = this; me.callParent(arguments); if (newValue != null && Ext.isObject(newValue)) { Ext.each(me.associations.keys, function (table) { if (fieldName == table) { for (var key in newValue) { me.set(table + "." + key, newValue[key]); } me.set(table + 'Id', newValue.id); } }); } } });
/** * Created by dungvn3000 on 3/14/14. * The model automatic update mapping field when set associations table. */ Ext.define('sunerp.model.BaseModel', { extend: 'Ext.data.Model', set: function (fieldName, newValue) { var me = this; me.callParent(arguments); if (newValue != null && Ext.isObject(newValue)) { Ext.each(me.associations.keys, function (table) { if (fieldName == table) { for (var key in newValue) { me.set(table + "." + key, newValue[key]); } me.set(key + 'Id', newValue.id); } }); } } });
Fix the one offset error
@extends('layouts.app') @section('wrap') <div class="container"> <div class="list-group"> <h3>文言文語譯</h3> @for ($i = 1; $i <= min(10, count($links)); $i += 1) <a href="{{ url('/e/link/' . $i) }}">{{ $links[$i] }}</a> @endfor </div> <div class="list-group"> <h3>2014文憑試口語</h3> @for ($i = 11; $i <= min(16, count($links)); $i += 1) <a href="{{ url('/e/link/' . $i) }}">{{ $links[$i] }}</a> @endfor </div> </div> @endsection @section('scripts') @parent <script src="{{ url('/js/subject/chinese/links.js') }}"></script> @endsection
@extends('layouts.app') @section('wrap') <div class="container"> <div class="list-group"> <h3>文言文語譯</h3> @for ($i = 1; $i <= min(10, count($links)); $i += 1) <a href="{{ url('/e/link/' . $i) }}">{{ $links[$i] }}</a> @endfor </div> <div class="list-group"> <h3>2014文憑試口語</h3> @for ($i = 10; $i <= min(16, count($links)); $i += 1) <a href="{{ url('/e/link/' . $i) }}">{{ $links[$i] }}</a> @endfor </div> </div> @endsection @section('scripts') @parent <script src="{{ url('/js/subject/chinese/links.js') }}"></script> @endsection
Fix daylight savings time bug
""" Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format WARNING: you must have PyXML installed as part of your python installation in order for this plugin to work Place this plugin early in your load_plugins list, so that the w3cdate will be available to subsequent plugins """ __author__ = "Ted Leung <twl@sauria.com>" __version__ = "$Id:" __copyright__ = "Copyright (c) 2003 Ted Leung" __license__ = "Python" import xml.utils.iso8601 import time def cb_prepare(args): request = args["request"] form = request.getHttp()['form'] config = request.getConfiguration() data = request.getData() entry_list = data['entry_list'] for i in range(len(entry_list)): entry = entry_list[i] t = entry['timetuple'] # adjust for daylight savings time t = t[0],t[1],t[2],t[3]+time.localtime()[-1],t[4],t[5],t[6],t[7],t[8] entry['w3cdate'] = xml.utils.iso8601.ctime(time.mktime(t))
""" Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format WARNING: you must have PyXML installed as part of your python installation in order for this plugin to work Place this plugin early in your load_plugins list, so that the w3cdate will be available to subsequent plugins """ __author__ = "Ted Leung <twl@sauria.com>" __version__ = "$Id:" __copyright__ = "Copyright (c) 2003 Ted Leung" __license__ = "Python" import xml.utils.iso8601 import time def cb_prepare(args): request = args["request"] form = request.getHttp()['form'] config = request.getConfiguration() data = request.getData() entry_list = data['entry_list'] for i in range(len(entry_list)): entry = entry_list[i] entry['w3cdate'] = xml.utils.iso8601.ctime(time.mktime(entry['timetuple']))
Use the repackaged versions of classes. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@299 c7a0535c-eda6-11de-83d8-6d5adf01d787
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.unittesting.assertionbenchmarks; import java.math.BigDecimal; import org.mutabilitydetector.cli.CommandLineOptions; import org.mutabilitydetector.cli.RunMutabilityDetector; import org.mutabilitydetector.repackaged.com.google.classpath.ClassPath; import org.mutabilitydetector.repackaged.com.google.classpath.ClassPathFactory; public class CheckSomeClass { public static void main(String[] args) { //checkClass(TestIllegalFieldValueException.class); // checkClass(DurationField.class); checkClass(BigDecimal.class); } private static void checkClass(Class<?> toAnalyse) { ClassPath cp = new ClassPathFactory().createFromJVM(); String match = toAnalyse.getName().replace("$", "\\$"); CommandLineOptions options = new CommandLineOptions(System.out, "-v", "-match", match); new RunMutabilityDetector(cp, options).run(); } }
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.unittesting.assertionbenchmarks; import java.math.BigDecimal; import org.mutabilitydetector.cli.CommandLineOptions; import org.mutabilitydetector.cli.RunMutabilityDetector; import com.google.classpath.ClassPath; import com.google.classpath.ClassPathFactory; public class CheckSomeClass { public static void main(String[] args) { //checkClass(TestIllegalFieldValueException.class); // checkClass(DurationField.class); checkClass(BigDecimal.class); } private static void checkClass(Class<?> toAnalyse) { ClassPath cp = new ClassPathFactory().createFromJVM(); String match = toAnalyse.getName().replace("$", "\\$"); CommandLineOptions options = new CommandLineOptions(System.out, "-v", "-match", match); new RunMutabilityDetector(cp, options).run(); } }
Fix files that have no namespace, but with psr-0 . Eg Solar, Kohana, Zend_ etc
<?php $class = $argv[1]; $file = $argv[2]; $rootpath = $argv[3]; $autoloader = $rootpath . '/vendor/autoload.php'; if (file_exists($autoloader)) { $loader = require $autoloader; require __DIR__ . '/FQCN.php'; $contents = file_get_contents($file); $fqns = new Hkt\FQCN(); $useClasses = $fqns->getAllUseStatements($contents); if (array_key_exists($class, $useClasses)) { echo $loader->findFile($useClasses[$class]); } else { // Get current namespace $namespace = $fqns->getNamespace(); if ($namespace) { $class = $namespace . '\\' . $class; } echo $loader->findFile($class); } }
<?php $class = $argv[1]; $file = $argv[2]; $rootpath = $argv[3]; $autoloader = $rootpath . '/vendor/autoload.php'; if (file_exists($autoloader)) { $loader = require $autoloader; require __DIR__ . '/FQCN.php'; $contents = file_get_contents($file); $fqns = new Hkt\FQCN(); $useClasses = $fqns->getAllUseStatements($contents); if (array_key_exists($class, $useClasses)) { echo $loader->findFile($useClasses[$class]); } else { // Get current namespace $namespace = $fqns->getNamespace(); echo $loader->findFile($namespace . '\\' . $class); } }
Set path.py to a fixed version
######## # Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############ from setuptools import setup setup( name='clash', version='0.16', author='GigaSpaces', author_email='cosmo-admin@gigaspaces.com', packages=['clash'], description='Framework to wrap Cloudify local based blueprints as CLIs', license='Apache License, Version 2.0', zip_safe=False, install_requires=[ 'argcomplete', 'ansicolors', 'argh', 'path.py==8.1.2', 'cloudify-plugins-common==3.3.1', 'cloudify-dsl-parser==3.3.1', 'cloudify-script-plugin==1.3.1' ] )
######## # Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############ from setuptools import setup setup( name='clash', version='0.16', author='GigaSpaces', author_email='cosmo-admin@gigaspaces.com', packages=['clash'], description='Framework to wrap Cloudify local based blueprints as CLIs', license='Apache License, Version 2.0', zip_safe=False, install_requires=[ 'argcomplete', 'ansicolors', 'argh', 'path.py', 'cloudify-plugins-common==3.3.1', 'cloudify-dsl-parser==3.3.1', 'cloudify-script-plugin==1.3.1' ] )
Replace confusing min/max selection logic
package io.generators.core; import com.google.common.collect.Ordering; import com.google.common.collect.Range; import javax.annotation.Nonnull; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Range.closed; /** * Generates random closed range of Comparable%lt;T%gt; * * @author Tomas Klubal */ public class RandomClosedRangeGenerator<T extends Comparable<T>> implements Generator<Range<T>> { private final Generator<T> delegate; /** * Creates range generator that delegates generation endpoints to its delegate * * @param delegate actual generator that generates values * @throws NullPointerException when <code>delegate</code> is null */ public RandomClosedRangeGenerator(@Nonnull Generator<T> delegate) { this.delegate = checkNotNull(delegate, "Delegate generator can't be null"); } @Override public Range<T> next() { T a = delegate.next(); T b = delegate.next(); T lower = Ordering.natural().min(a, b); T upper = Ordering.natural().max(a, b); return closed(lower, upper); } }
package io.generators.core; import com.google.common.collect.Range; import javax.annotation.Nonnull; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Range.closed; /** * Generates random closed range of Comparable%lt;T%gt; * * @author Tomas Klubal */ public class RandomClosedRangeGenerator<T extends Comparable<T>> implements Generator<Range<T>> { private final Generator<T> delegate; /** * Creates range generator that delegates generation endpoints to its delegate * * @param delegate actual generator that generates values * @throws NullPointerException when <code>delegate</code> is null */ public RandomClosedRangeGenerator(@Nonnull Generator<T> delegate) { this.delegate = checkNotNull(delegate, "Delegate generator can't be null"); } @Override public Range<T> next() { T lower = delegate.next(); T maybeUpper = delegate.next(); T upper = lower.compareTo(maybeUpper) < 0 ? maybeUpper : lower; lower = upper == maybeUpper ? lower : maybeUpper; return closed(lower, upper); } }
Add scroll position function calls
if (Meteor.isClient) { Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY' }); Template.messages.helpers({ messages: function() { return Messages.find({}, { sort: { time: 1}}); } }); var scrollPosition = function() { $('#messages').scrollTop($('#messages')[0].scrollHeight); }; Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { if (Meteor.user()) var name = Meteor.user().username; else var name = 'Anonymous'; var message = document.getElementById('message'); if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), }); document.getElementById('message').value = ''; message.value = ''; scrollPosition(); } } } }; $(document).ready(function(){ scrollPosition(); }); if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } }
if (Meteor.isClient) { Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY' }); Template.messages.helpers({ messages: function() { return Messages.find({}, { sort: { time: 1}}); } }); var scrollPosition = function() { $('#messages').scrollTop($('#messages')[0].scrollHeight); }; Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { if (Meteor.user()) var name = Meteor.user().username; else var name = 'Anonymous'; var message = document.getElementById('message'); if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), }); document.getElementById('message').value = ''; message.value = ''; } } } }; if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } }
Increase bullet speed for testing
// import Platform from 'objects/platform'; import { ASSETS } from 'constants'; import Bullet from 'objects/bullet'; export default class Player extends Phaser.Sprite { constructor(game, x, y) { const { world } = game; super(game, x, y, ASSETS.PLAYER, 1); game.physics.p2.enable(this, true); this.body.setRectangle(20); this.body.static = true; game.debug.body(this); this.spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); this.bullet = new Bullet(game, x, y + 20); game.add.existing(this.bullet); } update() { if (this.spaceKey.isDown) { console.log('fire!') this.fireBullet(); } } fireBullet() { this.bullet.body.velocity.x = 500; // this.bullet.body.velocity.y = 200; } }
// import Platform from 'objects/platform'; import { ASSETS } from 'constants'; import Bullet from 'objects/bullet'; export default class Player extends Phaser.Sprite { constructor(game, x, y) { const { world } = game; super(game, x, y, ASSETS.PLAYER, 1); game.physics.p2.enable(this, true); this.body.setRectangle(20); this.body.static = true; game.debug.body(this); this.spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); this.bullet = new Bullet(game, x, y + 20); game.add.existing(this.bullet); } update() { if (this.spaceKey.isDown) { console.log('fire!') this.fireBullet(); } } fireBullet() { this.bullet.body.velocity.x = 200; } }
Disable clicking on thread underline when accepting selection
import React from 'react' import { connect } from 'react-redux' import { openCommentThreads, selectCommentThread } from 'redux/actions.js' function mapStateToProps(state, { contentState, children }) { let commentThreadId = getFirstThreadId(contentState, children[0]) return { cardId: state.commentThreadsById[commentThreadId].cardId, disabled: state.ui.acceptingSelection, commentThreadId, } } function mergeProps( {cardId, commentThreadId, disabled}, {openCommentThreads, selectCommentThread}, {children} ) { return { onClick: () => { disabled || ( openCommentThreads(cardId) && selectCommentThread(parseInt(commentThreadId, 10)) ) }, children: children.length > 0 && React.cloneElement(children[0], {forceSelection: true}), } } const CommentThreadEntity = ({ onClick, children }) => { return <span onClick={onClick}> {children} </span> } export default connect( mapStateToProps, { openCommentThreads, selectCommentThread }, mergeProps, )(CommentThreadEntity) function getFirstThreadId(contentState, leaf) { const styles = contentState.getBlockForKey(leaf.props.blockKey) .getInlineStyleAt(leaf.props.start) const ids = styles.map(s => s.match(/thread--([0-9]+)/)) .filter(s => s && s[1]) .map(s => s[1]) return ids.count() > 0 ? ids.toJS()[0] : null }
import React from 'react' import { connect } from 'react-redux' import { openCommentThreads, selectCommentThread } from 'redux/actions.js' function mapStateToProps(state, { contentState, children }) { let commentThreadId = getFirstThreadId(contentState, children[0]) return { cardId: state.commentThreadsById[commentThreadId].cardId, commentThreadId, } } function mergeProps( {cardId, commentThreadId}, {openCommentThreads, selectCommentThread}, {children} ) { return { onClick: () => { openCommentThreads(cardId) && selectCommentThread(parseInt(commentThreadId, 10)) }, children: children.length > 0 && React.cloneElement(children[0], {forceSelection: true}), } } const CommentThreadEntity = ({ onClick, children }) => { return <span onClick={onClick}> {children} </span> } export default connect( mapStateToProps, { openCommentThreads, selectCommentThread }, mergeProps, )(CommentThreadEntity) function getFirstThreadId(contentState, leaf) { const styles = contentState.getBlockForKey(leaf.props.blockKey) .getInlineStyleAt(leaf.props.start) const ids = styles.map(s => s.match(/thread--([0-9]+)/)) .filter(s => s && s[1]) .map(s => s[1]) return ids.count() > 0 ? ids.toJS()[0] : null }
Rewrite to replace IC_FLAG by FLAG_from_IC.
''' >>> FLAG_from_IC[2] array([[1, 1], [3, 4]]) The flag vector of ICC is [1, 6, 9]. >>> numpy.dot(FLAG_from_IC[3], [0, 0, 1]) array([1, 6, 9]) >>> FLAG_from_IC[3] array([[1, 1, 1], [4, 5, 6], [6, 8, 9]]) ''' # For Python2 compatibility from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __metaclass__ = type import numpy from .fibonacci import FIBONACCI from .tools import grow_list from .data import IC_flag def fib_zeros_array(*argv): '''Return array with shape (FIB[argv[0] + 1], ...). ''' shape = tuple(FIBONACCI[n+1] for n in argv) value = numpy.zeros(shape, int) return value @grow_list def FLAG_from_IC(self): deg = len(self) value = fib_zeros_array(deg, deg) for i, line in enumerate(IC_flag[deg]): value[:,i] = list(map(int, line.split()[1:])) return value
''' >>> IC_FLAG[2] array([[1, 3], [1, 4]]) >>> IC_FLAG[3] array([[1, 4, 6], [1, 5, 8], [1, 6, 9]]) ''' # For Python2 compatibility from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __metaclass__ = type import numpy from .fibonacci import FIBONACCI from .tools import grow_list from .data import IC_flag def fib_zeros_array(*argv): '''Return array with shape (FIB[argv[0] + 1], ...). ''' shape = tuple(FIBONACCI[n+1] for n in argv) value = numpy.zeros(shape, int) return value @grow_list def IC_FLAG(self): deg = len(self) value = fib_zeros_array(deg, deg) for i, line in enumerate(IC_flag[deg]): value[i] = list(map(int, line.split()[1:])) return value
Correct namespace zone service trait
<?php namespace Heystack\Ecommerce\Locale\Traits; use Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface; /** * Class HasZoneServiceTrait * @package Heystack\Ecommerce\Locale\Traits */ trait HasZoneServiceTrait { /** * @var \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface */ protected $zoneService; /** * @param \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface $localService */ public function setZoneService(ZoneServiceInterface $localService) { $this->zoneService = $localService; } /** * @return \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface */ public function getZoneService() { return $this->zoneService; } }
<?php namespace Heystack\Ecommerce\Zone\Traits; use Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface; /** * Class HasZoneServiceTrait * @package Heystack\Ecommerce\Zone\Traits */ trait HasZoneServiceTrait { /** * @var \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface */ protected $zoneService; /** * @param \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface $localService */ public function setZoneService(ZoneServiceInterface $localService) { $this->zoneService = $localService; } /** * @return \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface */ public function getZoneService() { return $this->zoneService; } }
Fix tests in Python 3.6
from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.raises(IndexError): make_func(1)('a') with pytest.raises(TypeError): make_func(1)(42) def test_slice(): assert make_func(slice(1, None))('abc') == 'bc' def test_str(): assert make_func(r'\d+')('ab42c') == '42' assert make_func(r'\d+')('abc') is None assert make_pred(r'\d+')('ab42c') is True assert make_pred(r'\d+')('abc') is False def test_dict(): assert make_func({1: 'a'})(1) == 'a' with pytest.raises(KeyError): make_func({1: 'a'})(2) d = defaultdict(int, a=42) assert make_func(d)('a') == 42 assert make_func(d)('b') == 0 def test_set(): s = set([1,2,3]) assert make_func(s)(1) is True assert make_func(s)(4) is False
from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.raises(IndexError): make_func(1)('a') with pytest.raises(TypeError): make_func(1)(42) def test_slice(): assert make_func(slice(1, None))('abc') == 'bc' def test_str(): assert make_func('\d+')('ab42c') == '42' assert make_func('\d+')('abc') is None assert make_pred('\d+')('ab42c') is True assert make_pred('\d+')('abc') is False def test_dict(): assert make_func({1: 'a'})(1) == 'a' with pytest.raises(KeyError): make_func({1: 'a'})(2) d = defaultdict(int, a=42) assert make_func(d)('a') == 42 assert make_func(d)('b') == 0 def test_set(): s = set([1,2,3]) assert make_func(s)(1) is True assert make_func(s)(4) is False
Update formatting for consistency and readability.
/** * Visually Hidden component, mainly used for screen-reader text. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; import classnames from 'classnames'; function VisuallyHidden( { className, children, ...otherProps } ) { return ( <span { ...otherProps } className={ classnames( 'screen-reader-text', className ) } > { children } </span> ); } VisuallyHidden.propTypes = { className: PropTypes.string, children: PropTypes.node.isRequired, }; VisuallyHidden.defaultProps = { className: '', }; export default VisuallyHidden;
/** * Visually Hidden component, mainly used for screen-reader text. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; import classnames from 'classnames'; function VisuallyHidden( { className, children, ...otherProps } ) { return <span { ...otherProps } className={ classnames( 'screen-reader-text', className ) }>{ children }</span>; } VisuallyHidden.propTypes = { className: PropTypes.string, children: PropTypes.node.isRequired, }; VisuallyHidden.defaultProps = { className: '', }; export default VisuallyHidden;
Throw Ex in stream if monitor cancelled
package io.github.duckasteroid.progress.utils; import io.github.duckasteroid.progress.ProgressMonitor; import java.io.IOException; import java.io.InputStream; /** * Wraps an input stream to report 1 unit of work for every byte {@link #read()}. * Clients should set the {@link ProgressMonitor#setSize(long)} prior to invoking for this * to report correctly. * When the stream is {@link #close() closed} the monitor is marked done */ public class InputStreamProgress extends InputStream { private final transient InputStream delegate; private final transient ProgressMonitor monitor; public InputStreamProgress(InputStream delegate, ProgressMonitor monitor) { this.delegate = delegate; this.monitor = monitor; } @Override public int read() throws IOException { if (monitor.isCancelled()) { throw new IOException("Read operation cancelled by monitor"); } monitor.worked(1); return delegate.read(); } @Override public void close() throws IOException { monitor.done(); super.close(); } }
package io.github.duckasteroid.progress.utils; import io.github.duckasteroid.progress.ProgressMonitor; import java.io.IOException; import java.io.InputStream; /** * Wraps an input stream to report 1 unit of work for every byte {@link #read()}. * Clients should set the {@link ProgressMonitor#setSize(long)} prior to invoking for this * to report correctly. * When the stream is {@link #close() closed} the monitor is marked done */ public class InputStreamProgress extends InputStream { private final transient InputStream delegate; private final transient ProgressMonitor monitor; public InputStreamProgress(InputStream delegate, ProgressMonitor monitor) { this.delegate = delegate; this.monitor = monitor; } @Override public int read() throws IOException { monitor.worked(1); return delegate.read(); } @Override public void close() throws IOException { monitor.done(); super.close(); } }
Fix typo... type to Type
<?php namespace Core\GameSessionBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class CreateGameSessionType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('description', 'textarea', array('attr' => array('rows' => '5', 'cols' => '30'))) ->add('save', 'submit') ->getForm() ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Core\GameSessionBundle\Entity\GameSession', )); } /** * @return string */ public function getName() { return 'core_gamesessionbundle_createGameSession'; } }
<?php namespace Core\GameSessionBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class CreateGameSessiontype extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('description', 'textarea', array('attr' => array('rows' => '5', 'cols' => '30'))) ->add('save', 'submit') ->getForm() ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Core\GameSessionBundle\Entity\GameSession', )); } /** * @return string */ public function getName() { return 'core_gamesessionbundle_createGameSession'; } }
Allow RPC client to accept string arguments.
#!/usr/bin/env node var sys = require('sys'); var logger = require('../lib/logger'); var getConfig = require('./init').getConfig; var cfg = getConfig(); if (cfg.jsonrpc.password == null) { logger.error('No JSON RPC password specified in configuration.'); logger.notice('Note that you can use the --rpcpassword command line parameter.'); process.exit(1); } var RpcClient = require('jsonrpc2').Client; var rpc = new RpcClient(cfg.jsonrpc.port, cfg.jsonrpc.host, cfg.jsonrpc.username, cfg.jsonrpc.password); if (process.argv.length < 3) { logger.error("No RPC method specified!"); console.log("Usage: node daemon/cli.js <rpcmethod> [rpcparam1 rpcparam2 ...]"); process.exit(1); } var params = process.argv.slice(3).map(function (param) { var value; try { value = JSON.parse(param); } catch (e) { value = param; } return value; }); rpc.call(process.argv[2], params, function (err, result) { if (err) { logger.error("RPC Error: "+ (err.stack ? err.stack : sys.inspect(err))); process.exit(1); } sys.puts(sys.inspect(result, false, null)); });
#!/usr/bin/env node var sys = require('sys'); var logger = require('../lib/logger'); var getConfig = require('./init').getConfig; var cfg = getConfig(); if (cfg.jsonrpc.password == null) { logger.error('No JSON RPC password specified in configuration.'); logger.notice('Note that you can use the --rpcpassword command line parameter.'); process.exit(1); } var RpcClient = require('jsonrpc2').Client; var rpc = new RpcClient(cfg.jsonrpc.port, cfg.jsonrpc.host, cfg.jsonrpc.username, cfg.jsonrpc.password); if (process.argv.length < 3) { logger.error("No RPC method specified!"); console.log("Usage: node daemon/cli.js <rpcmethod> [rpcparam1 rpcparam2 ...]"); process.exit(1); } var params = process.argv.slice(3).map(function (param) { return JSON.parse(param); }); rpc.call(process.argv[2], params, function (err, result) { if (err) { logger.error("RPC Error: "+ (err.stack ? err.stack : sys.inspect(err))); process.exit(1); } sys.puts(sys.inspect(result, false, null)); });
Handle *.iced sources in addition to *.coffee.
var fs = Npm.require('fs'); var path = Npm.require('path'); var iced = Npm.require('iced-coffee-script'); var handler = function (compileStep) { var source = compileStep.read().toString('utf8'); var outputFile = compileStep.inputPath + ".js"; options = { bare: true, filename: compileStep.inputPath, literate: path.extname(compileStep.inputPath) === '.litcoffee' }; try { var output = iced.compile(source, options); } catch (e) { throw new Error( compileStep.inputPath + ':' + (e.location ? (e.location.first_line + ': ') : ' ') + e.message ); } compileStep.addJavaScript({ path: outputFile, sourcePath: compileStep.inputPath, data: output }); }; Plugin.registerSourceHandler('coffee', handler); Plugin.registerSourceHandler('litcoffee', handler); Plugin.registerSourceHandler('iced', handler);
var fs = Npm.require('fs'); var path = Npm.require('path'); var iced = Npm.require('iced-coffee-script'); var handler = function (compileStep) { var source = compileStep.read().toString('utf8'); var outputFile = compileStep.inputPath + ".js"; options = { bare: true, filename: compileStep.inputPath, literate: path.extname(compileStep.inputPath) === '.litcoffee' }; try { var output = iced.compile(source, options); } catch (e) { throw new Error( compileStep.inputPath + ':' + (e.location ? (e.location.first_line + ': ') : ' ') + e.message ); } compileStep.addJavaScript({ path: outputFile, sourcePath: compileStep.inputPath, data: output }); }; Plugin.registerSourceHandler('coffee', handler); Plugin.registerSourceHandler('litcoffee', handler);
Fix type casting: use interface instead of object itself.
<?PHP /** * A Phone value object. * * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Money; use SerendipityHQ\Component\ValueObjects\Common\ComplexValueObjectInterface; /** * Defines the minimum requirements of a Money object. * * {@inheritdoc} */ interface MoneyInterface extends ComplexValueObjectInterface { /** * @param MoneyInterface $other * * @return static */ public function add(MoneyInterface $other); /** * Returns the monetary value represented by this object. * * @return int */ public function getAmount(); /** * return the monetary value represented by this object converted to its base units. * * @return float */ public function getConvertedAmount(); /** * Returns the currency of the monetary value represented by this * object. * * @return \SebastianBergmann\Money\Currency */ public function getCurrency(); /** * @param MoneyInterface $other * * @return static */ public function subtract(MoneyInterface $other); }
<?PHP /** * A Phone value object. * * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Money; use SerendipityHQ\Component\ValueObjects\Common\ComplexValueObjectInterface; /** * Defines the minimum requirements of a Money object. * * {@inheritdoc} */ interface MoneyInterface extends ComplexValueObjectInterface { /** * @param Money $other * * @return static */ public function add(Money $other); /** * Returns the monetary value represented by this object. * * @return int */ public function getAmount(); /** * return the monetary value represented by this object converted to its base units. * * @return float */ public function getConvertedAmount(); /** * Returns the currency of the monetary value represented by this * object. * * @return \SebastianBergmann\Money\Currency */ public function getCurrency(); /** * @param Money $other * * @return static */ public function subtract(Money $other); }
Use json module instead of django.utils.simplejson for Django 1.5
# -*- coding: utf-8 -*- from distutils.version import LooseVersion from classytags.core import Tag, Options import django from django import template from django.core.serializers.json import DjangoJSONEncoder from django.utils.text import javascript_quote DJANGO_1_4 = LooseVersion(django.get_version()) < LooseVersion('1.5') if DJANGO_1_4: from django.utils import simplejson as json else: import json register = template.Library() @register.filter def js(value): return json.dumps(value, cls=DjangoJSONEncoder) @register.filter def bool(value): if value: return 'true' else: return 'false' class JavascriptString(Tag): name = 'javascript_string' options = Options( blocks=[ ('end_javascript_string', 'nodelist'), ] ) def render_tag(self, context, **kwargs): rendered = self.nodelist.render(context) return u"'%s'" % javascript_quote(rendered.strip()) register.tag(JavascriptString)
# -*- coding: utf-8 -*- from classytags.core import Tag, Options from django import template from django.core.serializers.json import DjangoJSONEncoder from django.utils import simplejson from django.utils.text import javascript_quote register = template.Library() @register.filter def js(value): return simplejson.dumps(value, cls=DjangoJSONEncoder) @register.filter def bool(value): if value: return 'true' else: return 'false' class JavascriptString(Tag): name = 'javascript_string' options = Options( blocks=[ ('end_javascript_string', 'nodelist'), ] ) def render_tag(self, context, **kwargs): rendered = self.nodelist.render(context) return u"'%s'" % javascript_quote(rendered.strip()) register.tag(JavascriptString)
Fix error where intlTelInput was not defined
'use strict'; const path = require('path'); const fastbootTransform = require('fastboot-transform'); const Funnel = require('broccoli-funnel'); module.exports = { name: 'ember-cli-intl-tel-input', included: function(app) { this._super.included.apply(this, arguments); let config = app.options.intlTelInput; let assetPath = path.join('node_modules', 'intl-tel-input', 'build'); let importOptions = { using: [{ transformation: 'fastbootTransform' }] }; if (config && true === config.includeUtilsScript) { app.import(path.join(assetPath, 'js', 'utils.js'), importOptions); } app.import(path.join(assetPath, 'js', 'intlTelInput.js'), importOptions); app.import(path.join(assetPath, 'css', 'intlTelInput.css')); }, treeForPublic() { let intlTelInputImagePath = path.join(this.app.project.root, 'node_modules', 'intl-tel-input', 'build', 'img'); let publicTree = new Funnel(intlTelInputImagePath, { include: ['*.png'], destDir: 'img' }); return publicTree; }, importTransforms: function () { return { fastbootTransform: fastbootTransform } }, };
'use strict'; const path = require('path'); const fastbootTransform = require('fastboot-transform'); const Funnel = require('broccoli-funnel'); module.exports = { name: 'ember-cli-intl-tel-input', included: function(app) { this._super.included.apply(this, arguments); let config = app.options.intlTelInput; let assetPath = path.join('node_modules', 'intl-tel-input', 'build'); let importOptions = { using: [{ transformation: 'fastbootTransform' }] }; if (config && true === config.includeUtilsScript) { app.import(path.join(assetPath, 'js', 'utils.js'), importOptions); } app.import({ development: path.join(assetPath, 'js', 'intlTelInput.js'), production: path.join(assetPath, 'js', 'intlTelInput.js.min') }, importOptions); app.import(path.join(assetPath, 'css', 'intlTelInput.css')); }, treeForPublic() { let intlTelInputImagePath = path.join(this.app.project.root, 'node_modules', 'intl-tel-input', 'build', 'img'); let publicTree = new Funnel(intlTelInputImagePath, { include: ['*.png'], destDir: 'img' }); return publicTree; }, importTransforms: function () { return { fastbootTransform: fastbootTransform } }, };
Fix the name in an error message
<?php /* Plugin Name: Opauth Plugin URI: http://labculturadigital.org/ Description: Adds Opauth (opauth.org) support Author: Laboratório de Cultura Digital - Flávio Zavan Version: 0.01 Text Domain: wp-opauth */ define('CONF_FILE', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'opauth.conf.php'); define('OPAUTH_PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'opauth' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'Opauth'); define('WPOPAUTH_PATH', dirname(__FILE__)); define('WPOPAUTH_USER_TABLE_NAME', 'wpopauth_users'); if (!file_exists(CONF_FILE)) { trigger_error( __('Configuration file missing at ' . CONF_FILE . '. Opauth disabled.'), E_USER_NOTICE); return; } require_once CONF_FILE; require_once OPAUTH_PATH . DIRECTORY_SEPARATOR . 'Opauth.php'; require_once WPOPAUTH_PATH . DIRECTORY_SEPARATOR . 'wpopauth.php'; $opauth = new WPOpauth($config); ?>
<?php /* Plugin Name: Opauth Plugin URI: http://labculturadigital.org/ Description: Adds Opauth (opauth.org) support Author: Laboratório de Cultura Digital - Flávio Zavan Version: 0.01 Text Domain: wp-opauth */ define('CONF_FILE', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'opauth.conf.php'); define('OPAUTH_PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'opauth' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'Opauth'); define('WPOPAUTH_PATH', dirname(__FILE__)); define('WPOPAUTH_USER_TABLE_NAME', 'wpopauth_users'); if (!file_exists(CONF_FILE)) { trigger_error( __('Configuration file missing at ' . CONF_FILE . '. Wordpress Opauth disabled.'), E_USER_NOTICE); return; } require_once CONF_FILE; require_once OPAUTH_PATH . DIRECTORY_SEPARATOR . 'Opauth.php'; require_once WPOPAUTH_PATH . DIRECTORY_SEPARATOR . 'wpopauth.php'; $opauth = new WPOpauth($config); ?>
Increase browser disconnect timeout in smoke tests
'use strict'; let isCI = !!process.env.CI; let smokeTests = !!process.env.SMOKE_TESTS; let config = { framework: 'qunit', test_page: smokeTests ? 'tests/index.html?smoke_tests=true' : 'tests/index.html?hidepassed', disable_watching: true, browser_start_timeout: smokeTests ? 300000 : 30000, browser_disconnect_timeout: smokeTests ? 120 : 10, browser_args: { Chrome: { mode: 'ci', args: [ // --no-sandbox is needed when running Chrome inside a container process.env.CI ? '--no-sandbox' : null, '--headless', '--disable-gpu', '--disable-dev-shm-usage', '--disable-software-rasterizer', '--mute-audio', '--remote-debugging-port=0', '--window-size=1440,900', ], }, }, launch_in_dev: ['Chrome'], launch_in_ci: ['Chrome'], }; if (isCI) { config.tap_quiet_logs = true; } module.exports = config;
'use strict'; let isCI = !!process.env.CI; let smokeTests = !!process.env.SMOKE_TESTS; let config = { framework: 'qunit', test_page: smokeTests ? 'tests/index.html?smoke_tests=true' : 'tests/index.html?hidepassed', disable_watching: true, browser_start_timeout: smokeTests ? 300000 : 30000, browser_args: { Chrome: { mode: 'ci', args: [ // --no-sandbox is needed when running Chrome inside a container process.env.CI ? '--no-sandbox' : null, '--headless', '--disable-gpu', '--disable-dev-shm-usage', '--disable-software-rasterizer', '--mute-audio', '--remote-debugging-port=0', '--window-size=1440,900', ], }, }, launch_in_dev: ['Chrome'], launch_in_ci: ['Chrome'], }; if (isCI) { config.tap_quiet_logs = true; } module.exports = config;
Fix typo in error message
/** * Module dependencies */ var _ = require('@sailshq/lodash'); /** * Give Waterline UsageErrors from blueprints a toJSON function for nicer output. */ module.exports = function(err, req) { err.toJSON = function (){ // Include the error code and the array of RTTC validation errors // for easy programmatic parsing. var jsonReadyErrDictionary = _.pick(err, ['code', 'details']); // And also include a more front-end-friendly version of the error message. var preamble = 'The server could not fulfill this request (`'+req.method+' '+req.path+'`) '+ 'due to a problem with the parameters that were sent. See the `details` for more info.'; // If NOT running in production, then provide additional details and tips. if (process.env.NODE_ENV !== 'production') { jsonReadyErrDictionary.message = preamble+' '+ '**The following additional tip will not be shown in production**: '+ 'Tip: Check your client-side code to make sure that the request data it '+ 'sends matches the expectations of the corresponding attributes in your '+ 'model. Also check that your client-side code sends data for every required attribute.'; } // If running in production, use a message that is more terse. else { jsonReadyErrDictionary.message = preamble; } //>- return jsonReadyErrDictionary; };//</define :: err.toJSON()> return err; };
/** * Module dependencies */ var _ = require('@sailshq/lodash'); /** * Give Waterline UsageErrors from blueprints a toJSON function for nicer output. */ module.exports = function(err, req) { err.toJSON = function (){ // Include the error code and the array of RTTC validation errors // for easy programmatic parsing. var jsonReadyErrDictionary = _.pick(err, ['code', 'details']); // And also include a more front-end-friendly version of the error message. var preamble = 'The server could not fulfill this request (`'+req.method+' '+req.path+'`) '+ 'due to a problem with the parameters that were sent. See the `details` for more info.'; // If NOT running in production, then provide additional details and tips. if (process.env.NODE_ENV !== 'production') { jsonReadyErrDictionary.message = preamble+' '+ '**The following additional tip will not be shown in production**: '+ 'Tip: Check your client-side code to make sure that the request data it '+ 'sends matches the expectations of the corresponding attribues in your '+ 'model. Also check that your client-side code sends data for every required attribute.'; } // If running in production, use a message that is more terse. else { jsonReadyErrDictionary.message = preamble; } //>- return jsonReadyErrDictionary; };//</define :: err.toJSON()> return err; };
Add delete old sessions command
from datetime import datetime from django.core.management.base import NoArgsCommand from django.contrib.sessions.models import Session class Command(NoArgsCommand): help = "Delete old sessions" def handle_noargs(self, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions)[:10000]: session.delete() if str(index).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
from datetime import datetime from django.core.management.base import BaseCommand from django.contrib.sessions.models import Session class Command(BaseCommand): args = '<count count ...>' help = "Delete old sessions" def handle(self, *args, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions): session.delete() if str(index).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
Use browserify plugin to collapse require ids
'use strict'; var join = require( 'path' ).join; var writeFile = require( 'fs' ).writeFileSync; var mkdirp = require( 'mkdirp' ).sync; var collapse = require( 'bundle-collapser/plugin' ); var uglify = require( 'uglify-js' ); var bundle = require( './../../lib' ); var names = [ '@stdlib/math/base/special/erf', '@stdlib/math/base/special/gamma' ]; var bopts = { 'namespace': 'flat', 'exportName': '@stdlib', 'plugins': [ collapse // convert bundle paths to IDs ] }; var dir = join( __dirname, 'build' ); bundle( names, bopts, onBundle ); function onBundle( error, bundle ) { var fpath; if ( error ) { throw error; } mkdirp( dir ); fpath = join( dir, 'bundle.js' ); writeFile( fpath, bundle ); bundle = uglify.minify( bundle.toString() ).code; fpath = join( dir, 'bundle.min.js' ); writeFile( fpath, bundle ); }
'use strict'; var join = require( 'path' ).join; var writeFile = require( 'fs' ).writeFileSync; var mkdirp = require( 'mkdirp' ).sync; var uglify = require( 'uglify-js' ); var bundle = require( './../../lib' ); var names = [ '@stdlib/math/base/special/erf', '@stdlib/math/base/special/gamma' ]; var bopts = { 'namespace': 'flat', 'exportName': '@stdlib' }; var dir = join( __dirname, 'build' ); bundle( names, bopts, onBundle ); function onBundle( error, bundle ) { var fpath; if ( error ) { throw error; } mkdirp( dir ); fpath = join( dir, 'bundle.js' ); writeFile( fpath, bundle ); bundle = uglify.minify( bundle.toString() ).code; fpath = join( dir, 'bundle.min.js' ); writeFile( fpath, bundle ); }
Deploy from asana-api-meta v0.4.5 (c7c1b64/master) by noonhub
<?php namespace Asana\Resources\Gen; class StoriesBase { public function __construct($client) { $this->client = $client; } public function findByTask($task, $params = array(), $options = array()) { $path = sprintf("/tasks/%s/stories", $task); return $this->client->getCollection($path, $params, $options); } public function findById($story, $params = array(), $options = array()) { $path = sprintf("/stories/%s", $story); return $this->client->get($path, $params, $options); } public function createOnTask($task, $params = array(), $options = array()) { $path = sprintf("/tasks/%s/stories", $task); return $this->client->post($path, $params, $options); } }
<?php namespace Asana\Resources\Gen; class StoriesBase { public function __construct($client) { $this->client = $client; } public function findById($story, $params = array(), $options = array()) { $path = sprintf("/stories/%s", $story); return $this->client->get($path, $params, $options); } public function findByTask($task, $params = array(), $options = array()) { $path = sprintf("/tasks/%s/stories", $task); return $this->client->getCollection($path, $params, $options); } public function createOnTask($task, $params = array(), $options = array()) { $path = sprintf("/tasks/%s/stories", $task); return $this->client->post($path, $params, $options); } }
Set up a default port of 5000 so it won't fail if you forget to specify one in config.yaml
from http import server from socketserver import TCPServer import os class Server: def __init__(self, own_config, config, builder): self.directory = config.folders['output'] self.port = own_config.get('port', 5000) self.builder = builder def serve(self): os.chdir(self.directory) request_handler = server.SimpleHTTPRequestHandler httpd = TCPServer(('', self.port), request_handler) try: httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() def register(plugin_config, config, commander, builder, content_renderer): server = Server(plugin_config, config, builder) commander.add('preview', server.serve, 'Serve the rendered site')
from http import server from socketserver import TCPServer import os class Server: def __init__(self, own_config, config, builder): self.directory = config.folders['output'] self.port = own_config['port'] self.builder = builder def serve(self): os.chdir(self.directory) request_handler = server.SimpleHTTPRequestHandler httpd = TCPServer(('', self.port), request_handler) try: httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() def register(plugin_config, config, commander, builder, content_renderer): server = Server(plugin_config, config, builder) commander.add('preview', server.serve, 'Serve the rendered site')
Allow debug and verbose modes to be set directly from config.
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() debug_mode = args.debug verbose = args.verbose sabotage = args.sabotage # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if setting == "DEBUG_MODE": debug_mode = value if setting == "VERBOSE_MODE": verbose = value if setting == "DEFAULT_MODULE": sabotage = value if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) botconfig.DEBUG_MODE = debug_mode if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
import argparse import botconfig from settings import wolfgame as var # Todo: Allow game modes to be set via config # Carry over settings from botconfig into settings/wolfgame.py for setting, value in botconfig.__dict__.items(): if not setting.isupper(): continue # Not a setting if not setting in var.__dict__.keys(): continue # Don't carry over config-only settings # If we got that far, it's valid setattr(var, setting, value) # Handle launch parameters # Argument --debug means start in debug mode # --verbose means to print a lot of stuff (when not in debug mode) parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--sabotage', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() botconfig.DEBUG_MODE = args.debug if not botconfig.DISABLE_DEBUG_MODE else False botconfig.VERBOSE_MODE = args.verbose botconfig.DEFAULT_MODULE = "sabotage" if args.sabotage else "wolfgame" # Initialize Database var.init_db()
Add ability to launch arb url from push
console.log('Started', self); self.addEventListener('install', function(event) { self.skipWaiting(); console.log('Installed', event); }); self.addEventListener('activate', function(event) { console.log('Activated', event); }); self.addEventListener('push', function(event) { if (event.data) { var json = event.data.json(); self.registration.showNotification(json.title, json); } }); self.addEventListener('notificationclick', function(event) { console.log('Notification click: tag ', event.notification.tag); event.notification.close(); var action = event.action || 'open-app'; var url = event.url; if (action === 'open-app') { url = '//glassycollections.com/'; } else if (action === 'record-pendant') { url = '//glassycollections.com/my/pendant_records/new'; } if (url) { event.waitUntil(clients.matchAll({ includeUncontrolled: true, type: 'window' }).then( function(activeClients) { if (activeClients.length > 0) { activeClients[0].navigate(url); activeClients[0].focus(); } else { clients.openWindow(url); } }) ); } });
console.log('Started', self); self.addEventListener('install', function(event) { self.skipWaiting(); console.log('Installed', event); }); self.addEventListener('activate', function(event) { console.log('Activated', event); }); self.addEventListener('push', function(event) { if (event.data) { var json = event.data.json(); self.registration.showNotification(json.title, json); } }); self.addEventListener('notificationclick', function(event) { console.log('Notification click: tag ', event.notification.tag); event.notification.close(); var action = event.action || 'open-app'; var url = false; if (action === 'open-app') { url = '//glassycollections.com/'; } else if (action === 'record-pendant') { url = '//glassycollections.com/my/pendant_records/new'; } if (url) { event.waitUntil(clients.matchAll({ includeUncontrolled: true, type: 'window' }).then( function(activeClients) { if (activeClients.length > 0) { activeClients[0].navigate(url); activeClients[0].focus(); } else { clients.openWindow(url); } }) ); } });
Add the ability to specify public api endpoints in Module's HTTP/Controllers/ApiController
<?php namespace TypiCMS\Modules\Core\Http\Controllers; use Illuminate\Routing\Controller; abstract class BaseApiController extends Controller { /** * Array of endpoints that do not require authorization. * */ protected $publicEndpoints = []; protected $repository; public function __construct($repository = null) { $this->middleware('api',['except' => $publicEndpoints]); $this->repository = $repository; } /** * List resources. * * @return \Illuminate\Http\JsonResponse */ public function index() { $models = $this->repository->all([], true); return response()->json($models, 200); } /** * Update the specified resource in storage. * * @param $model * * @return \Illuminate\Http\JsonResponse */ public function show($model) { return response()->json($model, 200); } /** * Update the specified resource in storage. * * @param $model * * @return \Illuminate\Http\JsonResponse */ public function edit($model) { return response()->json($model, 200); } }
<?php namespace TypiCMS\Modules\Core\Http\Controllers; use Illuminate\Routing\Controller; abstract class BaseApiController extends Controller { protected $repository; public function __construct($repository = null) { $this->middleware('api'); $this->repository = $repository; } /** * List resources. * * @return \Illuminate\Http\JsonResponse */ public function index() { $models = $this->repository->all([], true); return response()->json($models, 200); } /** * Update the specified resource in storage. * * @param $model * * @return \Illuminate\Http\JsonResponse */ public function show($model) { return response()->json($model, 200); } /** * Update the specified resource in storage. * * @param $model * * @return \Illuminate\Http\JsonResponse */ public function edit($model) { return response()->json($model, 200); } }
Update homepage field, release version 0.2
""" nubo ---- An easy way to deploy Linux VMs on different cloud providers. """ from setuptools import setup setup( name='nubo', version='0.2', url='http://pythonhosted.org/nubo', license='BSD', author='Emanuele Rocca', author_email='ema@linux.it', description='Virtual Machine deployments on multiple cloud providers', long_description=__doc__, install_requires=[ 'setuptools', 'apache-libcloud', 'paramiko', 'texttable' ], packages=['nubo', 'nubo.clouds'], scripts=['scripts/nubo'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: Internet', 'Topic :: System', ], keywords='cloud vm startup devops ec2 rackspace', )
""" nubo ---- An easy way to deploy Linux VMs on different cloud providers. """ from setuptools import setup setup( name='nubo', version='0.1', url='https://github.com/ema/nubo', license='BSD', author='Emanuele Rocca', author_email='ema@linux.it', description='Virtual Machine deployments on multiple cloud providers', long_description=__doc__, install_requires=[ 'setuptools', 'apache-libcloud', 'paramiko', 'texttable' ], packages=['nubo', 'nubo.clouds'], scripts=['scripts/nubo'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: Internet', 'Topic :: System', ], keywords='cloud vm startup devops ec2 rackspace', )
Fix for appid detection in friendsthatplay
'use strict'; var CurrentAppID, GetCurrentAppID = function() { if( !CurrentAppID ) { CurrentAppID = location.pathname.match( /\/(app|sub|friendsthatplay)\/([0-9]{1,7})/ ); if( CurrentAppID ) { CurrentAppID = parseInt( CurrentAppID[ 2 ], 10 ); } else { CurrentAppID = -1; } } return CurrentAppID; }, GetHomepage = function() { return 'https://steamdb.info/'; }, GetOption = function( items, callback ) { if( typeof chrome !== 'undefined' ) { chrome.storage.local.get( items, callback ); } else if( typeof self.options.firefox !== 'undefined' ) { for( var item in items ) { items[ item ] = self.options.preferences[ item ]; } callback( items ); } }, GetLocalResource = function( res ) { if( typeof chrome !== 'undefined' ) { return chrome.extension.getURL( res ); } else if( typeof self.options.firefox !== 'undefined' ) { return self.options[ res ]; } return res; };
'use strict'; var CurrentAppID, GetCurrentAppID = function() { if( !CurrentAppID ) { CurrentAppID = location.pathname.match( /\/(app|sub)\/([0-9]{1,7})/ ); if( CurrentAppID ) { CurrentAppID = parseInt( CurrentAppID[ 2 ], 10 ); } else { CurrentAppID = -1; } } return CurrentAppID; }, GetHomepage = function() { return 'https://steamdb.info/'; }, GetOption = function( items, callback ) { if( typeof chrome !== 'undefined' ) { chrome.storage.local.get( items, callback ); } else if( typeof self.options.firefox !== 'undefined' ) { for( var item in items ) { items[ item ] = self.options.preferences[ item ]; } callback( items ); } }, GetLocalResource = function( res ) { if( typeof chrome !== 'undefined' ) { return chrome.extension.getURL( res ); } else if( typeof self.options.firefox !== 'undefined' ) { return self.options[ res ]; } return res; };
Fix HTML help generation for TMP_DIR so it has a more generic default value.
/* * The MIT License * * Copyright (c) 2010 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.picard.cmdline; public class CreateHtmlDocForStandardOptions { public static void main(final String[] args) throws Exception { System.setProperty("java.io.tmpdir", "<System temp directory>"); System.setProperty("user.name", "<current user name>"); CommandLineParser clp = new CommandLineParser(new DummyProgram()); clp.htmlPrintOptions(System.out, true); } static class DummyProgram extends CommandLineProgram { @Override protected int doWork() { return 0; } } }
/* * The MIT License * * Copyright (c) 2010 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.picard.cmdline; public class CreateHtmlDocForStandardOptions { public static void main(final String[] args) throws Exception { CommandLineParser clp = new CommandLineParser(new DummyProgram()); clp.htmlPrintOptions(System.out, true); } static class DummyProgram extends CommandLineProgram { @Override protected int doWork() { return 0; } } }
Call connect() on the Users component only once, and cache the result. This seems to fix STRIPES-97 at last!
import React from 'react'; import Match from 'react-router/Match'; import Miss from 'react-router/Miss'; import Users from './Users'; class UsersRouting extends React.Component { constructor(props){ super(props); this.connectedUsers = props.connect(Users); } NoMatch() { return <div> <h2>Uh-oh!</h2> <p>How did you get to <tt>{this.props.location.pathname}</tt>?</p> </div> } render() { var pathname = this.props.pathname; var connect = this.props.connect; console.log("matching location:", this.props.location.pathname); return <div> <h1>Users module</h1> <Match exactly pattern={`${pathname}`} component={this.connectedUsers}/> <Match exactly pattern={`${pathname}/:query`} component={this.connectedUsers}/> <Match pattern={`${pathname}/:query?/view/:userid`} component={this.connectedUsers}/> <Miss component={this.NoMatch.bind(this)}/> </div> } } export default UsersRouting;
import React from 'react'; import Match from 'react-router/Match'; import Miss from 'react-router/Miss'; import Users from './Users'; class UsersRouting extends React.Component { NoMatch() { return <div> <h2>Uh-oh!</h2> <p>How did you get to <tt>{this.props.location.pathname}</tt>?</p> </div> } render() { var pathname = this.props.pathname; var connect = this.props.connect; console.log("matching location:", this.props.location.pathname); return <div> <h1>Users module</h1> <Match exactly pattern={`${pathname}`} component={connect(Users)}/> <Match exactly pattern={`${pathname}/:query`} component={connect(Users)}/> <Match pattern={`${pathname}/:query?/view/:userid`} component={connect(Users)}/> <Miss component={this.NoMatch.bind(this)}/> </div> } } export default UsersRouting;
Update script name and namespace
// ==UserScript== // @name Google Services List // @namespace wsmwason.google.services.list // @description List all Google services on support page, and auto redirect to product url. // @include https://support.google.com/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js // @auther wsmwason // @version 1.1 // @license MIT // @grant none // ==/UserScript== // hide show all icon $('.show-all').hide(); // display hide container $('.all-hc-container').addClass('all-hc-container-shown'); // add link redirect param for next page $('a').each(function(){ var stid = $(this).attr('st-id'); if (typeof stid !== typeof undefined && stid !== false) { $(this).attr('href', $(this).attr('href')+'&redirect=1').attr('target', '_blank'); } }); // auto redirect to product url if (location.search.indexOf('redirect=1') > 0) { // find product-icon link var productIcon = $('a.product-icon'); if (productIcon.length == 1) { var productUrl = productIcon.attr('href'); location.href = productUrl; } }
// ==UserScript== // @name Google Service List // @namespace wsmwason.google.service.list // @description List all Google services on support page, and auto redirect to product url. // @include https://support.google.com/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js // @auther wsmwason // @version 1.0 // @license MIT // @grant none // ==/UserScript== // hide show all icon $('.show-all').hide(); // display hide container $('.all-hc-container').addClass('all-hc-container-shown'); // add link redirect param for next page $('a').each(function(){ var stid = $(this).attr('st-id'); if (typeof stid !== typeof undefined && stid !== false) { $(this).attr('href', $(this).attr('href')+'&redirect=1').attr('target', '_blank'); } }); // auto redirect to product url if (location.search.indexOf('redirect=1') > 0) { // find product-icon link var productIcon = $('a.product-icon'); if (productIcon.length == 1) { var productUrl = productIcon.attr('href'); location.href = productUrl; } }
Update the PyPI version to 0.2.17
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.17', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.16', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Remove pass_event (deprecated) and replace with next
import pyrox.filtering as filtering class SimpleFilter(filtering.HttpFilter): """ This is an example of a simple filter that simply prints out the user-agent value from the header """ @filtering.handles_request_head def on_request_head(self, request_message): user_agent_header = request_message.get_header('user-agent') if user_agent_header and len(user_agent_header.values) > 0: # If there is a user-agent value then print it out and pass # the request upstream print(user_agent_header.values[0]) return filtering.next() else: # If there is no user-agent, then reject the request return filtering.reject()
import pyrox.filtering as filtering class SimpleFilter(filtering.HttpFilter): """ This is an example of a simple filter that simply prints out the user-agent value from the header """ @filtering.handles_request_head def on_request_head(self, request_message): user_agent_header = request_message.get_header('user-agent') if user_agent_header and len(user_agent_header.values) > 0: # If there is a user-agent value then print it out and pass # the request upstream print(user_agent_header.values[0]) return filtering.pass_event() else: # If there is no user-agent, then reject the request return filtering.reject()
Improve robustness of link utility functions Fixes #321, fixes #323
var url = require('url'); var path = require('path'); // Is the link an external link var isExternal = function(href) { try { return Boolean(url.parse(href).protocol); } catch(err) { } return false; }; // Return true if the link is relative var isRelative = function(href) { try { var parsed = url.parse(href); return !parsed.protocol && parsed.path && parsed.path[0] != '/'; } catch(err) {} return true; }; // Relative to absolute path // dir: directory parent of the file currently in rendering process // outdir: directory parent from the html output var toAbsolute = function(_href, dir, outdir) { // Absolute file in source _href = path.join(dir, _href); // make it relative to output _href = path.relative(outdir, _href); if (process.platform === 'win32') { _href = _href.replace(/\\/g, '/'); } return _href; }; // Join links var join = function() { var _href = path.join.apply(path, arguments); if (process.platform === 'win32') { _href = _href.replace(/\\/g, '/'); } return _href; }; module.exports = { isRelative: isRelative, isExternal: isExternal, toAbsolute: toAbsolute, join: join };
var url = require('url'); var path = require('path'); // Is the link an external link var isExternal = function(href) { return Boolean(url.parse(href).protocol); }; // Return true if the link is relative var isRelative = function(href) { var parsed = url.parse(href); return !parsed.protocol && parsed.path && parsed.path[0] != '/'; }; // Relative to absolute path // dir: directory parent of the file currently in rendering process // outdir: directory parent from the html output var toAbsolute = function(_href, dir, outdir) { // Absolute file in source _href = path.join(dir, _href); // make it relative to output _href = path.relative(outdir, _href); if (process.platform === 'win32') { _href = _href.replace(/\\/g, '/'); } return _href; }; // Join links var join = function() { var _href = path.join.apply(path, arguments); if (process.platform === 'win32') { _href = _href.replace(/\\/g, '/'); } return _href; }; module.exports = { isRelative: isRelative, isExternal: isExternal, toAbsolute: toAbsolute, join: join };
Add validation for configuring story. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\View; use Orchestra\Support\Facades\Asset; use Orchestra\Support\Facades\Widget; Event::listen('orchestra.ready: admin', 'Orchestra\Story\Services\Event\DashboardHandler@onDashboardView'); Event::listen('orchestra.form: extension.orchestra/story', 'Orchestra\Story\Services\Event\ExtensionHandler@onFormView'); Event::listen('orchestra.form: extension.orchestra/story', function () { $placeholder = Widget::make('placeholder.orchestra.extensions'); $placeholder->add('permalink')->value(View::make('orchestra/story::widgets.help')); }); Event::listen('orchestra.validate: extension.orchestra/story', function (& $rules) { $rules['page_permalink'] = array('required'); $rules['post_permalink'] = array('required'); }); Event::listen('orchestra.story.editor: markdown', function () { $asset = Asset::container('orchestra/foundation::footer'); $asset->script('editor', 'packages/orchestra/story/vendor/editor/editor.js'); $asset->style('editor', 'packages/orchestra/story/vendor/editor/editor.css'); $asset->script('storycms', 'packages/orchestra/story/js/storycms.min.js'); $asset->script('storycms.md', 'packages/orchestra/story/js/storycms.markdown.min.js', array('editor')); });
<?php use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\View; use Orchestra\Support\Facades\Asset; use Orchestra\Support\Facades\Widget; Event::listen('orchestra.ready: admin', 'Orchestra\Story\Services\Event\DashboardHandler@onDashboardView'); Event::listen('orchestra.form: extension.orchestra/story', 'Orchestra\Story\Services\Event\ExtensionHandler@onFormView'); Event::listen('orchestra.form: extension.orchestra/story', function () { $placeholder = Widget::make('placeholder.orchestra.extensions'); $placeholder->add('permalink')->value(View::make('orchestra/story::widgets.help')); }); Event::listen('orchestra.validate: extension.orchestra/story', function (& $rules) { $rules['page_permalink'] = array('required'); }); Event::listen('orchestra.story.editor: markdown', function () { $asset = Asset::container('orchestra/foundation::footer'); $asset->script('editor', 'packages/orchestra/story/vendor/editor/editor.js'); $asset->style('editor', 'packages/orchestra/story/vendor/editor/editor.css'); $asset->script('storycms', 'packages/orchestra/story/js/storycms.min.js'); $asset->script('storycms.md', 'packages/orchestra/story/js/storycms.markdown.min.js', array('editor')); });
Fix installation version info type
import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) return tuple(int(x) for x in match.groups()) def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name)
import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) return match.groups() def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name)
Update requirements where it matters
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() # I wish there was a way to do this w/o having to put data files in # package dir. Couldn't ever get data_files arg working correctly... setup( name='cdk', version='0.0.1', description='Courseware Developement Kit based on asciidoc and deck.js', long_description=readme, author='Simeon Franklin', author_email='simeonf@gmail.com', url='https://github.com/twitter-university/cdk', license=license, packages=find_packages(exclude=('tests', 'docs')), include_package_data=True, entry_points = {'console_scripts': ['cdk = cdk:main']}, install_requires=['docopt', 'pygments'], classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: Apache Software License" ] )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() # I wish there was a way to do this w/o having to put data files in # package dir. Couldn't ever get data_files arg working correctly... setup( name='cdk', version='0.0.1', description='Courseware Developement Kit based on asciidoc and deck.js', long_description=readme, author='Simeon Franklin', author_email='simeonf@gmail.com', url='https://github.com/twitter-university/cdk', license=license, packages=find_packages(exclude=('tests', 'docs')), include_package_data=True, entry_points = {'console_scripts': ['cdk = cdk:main']}, install_requires=['docopt', 'schema'], classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ] )
Replace accidental _ with space in JSDoc link.
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the general collaborator field in * {@link RawTripData} and is not an actual field in a trip document. */ export const RAW_COLLAB_EMAILS = 'collaboratorEmails'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the general collaborator field in * {@link_RawTripData} and is not an actual field in a trip document. */ export const RAW_COLLAB_EMAILS = 'collaboratorEmails'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
Add the type column for votes table
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateVotesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('votes', function (Blueprint $table) { $table->unsignedInteger('user_id'); $table->unsignedInteger('votable_id'); $table->string('votable_type')->index(); $table->enum('type', ['up_vote', 'down_vote'])->default('up_vote'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('votes'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateVotesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('votes', function (Blueprint $table) { $table->unsignedInteger('user_id'); $table->unsignedInteger('votable_id'); $table->string('votable_type')->index(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('votes'); } }
Stop Requiring Dev Packages in Production Moved dev required packages to dev if block to prevent errors when deploying to production. Closes #9
const path = require('path') const express = require('express') const app = express() app.disable('x-powered-by') const dev = process.env.NODE_ENV === 'development' if (dev) { const webpack = require('webpack') const config = require('../webpack.config') const compiler = webpack(config) const history = require('connect-history-api-fallback') require('dotenv').config() app.use(history()) app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })) app.use(require('webpack-hot-middleware')(compiler)) } else { app.use(express.static(path.resolve(__dirname, '../public'))) app.get('*', function(req, res) { res.sendFile(path.resolve(__dirname, '../public/index.html')) }) } module.exports = app
const path = require('path') const express = require('express') const webpack = require('webpack') const config = require('../webpack.config') const history = require('connect-history-api-fallback') require('dotenv').config() const app = express() app.disable('x-powered-by') const dev = process.env.NODE_ENV === 'development' if (dev) { const compiler = webpack(config) app.use(history()) app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })) app.use(require('webpack-hot-middleware')(compiler)) } else { app.use(express.static(path.resolve(__dirname, '../public'))) app.get('*', function(req, res) { res.sendFile(path.resolve(__dirname, '../public/index.html')) }) } module.exports = app
Update the documentation to reflect the changes in removing get param to the V1Meta constructor.
// **NOTE:** This assumes you have jQuery as a node module. var jquery = require('jquery'); var v1sdk = require('./../dist/v1sdk'); var hostname = "www14.v1host.com"; var instance = "v1sdktesting"; var username = "admin"; var password = "admin"; var port = "443"; var protocol = "https"; var v1 = new v1sdk.V1Meta({ hostname: hostname, instance: instance, port: port, protocol: protocol, username: username, password: password, post: function (url, data, headerObj) { // Be sure to return jquery's jqxhr object/the post results return $.ajax({ url: url, method: 'POST', data: data, headers: headerObj, // Include provided authorization headers { Authorization: 'Basic: .....' } dataType: 'json' // SDK only supports JSON from the V1 Server }); } }); // Create Asset Actual v1.create('Actual', {Value: 5.4, Date: new Date()}) .then(function (result) { console.log(result); }) .catch(function (error) { console.log(error); });
// **NOTE:** This assumes you have jQuery as a node module. var jquery = require('jquery'); var v1sdk = require('./../dist/v1sdk'); var hostname = "www14.v1host.com"; var instance = "v1sdktesting"; var username = "admin"; var password = "admin"; var port = "443"; var protocol = "https"; var v1 = new v1sdk.V1Meta({ hostname: hostname, instance: instance, port: port, protocol: protocol, username: username, password: password, post: function (url, data, headerObj) { // Be sure to return jquery's jqxhr object/the post results return $.ajax({ url: url, method: 'POST', data: data, headers: headerObj, // Include provided authorization headers { Authorization: 'Basic: .....' } dataType: 'json' // SDK only supports JSON from the V1 Server }); }, get: function (url, data) { return $.ajax({ url: url, method: 'GET', data: data, dataType: 'json' // SDK only supports JSON from the V1 Server }); } }); // Create Asset Actual v1.create('Actual', {Value: 5.4, Date: new Date()}) .then(function (result) { console.log(result); }) .catch(function (error) { console.log(error); });
feat: Add appData/plugins to plugin paths
var path = require('path'); var config = require('../config'); var paths = module.paths.map(formatPath); var globalDir = formatPath(getGlobalDir()); var appDataDir = formatPath(process.env && process.env.APPDATA); paths.unshift(formatPath(path.join(config.DATA_DIR, 'plugins'))); if (appDataDir && paths.indexOf(appDataDir) == -1) { paths.push(path.join(appDataDir, 'npm/node_modules')); } if (globalDir && paths.indexOf(globalDir) == -1) { paths.push(globalDir); } function formatPath(path) { return typeof path == 'string' ? path.replace(/\\/g, '/') : null; } function getGlobalDir() { var globalPrefix; if (process.env.PREFIX) { globalPrefix = process.env.PREFIX; } else if (process.platform === 'win32') { globalPrefix = path.dirname(process.execPath); } else { globalPrefix = path.dirname(path.dirname(process.execPath)); if (process.env.DESTDIR) { globalPrefix = path.join(process.env.DESTDIR, globalPrefix); } } if (typeof globalPrefix == 'string') { return (process.platform !== 'win32') ? path.resolve(globalPrefix, 'lib', 'node_modules') : path.resolve(globalPrefix, 'node_modules'); } } exports.getPaths = function() { return paths; };
var path = require('path'); var paths = module.paths.map(formatPath); var globalDir = formatPath(getGlobalDir()); var appDataDir = formatPath(process.env && process.env.APPDATA); if (appDataDir && paths.indexOf(appDataDir) == -1) { paths.push(path.join(appDataDir, 'npm/node_modules')); } if (globalDir && paths.indexOf(globalDir) == -1) { paths.push(globalDir); } function formatPath(path) { return typeof path == 'string' ? path.replace(/\\/g, '/') : null; } function getGlobalDir() { var globalPrefix; if (process.env.PREFIX) { globalPrefix = process.env.PREFIX; } else if (process.platform === 'win32') { globalPrefix = path.dirname(process.execPath); } else { globalPrefix = path.dirname(path.dirname(process.execPath)); if (process.env.DESTDIR) { globalPrefix = path.join(process.env.DESTDIR, globalPrefix); } } if (typeof globalPrefix == 'string') { return (process.platform !== 'win32') ? path.resolve(globalPrefix, 'lib', 'node_modules') : path.resolve(globalPrefix, 'node_modules'); } } exports.getPaths = function() { return paths; };
Enable tests for Safari 9
var argv = require('yargs').argv; module.exports = { registerHooks: function(context) { var saucelabsPlatforms = [ 'macOS 10.12/iphone@10.3', 'macOS 10.12/ipad@10.3', 'Windows 10/microsoftedge@15', 'Windows 10/internet explorer@11', 'macOS 10.12/safari@11.0', 'macOS 9.3.2/iphone@9.3' ]; var cronPlatforms = [ 'Android/chrome', 'Windows 10/chrome@59', 'Windows 10/firefox@54' ]; if (argv.env === 'saucelabs') { context.options.plugins.sauce.browsers = saucelabsPlatforms; } else if (argv.env === 'saucelabs-cron') { context.options.plugins.sauce.browsers = cronPlatforms; } } };
var argv = require('yargs').argv; module.exports = { registerHooks: function(context) { var saucelabsPlatforms = [ 'macOS 10.12/iphone@10.3', 'macOS 10.12/ipad@10.3', 'Windows 10/microsoftedge@15', 'Windows 10/internet explorer@11', 'macOS 10.12/safari@11.0' ]; var cronPlatforms = [ 'Android/chrome', 'Windows 10/chrome@59', 'Windows 10/firefox@54' ]; if (argv.env === 'saucelabs') { context.options.plugins.sauce.browsers = saucelabsPlatforms; } else if (argv.env === 'saucelabs-cron') { context.options.plugins.sauce.browsers = cronPlatforms; } } };
Add support for windows-only drawer property "win_buttonTheme" Since the background of the drawer button can be changed independently from the navigation header, so has the theme. This is an experimental feature and will for now only be documented in the windows client release notes. Change-Id: I95ffc1b26d77f193b15a93b1ee785eec5b69321c
tabris.load(function() { if (device.platform === "windows") { tabris.registerWidget("Drawer", { _type: "tabris.Drawer", _supportsChildren: true, _create: function() { tabris.ui._setCurrentDrawer(this); this._super("_create", arguments); this._setParent(tabris.ui); return this; }, _properties: { win_displayMode: { type: ["choice", ["overlay", "compactOverlay"]], default: "overlay" }, win_buttonBackground: { type: "color", default: null }, win_buttonTheme: { type: ["choice", ["light", "dark", "default"]], default: "default" } }, open: function() { this._nativeCall("open", {}); return this; }, close: function() { this._nativeCall("close", {}); return this; }, dispose: function() { tabris.ui._setCurrentDrawer(null); this._super("dispose", arguments); } }); } });
tabris.load(function() { if (device.platform === "windows") { tabris.registerWidget("Drawer", { _type: "tabris.Drawer", _supportsChildren: true, _create: function() { tabris.ui._setCurrentDrawer(this); this._super("_create", arguments); this._setParent(tabris.ui); return this; }, _properties: { win_displayMode: { type: ["choice", ["overlay", "compactOverlay"]], default: "overlay" }, win_buttonBackground: { type: "color", default: null } }, open: function() { this._nativeCall("open", {}); return this; }, close: function() { this._nativeCall("close", {}); return this; }, dispose: function() { tabris.ui._setCurrentDrawer(null); this._super("dispose", arguments); } }); } });
Add support for multiple role assertions The `https://aws.amazon.com/SAML/Attributes/Role` attribute supports single or multiple values. This fixes Awsaml to work when a multiple-value attribute is passed. Currently, the first role is always used. Support for selecting from the roles may be added later. GH-105
const url = require('url'); const express = require('express'); const router = express.Router(); module.exports = (app, auth) => { router.post('/', auth.authenticate('saml', { failureFlash: true, failureRedirect: app.get('configureUrl'), }), (req, res) => { roles = req.user['https://aws.amazon.com/SAML/Attributes/Role'] if (!Array.isArray(roles)) { roles = [roles] } const arns = roles[0].split(','); /* eslint-disable no-param-reassign */ req.session.passport.samlResponse = req.body.SAMLResponse; req.session.passport.roleArn = arns[0]; req.session.passport.principalArn = arns[1]; req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers /* eslint-enable no-param-reassign */ let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl'); frontend = new url.URL(frontend); frontend.searchParams.set('auth', 'true'); res.redirect(frontend); }); return router; };
const url = require('url'); const express = require('express'); const router = express.Router(); module.exports = (app, auth) => { router.post('/', auth.authenticate('saml', { failureFlash: true, failureRedirect: app.get('configureUrl'), }), (req, res) => { const arns = req.user['https://aws.amazon.com/SAML/Attributes/Role'].split(','); /* eslint-disable no-param-reassign */ req.session.passport.samlResponse = req.body.SAMLResponse; req.session.passport.roleArn = arns[0]; req.session.passport.principalArn = arns[1]; req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers /* eslint-enable no-param-reassign */ let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl'); frontend = new url.URL(frontend); frontend.searchParams.set('auth', 'true'); res.redirect(frontend); }); return router; };
Test the type of return value
<?php require '../simplexml2flatarray.class.php'; class SimpleXML2FlatArray_Test extends PHPUnit_Framework_TestCase { /** * Test SimpleXML2FlatArray::get() output is correct array */ public function testGetArrayOutputIsCorrectArray() { $expected_array = array( array( "child" => "child1 value", "child11" => "child11 value", "child12" => "child12 value" ), array( "child" => "child2 value", "child21" => "child21 value", "child22" => "child22 value", ) ); $xml = simplexml_load_file('testfile.xml'); $data = new SimpleXML2FlatArray($xml); $data = $data->get(); $this->assertInternalType('array', $data); $this->assertEquals($expected_array, $data); } }
<?php require '../simplexml2flatarray.class.php'; class SimpleXML2FlatArray_Test extends PHPUnit_Framework_TestCase { /** * Test SimpleXML2FlatArray::get() output is correct array */ public function testGetArrayOutputIsCorrectArray() { $expected_array = array( array( "child" => "child1 value", "child11" => "child11 value", "child12" => "child12 value" ), array( "child" => "child2 value", "child21" => "child21 value", "child22" => "child22 value" ) ); $xml = simplexml_load_file('testfile.xml'); $data = new SimpleXML2FlatArray($xml); $this->assertEquals($expected_array, $data->get()); } }