text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Correct bugs and improve feature and GUI git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@91 28e8926c-6b08-0410-baaa-805c5e19b8d6
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis * Contact: proactive-support@inria.fr * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.examples.penguin; public interface PenguinMessageReceiver { public void receiveMessage(String s); public void receiveMessage(String s, java.awt.Color c); }
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis * Contact: proactive-support@inria.fr * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.examples.penguin; public interface PenguinMessageReceiver { public void receiveMessage(String s); }
Add license, long description and fix classifiers.
#!/usr/bin/env python # coding=utf-8 __author__ = 'kulakov.ilya@gmail.com' from setuptools import setup from sys import platform REQUIREMENTS = [] if platform.startswith('darwin'): REQUIREMENTS.append('pyobjc >= 2.5') setup( name="power", version="1.2", description="Cross-platform system power status information.", long_description="Library that allows you get current power source type (AC, Battery or UPS), warning level (none, <22%, <10min) and remaining minutes. You can also observe changes of power source and remaining time.", author="Ilya Kulakov", author_email="kulakov.ilya@gmail.com", url="https://github.com/Kentzo/Power", platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"], packages=['power'], license="MIT License", classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: System :: Monitoring', 'Topic :: System :: Power (UPS)', ], install_requires=REQUIREMENTS )
#!/usr/bin/env python # coding=utf-8 __author__ = 'kulakov.ilya@gmail.com' from setuptools import setup from sys import platform REQUIREMENTS = [] if platform.startswith('darwin'): REQUIREMENTS.append('pyobjc >= 2.5') setup( name="power", version="1.2", description="Cross-platform system power status information.", author="Ilya Kulakov", author_email="kulakov.ilya@gmail.com", url="https://github.com/Kentzo/Power", platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"], packages=['power'], classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: System :: Monitoring' 'Topic :: System :: Power (UPS)', ], install_requires=REQUIREMENTS )
Remove broken backward compatibility hack
--- --- var Collections = (function(window, undefined) { /* * Listing of all the collections and documents. Generated * automatically by Jekyll and used e.g for the auto-linking * feature. Don't edit this file unless you are sure what you are * doing. */ var listing = { {% for c in site.collections %} "{{ c.label }}": [{% for d in c.docs %} { "title": "{{ d.title }}", "url": "{{ site.baseurl }}{{ d.url }}", },{% endfor %} ], {% endfor %} }; return { listing: listing, }; })(window);
--- --- var Collections = (function(window, undefined) { /* * Listing of all the collections and documents. Generated * automatically by Jekyll and used e.g for the auto-linking * feature. Don't edit this file unless you are sure what you are * doing. */ var listing = { {% for i in site.collections %}{% comment %}Allow site.collections to be either hash (older jekyll) or list (newer){% endcomment %}{% if i[1] %}{% assign c = i[1] %}{% else %}{% assign c = i %}{% endif %} "{{ c.label }}": [{% for d in c.docs %} { "title": "{{ d.title }}", "url": "{{ site.baseurl }}{{ d.url }}", },{% endfor %} ], {% endfor %} }; return { listing: listing, }; })(window);
Reset page number when selecting a different resource
import { Controller } from "controllers/controller.js"; import { mapName } from "utils.js"; import { Ajax } from "ajax.js"; export class ResourcesController extends Controller { constructor(base) { super(base); this.model = { selected: "0" }; } /** * Retrieves the list of available resources from the API, then gets columns for each when done */ load(after) { this.ajax.call("") .then(response => { this.model.store = Object.keys(response).map((x, i) => { let out = mapName(x, i); out.columns = []; out.selected = false; return out; }); this.viewModel = new Vue({ el: "#resources", data: this.model, methods: { selectResource: this.selectResource } }); if (after) after(); }); } /** * Returns the resource currently selected by the select#resources element */ getSelected() { return this.model.store[this.model.selected]; } /** * Resets search results when selecting a different resource. */ selectResource (i) { $("#table").remove(); $("#btnPrev, #btnNext").prop("disabled", true); $VueDemo.default.table.page = 1; } }
import { Controller } from "controllers/controller.js"; import { mapName } from "utils.js"; import { Ajax } from "ajax.js"; export class ResourcesController extends Controller { constructor(base) { super(base); this.model = { selected: "0" }; } /** * Retrieves the list of available resources from the API, then gets columns for each when done */ load(after) { this.ajax.call("") .then(response => { this.model.store = Object.keys(response).map((x, i) => { let out = mapName(x, i); out.columns = []; out.selected = false; return out; }); this.viewModel = new Vue({ el: "#resources", data: this.model, methods: { selectResource: this.selectResource } }); if (after) after(); }); } /** * Returns the resource currently selected by the select#resources element */ getSelected() { return this.model.store[this.model.selected]; } selectResource (i) { $("#table").remove(); $("#btnPrev, #btnNext").prop("disabled", true); $VueDemo.page = 1; } }
Add function to configure store for server-side rendering
import { createStore, applyMiddleware, compose } from 'redux'; import { reduxReactRouter } from 'redux-router'; import thunk from 'redux-thunk'; import createHistory from 'history/lib/createBrowserHistory'; import routes from '../routes'; import createLogger from 'redux-logger'; import rootReducer from '../reducers'; const finalCreateStore = compose( applyMiddleware(thunk), applyMiddleware(createLogger()), reduxReactRouter({ routes, createHistory }) )(createStore); export default function configureStore(initialState) { const store = finalCreateStore(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers'); store.replaceReducer(nextRootReducer); }); } return store; } const finalCreateServerStore = compose( applyMiddleware(thunk), reduxReactRouter({ routes, createHistory }) )(createStore); export default function configureServerStore(initialState) { return finalCreateServerStore(rootReducer, initialState); }
import { createStore, applyMiddleware, compose } from 'redux'; import { reduxReactRouter } from 'redux-router'; import thunk from 'redux-thunk'; import createHistory from 'history/lib/createBrowserHistory'; import routes from '../routes'; import createLogger from 'redux-logger'; import rootReducer from '../reducers'; const finalCreateStore = compose( applyMiddleware(thunk), applyMiddleware(createLogger()), reduxReactRouter({ routes, createHistory }) )(createStore); export default function configureStore(initialState) { const store = finalCreateStore(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers'); store.replaceReducer(nextRootReducer); }); } return store; }
Allow return of raw translations
<?php namespace Modules\Translation\ValueObjects; use Illuminate\Support\Collection; class TranslationGroup { /** * @var array */ private $translations; public function __construct(array $translations) { $this->translations = $translations; } /** * @param array $translationsRaw * @return Collection */ private function reArrangeTranslations(array $translationsRaw) { $translations = []; foreach ($translationsRaw as $locale => $translationGroup) { foreach ($translationGroup as $key => $translation) { $translations[$key][$locale] = $translation; } } return new Collection($translations); } /** * Return the translations * @return Collection */ public function all() { return $this->reArrangeTranslations($this->translations);; } /** * Return the raw translations * @return array */ public function allRaw() { return $this->translations; } }
<?php namespace Modules\Translation\ValueObjects; use Illuminate\Support\Collection; class TranslationGroup { /** * @var Collection */ private $translations; public function __construct(array $translations) { $this->translations = $this->reArrangeTranslations($translations); } /** * @param array $translationsRaw * @return Collection */ private function reArrangeTranslations(array $translationsRaw) { $translations = []; foreach ($translationsRaw as $locale => $translationGroup) { foreach ($translationGroup as $key => $translation) { $translations[$key][$locale] = $translation; } } return new Collection($translations); } /** * Return the translations * @return Collection */ public function all() { return $this->translations; } }
Fix stream sending undefined as an x-auth-token
/*global Promise:true*/ 'use strict'; var EventSource = global.EventSource || require('eventsource') , Promise = require('rsvp').Promise ; var _source; var Streamable = { listen: { value: function () { return new Promise(function (resolve, reject) { var source , url = this.url; if (this.token && this.token.token) { url = url + '?x-auth-token=' + this.token.token; } try { source = _source = this.cacheStream && _source || new EventSource(url); } catch (e) { return reject(e); } return resolve(source); }.bind(this)); } } }; module.exports = Streamable;
/*global Promise:true*/ 'use strict'; var EventSource = global.EventSource || require('eventsource') , Promise = require('rsvp').Promise ; var _source; var Streamable = { listen: { value: function () { return new Promise(function (resolve, reject) { var source , url = this.url; if (this.token) { url = url + '?x-auth-token=' + this.token.token; } try { source = _source = this.cacheStream && _source || new EventSource(url); } catch (e) { return reject(e); } return resolve(source); }.bind(this)); } } }; module.exports = Streamable;
Update so collector has a default wait if unspecified
package jamex.link; import java.util.Collection; import java.util.LinkedList; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.jms.Message; import javax.jms.MessageListener; import static org.junit.Assert.*; final class MessageCollector implements MessageListener { private static final int MAX_MESSAGE_COUNT = 10; private static final long DEFAULT_WAIT = 100L; private final LinkedBlockingQueue<Message> m_messages = new LinkedBlockingQueue<Message>( MAX_MESSAGE_COUNT ); @Override public void onMessage( final Message message ) { m_messages.add( message ); } Collection<Message> expectMessageCount( final int expectedMessageCount ) throws InterruptedException { return expectMessageCount( expectedMessageCount, DEFAULT_WAIT ); } Collection<Message> expectMessageCount( final int expectedMessageCount, final long maxWait ) throws InterruptedException { final LinkedList<Message> results = new LinkedList<Message>(); final long start = System.currentTimeMillis(); long now; while( results.size() < expectedMessageCount && ( ( now = System.currentTimeMillis() ) < start + maxWait ) ) { final long waitTime = Math.max( 1, start + maxWait - now ); final Message message = m_messages.poll( waitTime, TimeUnit.MILLISECONDS ); results.add( message ); } assertEquals( "Expected message count", expectedMessageCount, results.size() ); return results; } }
package jamex.link; import java.util.Collection; import java.util.LinkedList; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.jms.Message; import javax.jms.MessageListener; import static org.junit.Assert.*; final class MessageCollector implements MessageListener { private static final int MAX_MESSAGE_COUNT = 10; private final LinkedBlockingQueue<Message> m_messages = new LinkedBlockingQueue<Message>( MAX_MESSAGE_COUNT ); @Override public void onMessage( final Message message ) { m_messages.add( message ); } Collection<Message> expectMessageCount( final int expectedMessageCount, final long maxWait ) throws InterruptedException { final LinkedList<Message> results = new LinkedList<Message>(); final long start = System.currentTimeMillis(); long now; while( results.size() < expectedMessageCount && ( ( now = System.currentTimeMillis() ) < start + maxWait ) ) { final long waitTime = Math.max( 1, start + maxWait - now ); final Message message = m_messages.poll( waitTime, TimeUnit.MILLISECONDS ); results.add( message ); } assertEquals( "Expected message count", expectedMessageCount, results.size() ); return results; } }
Clean up and better jshint support.
/* jshint unused:vars, sub:true */ /* global window, define, module */ (function () { "use strict"; var JSON_ = {}; function snakeToCamelCase(key) { // first_name -> firstName return key.replace(/(_+[a-z])/g, function (snip) { return snip.toUpperCase().replace("_", ""); }); } function camelToSnakeCase(key) { // firstName -> first_name return key.replace(/([A-Z])/g, function (snip) { return "_" + snip.toLowerCase(); }); } JSON_.parse = function parse(text, reviver) { text = text.replace(/"([^"]*)"\s*:/g, snakeToCamelCase); return JSON.parse(text, reviver); }; JSON_.stringify = function stringify(value, replacer, space) { var str = JSON.stringify(value, replacer, space); return str.replace(/"([^"]*)"\s*:/g, camelToSnakeCase); }; // Export to popular environments boilerplate. if (typeof define === "function" && define.amd) { define(JSON_); } else if (typeof module !== "undefined" && module.exports) { module.exports = JSON_; } else { window["JSON_"] = JSON_; } }());
(function (window) { "use strict"; var JSON_ = {}; function snakeToCamelCase(key) { // first_name -> firstName return key.replace(/(_+[a-z])/g, function (snip) { return snip.toUpperCase().replace("_", ""); }); } function camelToSnakeCase(key) { // firstName -> first_name return key.replace(/([A-Z])/g, function (snip) { return "_" + snip.toLowerCase(); }); } JSON_.parse = function parse(text, reviver) { text = text.replace(/"([^"]*)"\s*:/g, snakeToCamelCase); return JSON.parse(text, reviver); }; JSON_.stringify = function stringify(value, replacer, space) { var str = JSON.stringify(value, replacer, space); return str.replace(/"([^"]*)"\s*:/g, camelToSnakeCase); }; // Export to popular environments boilerplate. if (typeof define === "function" && define.amd) { define(JSON_); } else if (typeof module !== "undefined" && module.exports) { module.exports = JSON_; } else { window["JSON_"] = JSON_; } }(window));
Remove unused imports (and try out tmux)
from flask import Flask from flask.ext.restful import Api from mongoengine import connect from models import Tweet, Topic from models.routing import register_api_model from collecting.routes import CollectorListResource, CollectorResource import config app = Flask(__name__, static_url_path='') api = Api(app, prefix='/api') connect(config.db_name, host=config.db_host, port=config.db_port, username=config.db_user, password=config.db_pass) @app.route('/') def index(): return app.send_static_file('index.html') # register api models register_api_model(api, Topic) register_api_model(api, Tweet) # collectors resource api.add_resource(CollectorListResource, '/collectors') api.add_resource(CollectorResource, '/collectors/<topic_pk>') if __name__ == '__main__': import sys app.run(debug='--debug' in sys.argv)
import json from flask import Flask, request, abort from flask.ext.restful import Resource, Api from mongoengine import connect from models import Tweet, Topic from models.routing import register_api_model, ModelResource from collecting.routes import CollectorListResource, CollectorResource from helpers import get_request_json import config app = Flask(__name__, static_url_path='') api = Api(app, prefix='/api') connect(config.db_name, host=config.db_host, port=config.db_port, username=config.db_user, password=config.db_pass) @app.route('/') def index(): return app.send_static_file('index.html') # register api models register_api_model(api, Topic) register_api_model(api, Tweet) # collectors resource api.add_resource(CollectorListResource, '/collectors') api.add_resource(CollectorResource, '/collectors/<topic_pk>') if __name__ == '__main__': import sys app.run(debug='--debug' in sys.argv)
Refactor availability zone functional test Using json format output in availability zone list functional test Change-Id: I7098b1c3bee680e47e414dcb4fa272628cdec1eb
# 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 json from openstackclient.tests.functional import base class AvailabilityZoneTests(base.TestCase): """Functional tests for availability zone. """ def test_availability_zone_list(self): cmd_output = json.loads(self.openstack( 'availability zone list -f json')) zones = [x['Zone Name'] for x in cmd_output] self.assertIn( 'internal', zones ) self.assertIn( 'nova', zones )
# 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 openstackclient.tests.functional import base class AvailabilityZoneTests(base.TestCase): """Functional tests for availability zone. """ HEADERS = ["'Zone Name'"] # So far, all components have the same default availability zone name. DEFAULT_AZ_NAME = 'nova' def test_availability_zone_list(self): opts = self.get_opts(self.HEADERS) raw_output = self.openstack('availability zone list' + opts) self.assertIn(self.DEFAULT_AZ_NAME, raw_output)
Add junit test for SystemPropertyProvider.
package de.mvitz.jprops.core.impl.provider; import static org.fest.assertions.Assertions.assertThat; import org.junit.Test; public class SystemPropertyProviderTest { @Test public void nonPrefixProviderShouldUseGivenKey() throws Exception { System.setProperty("abc", "foo"); try { assertThat(new SystemPropertyProvider().get("abc")).isEqualTo("foo"); } finally { System.clearProperty("abc"); } } @Test public void prefixProviderShouldUseGivenPrefixAndKey() throws Exception { System.setProperty("abc", "foo"); try { assertThat(new SystemPropertyProvider("ab").get("c")).isEqualTo("foo"); } finally { System.clearProperty("abc"); } } @Test public void providerShouldReturnNullWhenNoPropertyIsFound() throws Exception { assertThat(new SystemPropertyProvider().get("abc")).isNull(); } }
package de.mvitz.jprops.core.impl.provider; import static org.fest.assertions.Assertions.assertThat; import org.junit.Test; public class SystemPropertyProviderTest { @Test public void nonPrefixProviderShouldUseGivenKey() throws Exception { System.setProperty("abc", "foo"); try { assertThat(new SystemPropertyProvider().get("abc")).isEqualTo("foo"); } finally { System.clearProperty("abc"); } } @Test public void prefixProviderShouldUseGivenPrefixAndKey() throws Exception { System.setProperty("abc", "foo"); try { assertThat(new SystemPropertyProvider("ab").get("c")).isEqualTo("foo"); } finally { System.clearProperty("abc"); } } }
Test against testting as default ember port.
"use strict"; const test = require('tape'); const randoPort = require('../../lib/randoport'); const _ = require('lodash'); test('empty object', t => { t.plan(1); const emptyObject = {}; const r = randoPort(emptyObject); t.equal(typeof r.port, 'number'); }); test('object with other properties', t => { t.plan(4); const obj = { a: false, b: 'test', c: 99 }; const r = randoPort(obj); t.equal(obj.a, false); t.equal(obj.b, 'test'); t.equal(obj.c, 99); t.equal(typeof r.port, 'number'); }); test('randoPort returns new object', t => { t.plan(1); const o = {}; t.notEqual(o, randoPort(o)); }); test('object with existing port or blacklisted port', t => { t.plan(10000); let i = 0; for(i; i < 5000; i +=1) { const o = { "port": _.random(4000, 4999) }; const r = randoPort(o); t.notEqual(o.port, r.port); t.notEqual(4200, r.port); } }); // test('when 4200 is generated as port', t => {});
"use strict"; const test = require('tape'); const randoPort = require('../../lib/randoport'); const _ = require('lodash'); test('empty object', t => { t.plan(1); const emptyObject = {}; const r = randoPort(emptyObject); t.equal(typeof r.port, 'number'); }); test('object with other properties', t => { t.plan(4); const obj = { a: false, b: 'test', c: 99 }; const r = randoPort(obj); t.equal(obj.a, false); t.equal(obj.b, 'test'); t.equal(obj.c, 99); t.equal(typeof r.port, 'number'); }); test('randoPort returns new object', t => { t.plan(1); const o = {}; t.notEqual(o, randoPort(o)); }); test('object with existing port', t => { t.plan(5000); let i = 0; for(i; i < 5000; i +=1) { const o = { "port": _.random(4000, 4999) }; t.notEqual(o.port, randoPort(o).port); } }); // test('when 4200 is generated as port', t => {});
Add a description, because metadata is hard.
import sys from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) try: from atomiclong import ffi except ImportError: ext_modules=[] else: ext_modules=[ffi.verifier.get_extension()] with open('README.rst') as r: README = r.read() setup( name='atomiclong', version='0.1.1', author='David Reid', author_email='dreid@dreid.org', url='https://github.com/dreid/atomiclong', description="An AtomicLong type using CFFI.", long_description=README, license='MIT', py_modules=['atomiclong'], setup_requires=['cffi'], install_requires=['cffi'], tests_require=['pytest'], ext_modules=ext_modules, zip_safe=False, cmdclass={"test": PyTest}, )
import sys from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) try: from atomiclong import ffi except ImportError: ext_modules=[] else: ext_modules=[ffi.verifier.get_extension()] with open('README.rst') as r: README = r.read() setup( name='atomiclong', version='0.1', author='David Reid', author_email='dreid@dreid.org', url='https://github.com/dreid/atomiclong', long_description=README, license='MIT', py_modules=['atomiclong'], setup_requires=['cffi'], install_requires=['cffi'], tests_require=['pytest'], ext_modules=ext_modules, zip_safe=False, cmdclass={"test": PyTest}, )
Include dev comment on solution
#!/bin/python3 import math import os import random import re import sys # See https://en.wikipedia.org/wiki/Longest_common_subsequence_problem # This solution creates the matrix described in "Traceback approach" def common_child(s1, s2): matrix = [[0 for i in range(len(s2) + 1)] for j in range(len(s1)+ 1)] for row_i in range(len(s1)): for col_i in range(len(s2)): if s1[row_i] == s2[col_i]: matrix[row_i + 1][col_i + 1] = matrix[row_i][col_i] + 1 else: matrix[row_i + 1][col_i + 1] = max(matrix[row_i+1][col_i], matrix[row_i][col_i + 1]) return matrix[len(s1)][len(s2)] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s1 = input() s2 = input() result = common_child(s1, s2) fptr.write(str(result) + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # See https://en.wikipedia.org/wiki/Longest_common_subsequence_problem def commonChild(s1, s2): matrix = [[0 for i in range(len(s2) + 1)] for j in range(len(s1)+ 1)] for row_i in range(len(s1)): for col_i in range(len(s2)): if s1[row_i] == s2[col_i]: matrix[row_i + 1][col_i + 1] = matrix[row_i][col_i] + 1 else: matrix[row_i + 1][col_i + 1] = max(matrix[row_i+1][col_i], matrix[row_i][col_i + 1]) return matrix[len(s1)][len(s2)] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s1 = input() s2 = input() result = commonChild(s1, s2) fptr.write(str(result) + '\n') fptr.close()
Return status when executing tests with DiscoverRunner
#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'sqjobs', 'sqjobs.tests', 'sqjobs.contrib.django.djsqjobs' ), 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'USE_TZ': 'true', 'SILENCED_SYSTEM_CHECKS': ["1_7.W001"], } if not settings.configured: settings.configure(**DEFAULT_SETTINGS) if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__) ))) sys.path.insert(0, parent) from django.test.runner import DiscoverRunner res = DiscoverRunner(failfast=False).run_tests([ 'sqjobs.tests' ], verbosity=1) os._exit(res)
#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'sqjobs', 'sqjobs.tests', 'sqjobs.contrib.django.djsqjobs' ), 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'USE_TZ': 'true', 'SILENCED_SYSTEM_CHECKS': ["1_7.W001"], } if not settings.configured: settings.configure(**DEFAULT_SETTINGS) if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__) ))) sys.path.insert(0, parent) from django.test.runner import DiscoverRunner DiscoverRunner(failfast=False).run_tests([ 'sqjobs.tests' ], verbosity=1)
refactor(listable): Allow override of options group name
"use strict"; module.exports = listableOptions; function listableOptions(yargs, group = "Command Options:") { return yargs.options({ json: { group, describe: "Show information as a JSON array", type: "boolean", }, ndjson: { group, describe: "Show information as newline-delimited JSON", type: "boolean", }, a: { group, describe: "Show private packages that are normally hidden", type: "boolean", alias: "all", }, l: { group, describe: "Show extended information", type: "boolean", alias: "long", }, p: { group, describe: "Show parseable output instead of columnified view", type: "boolean", alias: "parseable", }, toposort: { group, describe: "Sort packages in topological order instead of lexical by directory", type: "boolean", }, graph: { group, describe: "Show dependency graph as a JSON-formatted adjacency list", type: "boolean", }, }); }
"use strict"; module.exports = listableOptions; function listableOptions(yargs) { return yargs.options({ json: { group: "Command Options:", describe: "Show information as a JSON array", type: "boolean", }, ndjson: { group: "Command Options:", describe: "Show information as newline-delimited JSON", type: "boolean", }, a: { group: "Command Options:", describe: "Show private packages that are normally hidden", type: "boolean", alias: "all", }, l: { group: "Command Options:", describe: "Show extended information", type: "boolean", alias: "long", }, p: { group: "Command Options:", describe: "Show parseable output instead of columnified view", type: "boolean", alias: "parseable", }, toposort: { group: "Command Options:", describe: "Sort packages in topological order instead of lexical by directory", type: "boolean", }, graph: { group: "Command Options:", describe: "Show dependency graph as a JSON-formatted adjacency list", type: "boolean", }, }); }
BAP-6919: Add Title field to User - do not show in grid by default
<?php namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_9; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\QueryBag; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope; class OroUserBundle implements Migration { /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { self::addTitleColumn($schema); } /** * @param Schema $schema */ public static function addTitleColumn(Schema $schema) { $userTable = $schema->getTable('oro_user'); $userTable->addColumn( 'title', 'string', [ 'length' => 255, 'oro_options' => [ 'extend' => ['owner' => ExtendScope::OWNER_CUSTOM], 'datagrid' => ['is_visible' => false], ], ] ); } }
<?php namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_9; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroUserBundle implements Migration { /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { self::addTitleColumn($schema); } /** * @param Schema $schema */ public static function addTitleColumn(Schema $schema) { $userTable = $schema->getTable('oro_user'); $userTable->addColumn( 'title', 'string', [ 'length' => 255, 'oro_options' => [ 'extend' => ['owner' => ExtendScope::OWNER_CUSTOM], 'datagrid' => ['is_visible' => true], 'merge' => ['display' => true], ], ] ); } }
Add column support for sql server
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
Change 'check' to 'passes' in a vs. an check
"""Unit tests for MAU101.""" from check import Check from proselint.checks.garner import a_vs_an as chk class TestCheck(Check): """Test garner.a_vs_n.""" __test__ = True @property def this_check(self): """Boilerplate.""" return chk def test(self): """Ensure the test works correctly.""" assert self.passes("""An apple a day keeps the doctor away.""") assert self.passes("""The Epicurean garden.""") assert not self.passes("""A apple a day keeps the doctor away.""") assert not self.passes("""An apple an day keeps the doctor away.""") assert not self.passes("""An apple an\nday keeps the doctor away.""")
"""Unit tests for MAU101.""" from check import Check from proselint.checks.garner import a_vs_an as chk class TestCheck(Check): """Test garner.a_vs_n.""" __test__ = True @property def this_check(self): """Boilerplate.""" return chk def test(self): """Ensure the test works correctly.""" assert self.check("""An apple a day keeps the doctor away.""") assert self.check("""The Epicurean garden.""") assert not self.check("""A apple a day keeps the doctor away.""") assert not self.check("""An apple an day keeps the doctor away.""") assert not self.check("""An apple an\nday keeps the doctor away.""")
Fix impersonated user check issue.
'use strict'; const builder = require('botbuilder'); const timesheet = require('./timesheet'); module.exports = exports = [(session) => { builder.Prompts.text(session, 'Please tell me your domain user?'); }, (session, results, next) => { session.send('Ok. Searching for your stuff...'); session.sendTyping(); timesheet .searchColleagues(results.response) .then((colleagues) => { console.log('Found %s', colleagues.length); session.userData = colleagues[0]; session.userData.impersonated = true; }).catch((ex) => { console.log(ex); }).finally(() => { next(); }); }, (session) => { if (!session.userData.impersonated) { return session.endDialog('Oops! Couldn\'t impersonate'); } session.endDialog('(y)'); }];
'use strict'; const builder = require('botbuilder'); const timesheet = require('./timesheet'); module.exports = exports = [(session) => { builder.Prompts.text(session, 'Please tell me your domain user?'); }, (session, results, next) => { session.send('Ok. Searching for your stuff...'); session.sendTyping(); timesheet .searchColleagues(results.response) .then((colleagues) => { session.userData = colleagues[0]; session.userData.impersonated = true; }).catch((ex) => { console.log(ex); }).finally(() => { next(); }); }, (session) => { if (!session.impersonated) { console.log('Oops! Couldn\'t impersonate'); return session.endDialog('Oops! Couldn\'t impersonate'); } session.endDialog('(y)'); }];
Add user functionality to Pig Latin class
class Pig_latin(object): vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"] def __init__(self): self.sentence = raw_input("Enter a sentence to be converted into pig latin: ") print self.convert_sentence() while True: play_again = raw_input("Do you want to play again? Type yes or no ").lower() if play_again == "yes": Pig_latin() break elif play_again == "no": print "thanks for playing!" break else: print "Please type yes or no!" def convert_sentence(self): new_sentence = self.sentence.split(" ") converted_sentence = [] for word in new_sentence: if word[0] in self.vowels: converted_sentence.append(word) else: converted_sentence.append(''.join(self.word_converter(word))) return (' ').join(converted_sentence) def word_converter(self,word): solution = list(word) for letter in list(word): if letter not in self.vowels: solution.remove(letter) solution.append(letter) else: break solution.append("ay") return solution Pig_latin()
class Pig_latin(object): vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"] def __init__(self, sentence): self.sentence = sentence print self.convert_sentence() def convert_sentence(self): new_sentence = self.sentence.split(" ") converted_sentence = [] for word in new_sentence: if word[0] in self.vowels: converted_sentence.append(word) else: converted_sentence.append(''.join(self.word_converter(word))) return (' ').join(converted_sentence) def word_converter(self,word): solution = list(word) for letter in list(word): if letter not in self.vowels: solution.remove(letter) solution.append(letter) else: break solution.append("ay") return solution Pig_latin("Hello eric ryan there")
import: Implement YAML file compilation into 'bytecode' Store serialized Python structures resulted from loading YAML source in the .ymlc files, a-la .pyc
import subprocess class YamlValidationError(Exception): pass class Base(object): schema_file = '' @classmethod def validate(cls, meta): if 'marshalled' in meta and meta['marshalled']: return cls.validatefile(meta['filename']) @classmethod def validatefile(cls, filename): kwalify = subprocess.Popen(['kwalify', '-lf', cls.schema_file, filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = kwalify.communicate() if stdout.find('INVALID') >= 0 or stderr.find('ERROR') >= 0: raise YamlValidationError('Failed to validate file: %s\n\nValidator output: \n%s' % (filename, stderr + stdout)) @classmethod def _create_class(cls, meta, dct): cls.schema_file = meta['filename'] return type(meta['class']['name'], (Base,), {'schema_file': meta['filename']})
import subprocess class YamlValidationError(Exception): pass class Base(object): schema_file = '' @classmethod def validate(cls, filename): kwalify = subprocess.Popen(['kwalify', '-lf', cls.schema_file, filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = kwalify.communicate() if stdout.find('INVALID') >= 0 or stderr.find('ERROR') >= 0: raise YamlValidationError('Failed to validate file: %s\n\nValidator output: \n%s' % (filename, stderr + stdout)) @classmethod def _create_class(cls, meta, dct): cls.schema_file = meta['filename'] return type(meta['class']['name'], (Base,), {'schema_file': meta['filename']})
Revert change to watch script invocation
var childProcess = require('child_process'); var fs = require('fs-extra'); var glob = require('glob'); var path = require('path'); var sortPackageJson = require('sort-package-json'); // Run a production build with Typescript source maps. childProcess.execSync('npm run build:prod', {stdio:[0,1,2]}); // Update the package.app.json file. var data = require('./package.json'); data['scripts']['build'] = 'webpack' data['scripts']['watch'] = 'webpack --watch' data['jupyterlab']['outputDir'] = '..'; data['jupyterlab']['linkedPackages'] = {}; text = JSON.stringify(sortPackageJson(data), null, 2) + '\n'; fs.writeFileSync('./package.app.json', text); // Update our app index file. fs.copySync('./index.js', './index.app.js'); // Add the release metadata. var release_data = { version: data.jupyterlab.version }; text = JSON.stringify(release_data, null, 2) + '\n'; fs.writeFileSync('./build/release_data.json', text);
var childProcess = require('child_process'); var fs = require('fs-extra'); var glob = require('glob'); var path = require('path'); var sortPackageJson = require('sort-package-json'); // Run a production build with Typescript source maps. childProcess.execSync('npm run build:prod', {stdio:[0,1,2]}); // Update the package.app.json file. var data = require('./package.json'); data['scripts']['build'] = 'webpack' data['scripts']['watch'] = "concurrently \"webpack --watch\" \"node watch\"" data['jupyterlab']['outputDir'] = '..'; data['jupyterlab']['linkedPackages'] = {}; text = JSON.stringify(sortPackageJson(data), null, 2) + '\n'; fs.writeFileSync('./package.app.json', text); // Update our app index file. fs.copySync('./index.js', './index.app.js'); // Add the release metadata. var release_data = { version: data.jupyterlab.version }; text = JSON.stringify(release_data, null, 2) + '\n'; fs.writeFileSync('./build/release_data.json', text);
Fix displaying of the matrix.
from fractions import Fraction from parser import Parser class LinearProgram: def __init__(self): self.nbVariables = 0 self.nbConstraints = 0 self.objective = None self.tableaux = None self.variableFromIndex = {} self.indexFromVariable = {} def __str__(self): return '\n'.join(' '.join(str(y).ljust(6) for y in x) for x in self.tableaux.tolist()) if __name__ == '__main__': lp = LinearProgram() parser = Parser(lp, 'example.in') parser.parse() print(lp.variableFromIndex) print(lp.indexFromVariable) print(lp.nbVariables) print(lp.nbConstraints) print(lp)
from fractions import Fraction from parser import Parser class LinearProgram: def __init__(self): self.nbVariables = 0 self.nbConstraints = 0 self.objective = None self.tableaux = None self.variableFromIndex = {} self.indexFromVariable = {} def __str__(self): return '\n'.join(' '.join(str(y) for y in x) for x in self.tableaux.tolist()) if __name__ == '__main__': lp = LinearProgram() parser = Parser(lp, 'example.in') parser.parse() print(lp.variableFromIndex) print(lp.indexFromVariable) print(lp.nbVariables) print(lp.nbConstraints) print(lp)
Add default host and port to karma server
module.exports = function(config){ config.set({ basePath : '../', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/js/**/*.js', 'test/unit/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['PhantomJS'], hostname: process.env.IP || 'localhost', port: process.env.PORT || '9876', plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-phantomjs-launcher' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' }, }); };
module.exports = function(config){ config.set({ basePath : '../', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/js/**/*.js', 'test/unit/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['PhantomJS'], hostname: process.env.IP, port: process.env.PORT, plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-phantomjs-launcher' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' }, }); };
Fix focus state when field has value
(function () { 'use strict'; moj.Modules.LabelPlaceholder = { el: '.js-LabelPlaceholder', className: 'is-focused', init: function () { _.bindAll(this, 'render', 'renderEach', 'onFocus', 'onFocusOut'); this.cacheEls(); this.bindEvents(); }, cacheEls: function () { this.$inputs = $(this.el); }, bindEvents: function () { // set focused selector to parent label this.$inputs .on('focus', this.onFocus) .on('focusout', this.onFocusOut); moj.Events.on('render', this.render); }, render: function () { this.$inputs.each(this.renderEach); }, renderEach: function (i, el) { var $el = $(el); if ($el.val() !== '') { $el.addClass(this.className); } }, onFocus: function (e) { $(e.target).addClass(this.className); }, onFocusOut: function (e) { var $el = $(e.target); if ($el.val() === '') { $el.removeClass(this.className); } } }; }());
(function () { 'use strict'; moj.Modules.LabelPlaceholder = { el: '.js-LabelPlaceholder', className: 'is-focused', init: function () { _.bindAll(this, 'render', 'onFocus', 'onFocusOut'); this.cacheEls(); this.bindEvents(); }, cacheEls: function () { this.$inputs = $(this.el); }, bindEvents: function () { // set focused selector to parent label this.$inputs .on('focus', this.onFocus) .on('focusout', this.onFocusOut); moj.Events.on('render', this.render); }, render: function () { // if an input has value, give focused class this.$inputs.each(function (i, el) { var $el = $(el); if ($el.val() !== '') { $el.addClass(this.className); } }); }, onFocus: function (e) { $(e.target).addClass(this.className); }, onFocusOut: function (e) { var $el = $(e.target); if ($el.val() === '') { $el.removeClass(this.className); } } }; }());
Clarify why rules are used
module.exports = { "env": { "amd": true, "browser": true, "mocha": true, "node": true }, "parserOptions": { "ecmaVersion": 6 }, "globals": { "Promise": "readonly", "WebMidi": "readonly", "expect": "readonly" }, "extends": ["eslint:recommended", "prettier"], // The idea here is to stick to the rules defined by Prettier (https://prettier.io/) and only make // exceptions in ESLint when absolutely necessary. "rules": { // Rules to align ESLint with Prettier (even though we are already using eslint-config-prettier) "indent": ["error", 2], "semi": ["error", "always"], "quote-props": ["error", "as-needed"], "quotes": ["error", "double", {"avoidEscape": true, "allowTemplateLiterals": true}], // Rules that knowingly change the default Prettier behaviour "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "linebreak-style": ["error", "unix"], // Force \n instead of Prettier's auto-detect behaviour "no-trailing-spaces": ["error", { "skipBlankLines": true, "ignoreComments": true }], "max-len": ["error", { "code": 100 }], // Prettier's 80 is too small. Period. "no-console": ["error", { "allow": ["info", "warn", "error"] }] // Only some (unlike Prettier) } };
module.exports = { "env": { "amd": true, "browser": true, "mocha": true, "node": true }, "parserOptions": { "ecmaVersion": 6 }, "globals": { "Promise": "readonly", "WebMidi": "readonly", "expect": "readonly" }, "extends": ["eslint:recommended", "prettier"], "rules": { "indent": ["error", 2], "linebreak-style": ["error", "unix"], "max-len": ["error", { "code": 100 }], "no-console": ["error", { "allow": ["info", "warn", "error"] }], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "no-trailing-spaces": ["error", { "skipBlankLines": true, "ignoreComments": true }], "no-underscore-dangle": "off", "quote-props": ["error", "as-needed"], "quotes": ["error", "double", {"avoidEscape": true, "allowTemplateLiterals": true}], "semi": ["error", "always"] } };
Fix bug in validator summary statistics
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain; import java.util.concurrent.atomic.AtomicInteger; /** * @author Emerson Farrugia */ public class ValidationSummary { private AtomicInteger attempted = new AtomicInteger(); private AtomicInteger succeeded = new AtomicInteger(); private AtomicInteger failed = new AtomicInteger(); public void incrementAttempted() { attempted.incrementAndGet(); } public int getAttempted() { return attempted.get(); } public void incrementSucceeded() { succeeded.incrementAndGet(); } public int getSucceeded() { return succeeded.get(); } public void incrementFailed() { failed.incrementAndGet(); } public int getFailed() { return failed.get(); } }
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain; import java.util.concurrent.atomic.AtomicInteger; /** * @author Emerson Farrugia */ public class ValidationSummary { private AtomicInteger attempted = new AtomicInteger(); private AtomicInteger succeeded = new AtomicInteger(); private AtomicInteger failed = new AtomicInteger(); public void incrementAttempted() { attempted.incrementAndGet(); } public int getAttempted() { return attempted.get(); } public void incrementSucceeded() { succeeded.incrementAndGet(); } public int getSucceeded() { return succeeded.get(); } public void incrementFailed() { succeeded.incrementAndGet(); } public int getFailed() { return failed.get(); } }
Add new testing model `School` Issue #43
from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.Model): name = models.CharField(max_length=10) allotted_rooms = models.ManyToManyField(ClassRoom) allotted_labs = models.ManyToManyField(Lab) def __unicode__(self): return unicode(self.name) class Employee(models.Model): name = models.CharField(max_length=30) salary = models.FloatField() dept = models.ForeignKey(Dept) manager = models.ForeignKey('Employee', null=True, blank=True) def __unicode__(self): return unicode(self.name) class Word(models.Model): word = models.CharField(max_length=15) def __unicode__(self): return unicode(self.word) class School(models.Model): classes = models.ManyToManyField(ClassRoom)
from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.Model): name = models.CharField(max_length=10) allotted_rooms = models.ManyToManyField(ClassRoom) allotted_labs = models.ManyToManyField(Lab) def __unicode__(self): return unicode(self.name) class Employee(models.Model): name = models.CharField(max_length=30) salary = models.FloatField() dept = models.ForeignKey(Dept) manager = models.ForeignKey('Employee', null=True, blank=True) def __unicode__(self): return unicode(self.name) class Word(models.Model): word = models.CharField(max_length=15) def __unicode__(self): return unicode(self.word)
Remove cb argument from evaluate() and mark as async. Co-Authored-By: Andreas Lind <9d09920e13870a2871b35105baa9dce1d35b3390@gmail.com>
var extractSnippets = require('./extractSnippets'); var evaluateSnippets = require('./evaluateSnippets'); class Snippets { constructor(snippets) { this.items = snippets; } async evaluate(options) { return evaluateSnippets(this.items, options).then(() => this); } get(index) { return this.items[index]; } getTests() { var tests = []; var evaluatedExampleIndex; for (const [index, snippet] of this.items.entries()) { var flags = snippet.flags; switch (snippet.lang) { case 'javascript': if (flags.evaluate) { evaluatedExampleIndex = index; tests.push({ code: snippet.code, flags: flags }); } break; case 'output': if (evaluatedExampleIndex === index - 1) { tests[tests.length - 1].output = snippet.code; } break; } } return tests; } } module.exports = { fromMarkdown: function(markdown) { return new Snippets(extractSnippets(markdown)); } };
var extractSnippets = require('./extractSnippets'); var evaluateSnippets = require('./evaluateSnippets'); class Snippets { constructor(snippets) { this.items = snippets; } evaluate(options, cb) { return evaluateSnippets(this.items, options).then(() => this); } get(index) { return this.items[index]; } getTests() { var tests = []; var evaluatedExampleIndex; for (const [index, snippet] of this.items.entries()) { var flags = snippet.flags; switch (snippet.lang) { case 'javascript': if (flags.evaluate) { evaluatedExampleIndex = index; tests.push({ code: snippet.code, flags: flags }); } break; case 'output': if (evaluatedExampleIndex === index - 1) { tests[tests.length - 1].output = snippet.code; } break; } } return tests; } } module.exports = { fromMarkdown: function(markdown) { return new Snippets(extractSnippets(markdown)); } };
Improve Faye/Bayeux coverage in widget specs.
import { test , moduleForComponent } from 'appkit/tests/helpers/module-for'; import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; moduleForComponent('dashboard-widget', 'Unit - Dashboard widget component', { subject: function() { // Mock Faye/bayeux subscribe process; avoid network calls. var bayeuxStub = { subscribe: Ember.K }; var subscribeStub = sinon.stub(bayeuxStub, 'subscribe', function() { var subscribedStub = { then: Ember.K }; sinon.stub(subscribedStub, 'then'); return subscribedStub; }); var obj = DashboardWidgetComponent.create({ bayeux: bayeuxStub, channel: 'awesome-metrics' }); return obj; } }); test('it exists', function() { ok(this.subject() instanceof DashboardWidgetComponent); }); test('it subscribes using #bayeux', function() { ok(this.subject().get('bayeux').subscribe.calledOnce); }); test('it subscribes to #channel', function() { ok(this.subject().get('bayeux').subscribe.calledWith("/awesome-metrics")); });
import { test , moduleForComponent } from 'appkit/tests/helpers/module-for'; import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; moduleForComponent('dashboard-widget', 'Unit - Dashboard widget component', { subject: function() { var bayeuxStub = { subscribe: Ember.K }; var subscribeStub = sinon.stub(bayeuxStub, 'subscribe', function() { var subscribedStub = { then: Ember.K }; sinon.stub(subscribedStub, 'then'); return subscribedStub; }); var obj = DashboardWidgetComponent.create({ bayeux: bayeuxStub, channel: '/awesome-metrics' }); return obj; } }); test('it exists', function() { ok(this.subject() instanceof DashboardWidgetComponent); }); test('subscribes to its channel', function() { ok(this.subject().get('bayeux').subscribe.calledOnce); });
Add transformation in the pipeline according to their position
package x2x.translator.xcodeml.transformation; import java.util.ArrayList; import x2x.translator.xcodeml.xelement.XcodeProg; import x2x.translator.xcodeml.transformer.Transformer; /** * An dependent transformation group check wether it can be transformed with * another pending transformation in the pipeline. Each transformation are * applied only once. */ public class DependentTransformationGroup<T extends Transformation<? super T>> extends TransformationGroup<T> { public DependentTransformationGroup(String name) { super(name); } public void applyTranslations(XcodeProg xcodeml, Transformer transformer){ for(int i = 0; i < _translations.size(); ++i){ T base = _translations.get(i); for(int j = i + 1; j < _translations.size(); ++j){ T candidate = _translations.get(j); if(candidate.isTransformed()){ continue; } if(base.canBeTransformedWith(candidate)){ base.transform(xcodeml, transformer, candidate); } } } } // In the dependent transformation group, the order in which transformation // appears is important public void add(T translation){ int linePosition = translation.getStartLine(); int insertIndex = 0; for(Transformation t : _translations){ if(t.getStartLine() > linePosition){ break; } ++insertIndex; } _translations.add(insertIndex, translation); } }
package x2x.translator.xcodeml.transformation; import java.util.ArrayList; import x2x.translator.xcodeml.xelement.XcodeProg; import x2x.translator.xcodeml.transformer.Transformer; /** * An dependent transformation group check wether it can be transformed with * another pending transformation in the pipeline. Each transformation are * applied only once. */ public class DependentTransformationGroup<T extends Transformation<? super T>> extends TransformationGroup<T> { public DependentTransformationGroup(String name) { super(name); } public void applyTranslations(XcodeProg xcodeml, Transformer transformer){ for(int i = 0; i < _translations.size(); ++i){ T base = _translations.get(i); for(int j = i + 1; j < _translations.size(); ++j){ T candidate = _translations.get(j); if(candidate.isTransformed()){ continue; } if(base.canBeTransformedWith(candidate)){ base.transform(xcodeml, transformer, candidate); } } } } }
Add missing return value in PHPDoc
<?php /* * This file is part of the Active Collab Authentication project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ namespace ActiveCollab\Authentication\Adapter; use ActiveCollab\Authentication\AuthenticatedUser\AuthenticatedUserInterface; use ActiveCollab\Authentication\AuthenticationResult\AuthenticationResultInterface; use Psr\Http\Message\ServerRequestInterface; /** * @package ActiveCollab\Authentication\Adapter */ interface AdapterInterface { /** * Initialize authentication layer and see if we have a user who's already logged in. * * @param ServerRequestInterface $request * @param null $authenticated_with * @return AuthenticatedUserInterface|null */ public function initialize(ServerRequestInterface $request, &$authenticated_with = null); /** * Authenticate with given credential against authentication source. * * @param ServerRequestInterface $request * @param bool $check_password * @return AuthenticationResultInterface */ public function authenticate(ServerRequestInterface $request, $check_password = true); /** * Terminate an instance that was used to authenticate a user. * * @param AuthenticationResultInterface $authenticated_with */ public function terminate(AuthenticationResultInterface $authenticated_with); }
<?php /* * This file is part of the Active Collab Authentication project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ namespace ActiveCollab\Authentication\Adapter; use ActiveCollab\Authentication\AuthenticatedUser\AuthenticatedUserInterface; use ActiveCollab\Authentication\AuthenticationResult\AuthenticationResultInterface; use Psr\Http\Message\ServerRequestInterface; /** * @package ActiveCollab\Authentication\Adapter */ interface AdapterInterface { /** * Initialize authentication layer and see if we have a user who's already logged in. * * @param ServerRequestInterface $request * @param null $authenticated_with * @return AuthenticatedUserInterface */ public function initialize(ServerRequestInterface $request, &$authenticated_with = null); /** * Authenticate with given credential against authentication source. * * @param ServerRequestInterface $request * @param bool $check_password * @return AuthenticationResultInterface */ public function authenticate(ServerRequestInterface $request, $check_password = true); /** * Terminate an instance that was used to authenticate a user. * * @param AuthenticationResultInterface $authenticated_with */ public function terminate(AuthenticationResultInterface $authenticated_with); }
Fix typo in profile doc description build
#! /bin/env python import os from typing import Any, Dict, Generator, Iterable, Type from isort.profiles import profiles OUTPUT_FILE = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "../docs/configuration/profiles.md") ) HEADER = """Built-in Profile for isort ======== The following profiles are built into isort to allow easy interoperability with common projects and code styles. To use any of the listed profiles, use `isort --profile PROFILE_NAME` from the command line, or `profile=PROFILE_NAME` in your configuration file. """ def format_profile(profile_name: str, profile: Dict[str, Any]) -> str: options = "\n".join(f" - **{name}**: `{repr(value)}`" for name, value in profile.items()) return f""" #{profile_name} {profile.get('description', '')} {options} """ def document_text() -> str: return f"{HEADER}{''.join(format_profile(profile_name, profile) for profile_name, profile in profiles.items())}" def write_document(): with open(OUTPUT_FILE, "w") as output_file: output_file.write(document_text()) if __name__ == "__main__": write_document()
#! /bin/env python import os from typing import Any, Dict, Generator, Iterable, Type from isort.profiles import profiles OUTPUT_FILE = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "../docs/configuration/profiles.md") ) HEADER = """Built-in Profile for isort ======== The following profiles are built into isort to allow easy interoperability with common projects and code styles. To use any of the listed profiles, use `isort --profile PROFILE_NAME` from the command line, or `profile=PROFILE_NAME` in your configuration file. """ def format_profile(profile_name: str, profile: Dict[str, Any]) -> str: options = "\n".join(f" - **{name}**: `{repr(value)}`" for name, value in profile.items()) return f""" #{profile_name} {profile.get('descripiton', '')} {options} """ def document_text() -> str: return f"{HEADER}{''.join(format_profile(profile_name, profile) for profile_name, profile in profiles.items())}" def write_document(): with open(OUTPUT_FILE, "w") as output_file: output_file.write(document_text()) if __name__ == "__main__": write_document()
Allow custom positions to be passed through
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(source => new Promise(resolve => { const img = new Image(); img.onload = () => resolve(Object.assign({}, source, {img})); img.src = source.src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(...images.map(image => image.img.width)); canvas.height = Math.max(...images.map(image => image.img.height)); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(src => new Promise(resolve => { const img = new Image(); img.onload = () => resolve(img); img.src = src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(images.map(img => img.width)); canvas.height = Math.max(images.map(img => img.height)); // Draw images to canvas images.forEach(img => ctx.drawImage(img, 0, 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
Add new PyPi classifier "Development Status"
from setuptools import setup, find_packages setup( name="yasha", author="Kim Blomqvist", author_email="kblomqvist@iki.fi", version="1.1", description="A command-line tool to render Jinja templates", keywords=["jinja", "code generator"], packages=find_packages(), include_package_data=True, install_requires=[ "Click", "Jinja2", "pytoml", "pyyaml", ], entry_points=''' [console_scripts] yasha=yasha.scripts.yasha:cli ''', classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Software Development :: Code Generators", "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: MIT License", ], url="https://github.com/kblomqvist/yasha", download_url="https://github.com/kblomqvist/yasha/tarball/1.1", )
from setuptools import setup, find_packages setup( name="yasha", author="Kim Blomqvist", author_email="kblomqvist@iki.fi", version="1.1", description="A command-line tool to render Jinja templates", keywords=["jinja", "code generator"], packages=find_packages(), include_package_data=True, install_requires=[ "Click", "Jinja2", "pytoml", "pyyaml", ], entry_points=''' [console_scripts] yasha=yasha.scripts.yasha:cli ''', classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Software Development :: Code Generators", ], url="https://github.com/kblomqvist/yasha", download_url="https://github.com/kblomqvist/yasha/tarball/1.1", )
Make it usable as a plugin or a standalone module
/* * grunt-build-info * https://github.com/r3b/grunt-build-info * * Copyright (c) 2014 ryan bridges * Licensed under the APLv2 license. */ 'use strict'; var getConfiguration = require("../lib/services"); var merge = require('merge'); function registerTasks(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('set_build_info', 'Set the global build_info.', function(val) { // grunt.config.set("BUILD_INFO", val); console.log("VAL", val); global["BUILD_INFO"]=val; }); grunt.registerMultiTask('build_info', 'Import build info from CI systems', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ service : 'unknown', buildId : 'unknown', commitId : 'unknown', build : 'unknown', branch : 'unknown' }); global["BUILD_INFO"]=merge(options, getConfiguration()); }); } module.exports = function(grunt){ if(grunt){ registerTasks(grunt); }else{ return getConfiguration; } };
/* * grunt-build-info * https://github.com/r3b/grunt-build-info * * Copyright (c) 2014 ryan bridges * Licensed under the APLv2 license. */ 'use strict'; var getConfiguration = require("../lib/services"); var merge = require('merge'); module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('set_build_info', 'Set the global build_info.', function(val) { // grunt.config.set("BUILD_INFO", val); console.log("VAL", val); global["BUILD_INFO"]=val; }); grunt.registerMultiTask('build_info', 'Import build info from CI systems', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ service : 'unknown', buildId : 'unknown', commitId : 'unknown', build : 'unknown', branch : 'unknown' }); global["BUILD_INFO"]=merge(options, getConfiguration()); }); };
Fix duplicate payment profile handling
<?php namespace Omnipay\AuthorizeNet\Message; /** * Authorize.Net CIM Get payment profiles Response */ class CIMGetProfileResponse extends CIMCreatePaymentProfileResponse { protected $xmlRootElement = 'getCustomerProfileResponse'; /** * Get the payment profile id corresponding to the specified last4 by looking into the payment profiles * of the customer * * @param $last4 * * @return null|string */ public function getMatchingPaymentProfileId($last4) { if (!$this->isSuccessful()) { return null; } foreach ($this->data['profile'][0]['paymentProfiles'] as $paymentProfile) { // For every payment profile check if the last4 matches the last4 of the card in request. $cardLast4 = substr($paymentProfile['payment'][0]['creditCard'][0]['cardNumber'], -4); if ($last4 == $cardLast4) { return (string)$paymentProfile['customerPaymentProfileId']; } } return null; } public function getCustomerPaymentProfileId() { if ($this->isSuccessful()) { return $this->request->getCustomerPaymentProfileId(); } return null; } }
<?php namespace Omnipay\AuthorizeNet\Message; /** * Authorize.Net CIM Get payment profiles Response */ class CIMGetProfileResponse extends CIMCreatePaymentProfileResponse { protected $xmlRootElement = 'getCustomerProfileResponse'; /** * Get the payment profile id corresponding to the specified last4 by looking into the payment profiles * of the customer * * @param $last4 * * @return null|string */ public function getMatchingPaymentProfileId($last4) { if (!$this->isSuccessful()) { return null; } foreach ($this->data['profile'][0]['paymentProfiles'] as $paymentProfile) { // For every payment profile check if the last4 matches the last4 of the card in request. $cardLast4 = substr($paymentProfile['payment'][0]['creditCard'][0]['cardNumber'][0], -4); if ($last4 == $cardLast4) { return (string)$paymentProfile['customerPaymentProfileId']; } } return null; } public function getCustomerPaymentProfileId() { if ($this->isSuccessful()) { return $this->request->getCustomerPaymentProfileId(); } return null; } }
Fix setting rotation to 0
import multiprocessing import unicornhathd as unicornhat import importlib import sys import os import app.programs.hd class State: ''' Handles the Unicorn HAT state''' def __init__(self): self._process = None def start_program(self, name, params={}): try: program = getattr(app.programs.hd, name) except AttributeError: raise ProgramNotFound(name) self.stop_program() if params.get("brightness") is not None: unicornhat.brightness(float(params["brightness"])) if params.get("rotation") is not None: unicornhat.rotation(int(params["rotation"])) self._process = multiprocessing.Process(target=program.run, args=(params,)) self._process.start() def stop_program(self): if self._process is not None: self._process.terminate() unicornhat.show() class ProgramNotFound(Exception): pass
import multiprocessing import unicornhathd as unicornhat import importlib import sys import os import app.programs.hd class State: ''' Handles the Unicorn HAT state''' def __init__(self): self._process = None def start_program(self, name, params={}): try: program = getattr(app.programs.hd, name) except AttributeError: raise ProgramNotFound(name) self.stop_program() if params.get("brightness"): unicornhat.brightness(float(params["brightness"])) if params.get("rotation"): unicornhat.rotation(int(params["rotation"])) self._process = multiprocessing.Process(target=program.run, args=(params,)) self._process.start() def stop_program(self): if self._process is not None: self._process.terminate() unicornhat.show() class ProgramNotFound(Exception): pass
Solve a possible problem caused by name collision
'use strict'; const amqp = require('amqplib'); const debug = require('debug')('node-apimanager:amqp-sender'); class Rabbit { constructor(uri, monitor) { this.URI = uri; this.listen = monitor; } listenQueue() { let listen = this.listen; amqp.connect(this.URI).then( (conn) => conn.createChannel().then( (ch) => { ch.assertQueue(listen).then( () => { ch.consume(listen, (msg) => { let msgContent = JSON.parse(msg.content.toString()); debug(' [*] RECV @ %s', msg.properties.correlationId.toString()); }, { noAck: true }); }); })).catch((err) => { debug(err); }); } } const listener = new Rabbit(process.env.AMQP_URI, process.env.LISTEN_Q); listener.listenQueue();
'use strict'; const amqp = require('amqplib'); const debug = require('debug')('node-apimanager:amqp-sender'); class Rabbit { constructor(uri, monitor) { this.URI = uri; this.listen = monitor; } listen() { let listen = this.listen; amqp.connect(this.URI).then( (conn) => conn.createChannel().then( (ch) => { ch.assertQueue(listen).then( () => { ch.consume(listen, (msg) => { let msgContent = JSON.parse(msg.content.toString()); debug(' [*] RECV @ %s', msg.properties.correlationId.toString()); }, { noAck: true }); }); })).catch((err) => { debug(err); }); } } const listener = new Rabbit(process.env.AMQP_URI, process.env.LISTEN_Q); listener.listen();
scripts/examples: Fix VSYNC GPIO LED pin name.
# VSYNC GPIO output example. # # This example shows how to toggle a pin on VSYNC interrupt. import sensor, image, time from pyb import Pin sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) # This pin will be toggled on/off on VSYNC rising and falling edges. led_pin = Pin('LEDB', Pin.OUT_PP, Pin.PULL_NONE) sensor.set_vsync_callback(lambda state, led=led_pin: led_pin.value(state)) clock = time.clock() # Create a clock object to track the FPS. while(True): clock.tick() # Update the FPS clock. img = sensor.snapshot() # Take a picture and return the image. print(clock.fps()) # Note: OpenMV Cam runs about half as fast when connected # to the IDE. The FPS should increase once disconnected.
# VSYNC GPIO output example. # # This example shows how to toggle a pin on VSYNC interrupt. import sensor, image, time from pyb import Pin sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) # This pin will be toggled on/off on VSYNC rising and falling edges. led_pin = Pin('LED_BLUE', Pin.OUT_PP, Pin.PULL_NONE) sensor.set_vsync_callback(lambda state, led=led_pin: led_pin.value(state)) clock = time.clock() # Create a clock object to track the FPS. while(True): clock.tick() # Update the FPS clock. img = sensor.snapshot() # Take a picture and return the image. print(clock.fps()) # Note: OpenMV Cam runs about half as fast when connected # to the IDE. The FPS should increase once disconnected.
Replace deprecated imp usage with importlib
from importlib import machinery from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple(machinery.all_suffixes()) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, 'Loader')] def get_submodules(package): submodules = ("%s.%s" % (package.__name__, module) for module in package_contents(package)) return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]]) for module in submodules] def package_contents(package): package_path = dirname(loaders.__file__) contents = set([splitext(module)[0] for module in listdir(package_path) if module.endswith(MODULE_EXTENSIONS)]) return contents
import imp from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, 'Loader')] def get_submodules(package): submodules = ("%s.%s" % (package.__name__, module) for module in package_contents(package)) return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]]) for module in submodules] def package_contents(package): package_path = dirname(loaders.__file__) contents = set([splitext(module)[0] for module in listdir(package_path) if module.endswith(MODULE_EXTENSIONS)]) return contents
Add status as a query param for orders state
angular.module('orderCloud') .config(OrdersConfig) ; function OrdersConfig($stateProvider) { $stateProvider .state('orders', { parent: 'account', templateUrl: 'myOrders/orders/templates/orders.html', controller: 'OrdersCtrl', controllerAs: 'orders', data: { pageTitle: 'Orders' }, url: '/orders/:tab?fromDate&toDate&search&page&pageSize&searchOn&sortBy&status&filters', resolve: { Parameters: function($stateParams, ocParameters){ return ocParameters.Get($stateParams); }, OrderList: function(Parameters, CurrentUser, ocOrders){ return ocOrders.List(Parameters, CurrentUser); } } }); }
angular.module('orderCloud') .config(OrdersConfig) ; function OrdersConfig($stateProvider) { $stateProvider .state('orders', { parent: 'account', templateUrl: 'myOrders/orders/templates/orders.html', controller: 'OrdersCtrl', controllerAs: 'orders', data: { pageTitle: 'Orders' }, url: '/orders/:tab?fromDate&toDate&search&page&pageSize&searchOn&sortBy&filters', resolve: { Parameters: function($stateParams, ocParameters){ return ocParameters.Get($stateParams); }, OrderList: function(Parameters, CurrentUser, ocOrders){ return ocOrders.List(Parameters, CurrentUser); } } }); }
Remove tenant req from task query
from uuid import UUID from zeus import auth from zeus.config import celery from zeus.constants import Result, Status from zeus.models import Build from zeus.notifications import email @celery.task(name='zeus.tasks.send_build_notifications', max_retries=None) def send_build_notifications(build_id: UUID): build = Build.query.unrestricted_unsafe().get(build_id) if not build: raise ValueError('Unable to find build with id = {}'.format(build_id)) auth.set_current_tenant(auth.Tenant( repository_ids=[build.repository_id])) # double check that the build is still finished and only send when # its failing if build.result != Result.failed or build.status != Status.finished: return email.send_email_notification(build=build)
from uuid import UUID from zeus import auth from zeus.config import celery from zeus.constants import Result, Status from zeus.models import Build from zeus.notifications import email @celery.task(name='zeus.tasks.send_build_notifications', max_retries=None) def send_build_notifications(build_id: UUID): build = Build.query.get(build_id) if not build: raise ValueError('Unable to find build with id = {}'.format(build_id)) auth.set_current_tenant(auth.Tenant( repository_ids=[build.repository_id])) # double check that the build is still finished and only send when # its failing if build.result != Result.failed or build.status != Status.finished: return email.send_email_notification(build=build)
Change comment on suite a bit
package com.adaptc.mws.plugins; /** * This enumeration represents which suite or context Moab Web Services is running in. * @author bsaville */ public enum Suite { HPC("HPC"), CLOUD("Cloud"); /** * The default suite for MWS. This is equivalent to {@link #CLOUD}. */ public static final Suite DEFAULT_SUITE = Suite.CLOUD; private String str; private Suite(String str) { this.str = str; } /** * Returns the suite in a human-readable string, such as "Cloud" for {@link #CLOUD} and "HPC" for * {@link #HPC}. * @return A human-readable string */ public String toString() { return str; } /** * Returns {@link #DEFAULT_SUITE} by default if none is found matching. This is a * case insensitive match. Spaces and underscores are also equivalent for parsing. * @param suite The suite as a string * @return The corresponding suite value */ public static Suite parseString(String suite) { for(Suite val : values()) { if (val.toString().equalsIgnoreCase(suite) || val.name().equalsIgnoreCase(suite)) return val; } return DEFAULT_SUITE; } /** * A helper method to make sure that a true Suite reference may be used. * @param suite An actual suite value * @return The suite parameter */ public static Suite parseString(Suite suite) { return suite; } }
package com.adaptc.mws.plugins; /** * This enum represents which suite or context Moab Web Services is running in - * HPC or Cloud. * @author bsaville */ public enum Suite { HPC("HPC"), CLOUD("Cloud"); /** * The default suite for MWS. This is equivalent to {@link #CLOUD}. */ public static final Suite DEFAULT_SUITE = Suite.CLOUD; private String str; private Suite(String str) { this.str = str; } /** * Returns the suite in a human-readable string, such as "Cloud" for {@link #CLOUD} and "HPC" for * {@link #HPC}. * @return A human-readable string */ public String toString() { return str; } /** * Returns {@link #DEFAULT_SUITE} by default if none is found matching. This is a * case insensitive match. Spaces and underscores are also equivalent for parsing. * @param suite The suite as a string * @return The corresponding suite value */ public static Suite parseString(String suite) { for(Suite val : values()) { if (val.toString().equalsIgnoreCase(suite) || val.name().equalsIgnoreCase(suite)) return val; } return DEFAULT_SUITE; } /** * A helper method to make sure that a true Suite reference may be used. * @param suite An actual suite value * @return The suite parameter */ public static Suite parseString(Suite suite) { return suite; } }
Fix ordering of gulp tasks
var gulp = require('gulp'); var jade = require('gulp-jade'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var minifyCSS = require('gulp-minify-css'); gulp.task('jade', function() { var locals = {}; return gulp.src('templates/*.jade') .pipe(jade({ locals: locals })) .pipe(gulp.dest('./dist/')); }); gulp.task('minify-js', function() { return gulp.src('js/*.js') .pipe(concat('tmp.js')) .pipe(uglify()) .pipe(rename('app.js')) .pipe(gulp.dest('./dist/js/')); }); gulp.task('copy-imgs', function() { return gulp.src('imgs/*') .pipe(gulp.dest('./dist/imgs/')); }); gulp.task('minify-css', function() { return gulp.src('css/*.css') .pipe(concat('tmp.css')) .pipe(minifyCSS()) .pipe(rename('app.css')) .pipe(gulp.dest('./dist/css/')); }); gulp.task('copy-to-www', ['default'], function() { return gulp.src('./dist/**') .pipe(gulp.dest('/var/www/esk.email/')); }); gulp.task('default', ['jade', 'minify-js', 'minify-css', 'copy-imgs']); gulp.task('deploy', ['copy-to-www']);
var gulp = require('gulp'); var jade = require('gulp-jade'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var minifyCSS = require('gulp-minify-css'); gulp.task('jade', function() { var locals = {}; return gulp.src('templates/*.jade') .pipe(jade({ locals: locals })) .pipe(gulp.dest('./dist/')); }); gulp.task('minify-js', function() { return gulp.src('js/*.js') .pipe(concat('tmp.js')) .pipe(uglify()) .pipe(rename('app.js')) .pipe(gulp.dest('./dist/js/')); }); gulp.task('copy-imgs', function() { return gulp.src('imgs/*') .pipe(gulp.dest('./dist/imgs/')); }); gulp.task('minify-css', function() { return gulp.src('css/*.css') .pipe(concat('tmp.css')) .pipe(minifyCSS()) .pipe(rename('app.css')) .pipe(gulp.dest('./dist/css/')); }); gulp.task('copy-to-www', function() { return gulp.src('./dist/**') .pipe(gulp.dest('/var/www/esk.email/')); }); gulp.task('default', ['jade', 'minify-js', 'minify-css', 'copy-imgs']); gulp.task('deploy', ['default', 'copy-to-www']);
Add helper methods that convert a FindIterable to a List and Stream
package ch.rasc.eds.starter.util; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.bson.conversions.Bson; import com.mongodb.client.FindIterable; import com.mongodb.client.model.Sorts; import ch.ralscha.extdirectspring.bean.ExtDirectStoreReadRequest; import ch.ralscha.extdirectspring.bean.SortDirection; import ch.ralscha.extdirectspring.bean.SortInfo; public abstract class QueryUtil { public static List<Bson> getSorts(ExtDirectStoreReadRequest request) { List<Bson> sorts = new ArrayList<>(); for (SortInfo sortInfo : request.getSorters()) { if (sortInfo.getDirection() == SortDirection.ASCENDING) { sorts.add(Sorts.ascending(sortInfo.getProperty())); } else { sorts.add(Sorts.descending(sortInfo.getProperty())); } } return sorts; } public static <T> List<T> toList(FindIterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false) .collect(Collectors.toList()); } public static <T> Stream<T> stream(FindIterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); } }
package ch.rasc.eds.starter.util; import java.util.ArrayList; import java.util.List; import org.bson.conversions.Bson; import com.mongodb.client.model.Sorts; import ch.ralscha.extdirectspring.bean.ExtDirectStoreReadRequest; import ch.ralscha.extdirectspring.bean.SortDirection; import ch.ralscha.extdirectspring.bean.SortInfo; public abstract class QueryUtil { public static List<Bson> getSorts(ExtDirectStoreReadRequest request) { List<Bson> sorts = new ArrayList<>(); for (SortInfo sortInfo : request.getSorters()) { if (sortInfo.getDirection() == SortDirection.ASCENDING) { sorts.add(Sorts.ascending(sortInfo.getProperty())); } else { sorts.add(Sorts.descending(sortInfo.getProperty())); } } return sorts; } }
Return max possible total count when `countSynchronously` is true, calculate limit and offset
<?php /** * ActiveRecord for API * * @link https://github.com/hiqdev/yii2-hiart * @package yii2-hiart * @license BSD-3-Clause * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/) */ namespace hiqdev\hiart; class ActiveDataProvider extends \yii\data\ActiveDataProvider { /** * @var ActiveQuery the query that is used to fetch data models and [[totalCount]] * if it is not explicitly set */ public $query; /** * To improve performance, implemented grid summary and pager loading via AJAX when this attribute is `false` * There is a possibility set this attribute via DI * @see \hipanel\base\SearchModelTrait::search() * * @var bool */ public bool $countSynchronously = false; public function enableSynchronousCount(): void { $this->countSynchronously = true; } /** * When receiving the pager and summary through AJAX, to calculate the limit and offset of Grid, * you need to get the maximum possible total count, otherwise the Grid pages will not switch * * @return int * @throws \yii\base\InvalidConfigException */ protected function prepareTotalCount(): int { return $this->countSynchronously ? parent::prepareTotalCount() : PHP_INT_MAX; } }
<?php /** * ActiveRecord for API * * @link https://github.com/hiqdev/yii2-hiart * @package yii2-hiart * @license BSD-3-Clause * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/) */ namespace hiqdev\hiart; class ActiveDataProvider extends \yii\data\ActiveDataProvider { /** * @var ActiveQuery the query that is used to fetch data models and [[totalCount]] * if it is not explicitly set */ public $query; /** * To improve performance, implemented grid summary and pager loading via AJAX when this attribute is `false` * There is a possibility set this attribute via DI * @see \hipanel\base\SearchModelTrait::search() * * @var bool */ public bool $countSynchronously = false; public function enableSynchronousCount(): void { $this->countSynchronously = true; } protected function prepareTotalCount() { return $this->countSynchronously ? parent::prepareTotalCount() : 999999; } }
Fix moves across monitors acting funny When moving a tab to a different monitor, the tab would not render using the new window size. This change fixes that bug by creating a new tab on the target window and removing the old one (chrome.tabs.create, chrome.tabs.remove) rather than moving the tab (chrome.tabs.move).
chrome.commands.onCommand.addListener(dispatch); function dispatch(command, tab) { if (command === "movetab") { moveTab(tab); } } function moveTab(tab) { chrome.storage.local.get('savedWindow', function(storage) { var savedToWindow = storage.savedWindow; if (savedToWindow == undefined) { alert("You haven't selected a target window yet!"); return; } chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT}, function(tabs) { if (tabs.length > 1) { alert('Too many tabs found!'); return; } try { chrome.tabs.create({ 'windowId': savedToWindow, 'url': tabs[0].url, }); chrome.windows.update(savedToWindow, {'focused': true}); chrome.tabs.remove(tabs[0].id); } catch (e) { alert(e); } }); }); }
chrome.commands.onCommand.addListener(dispatch); function dispatch(command, tab) { if (command === "movetab") { moveTab(tab); } } function moveTab(tab) { chrome.storage.local.get('savedWindow', function(storage) { var savedToWindow = storage.savedWindow; if (savedToWindow == undefined) { alert("You haven't selected a target window yet!"); return; } chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT}, function(tabs) { if (tabs.length > 1) { alert('Too many tabs found!'); return; } try { chrome.tabs.move(tabs[0].id, { 'windowId': savedToWindow, 'index': -1 }, function(tabs) { chrome.tabs.update(tabs.id, {'active': true}, function() { chrome.windows.update(savedToWindow, {'focused': true}, function() { console.log('Done!') }); }); }); } catch (e) { alert(e); } }); }); }
Exclude details field from editable through API
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author', 'details') def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author',) def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
Fix Object.fromEntries polyfill (for Safari 11)
/* Copyright 2018 Alfredo Mungo <alfredo.mungo@protonmail.ch> 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. */ if (!Object.fromEntries) { Object.defineProperty(Object, 'fromEntries', { value(entries) { if (!entries || !entries[Symbol.iterator]) { throw new Error('Object.fromEntries() requires a single iterable argument'); } return [...entries].reduce((obj, [key, val]) => { obj[key]= val return obj }, {}) }, }); }
/* Copyright 2018 Alfredo Mungo <alfredo.mungo@protonmail.ch> 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. */ if (!Object.fromEntries) { Object.defineProperty(Object, 'fromEntries', { value(entries) { if (!entries || !entries[Symbol.iterator]) { throw new Error('Object.fromEntries() requires a single iterable argument'); } const o = {}; Object.keys(entries).forEach((key) => { const [k, v] = entries[key]; o[k] = v; }); return o; }, }); }
Fix login page for first time visitor.
/* eslint-disable fp/no-mutation */ /* eslint-disable no-param-reassign */ import { CALL_API } from 'redux-api-middleware'; import { SERVER_URL } from './../constants/Api'; import localStorageUtils from './../utils/localStorageUtils'; const requestMiddleware = (_store) => (next) => (action) => { if (action[CALL_API]) { const headers = action[CALL_API].headers = action[CALL_API].headers || {}; const method = action[CALL_API].method; // TODO(rasendubi): authenticated user data should be taken from store const user = localStorageUtils.getAuthenticatedUser(); if (method === 'GET' || method === 'POST' || method === 'PUT' || method === 'DELETE') { headers['Content-Type'] = 'application/json'; action[CALL_API].endpoint = `${SERVER_URL}/${action[CALL_API].endpoint}`; if (user && user.get('access_token')) { headers.Authorization = headers.Authorization || `JWT ${user.get('access_token')}`; } return next(action); } } return next(action); }; export default requestMiddleware;
/* eslint-disable fp/no-mutation */ /* eslint-disable no-param-reassign */ import { CALL_API } from 'redux-api-middleware'; import { SERVER_URL } from './../constants/Api'; import localStorageUtils from './../utils/localStorageUtils'; const requestMiddleware = (_store) => (next) => (action) => { if (action[CALL_API]) { const headers = action[CALL_API].headers = action[CALL_API].headers || {}; const method = action[CALL_API].method; // TODO(rasendubi): authenticated user data should be taken from store const user = localStorageUtils.getAuthenticatedUser(); if (method === 'GET' || method === 'POST' || method === 'PUT' || method === 'DELETE') { headers['Content-Type'] = 'application/json'; action[CALL_API].endpoint = `${SERVER_URL}/${action[CALL_API].endpoint}`; if (user) { headers.Authorization = headers.Authorization || `JWT ${user.get('access_token')}`; } return next(action); } } return next(action); }; export default requestMiddleware;
Add language line for inheriting user permissions. Signed-off-by: Micheal Mand <4a52646cf58d42dd1882775751ea450b8cf7f96f@kmdwebdesigns.com>
<?php return [ 'button' => [ 'new-role' => 'New role', ], 'title' => [ 'roles' => 'Roles', 'edit' => 'Edit role', 'users-with-roles' => 'Users with this role', ], 'breadcrumb' => [ 'roles' => 'Roles', 'new' => 'New', 'edit' => 'Edit role', ], 'table' => [ 'name' => 'Name', ], 'tabs' => [ 'data' => 'Data', 'permissions' => 'Permissions', ], 'form' => [ 'name' => 'Role name', 'slug' => 'Role slug', ], 'navigation' => [ 'back to index' => 'Back to roles index' ], 'select all' => 'Select all', 'deselect all' => 'Deselect all', 'inherit' => 'Inherit from role', 'swap' => 'Swap', ];
<?php return [ 'button' => [ 'new-role' => 'New role', ], 'title' => [ 'roles' => 'Roles', 'edit' => 'Edit role', 'users-with-roles' => 'Users with this role', ], 'breadcrumb' => [ 'roles' => 'Roles', 'new' => 'New', 'edit' => 'Edit role', ], 'table' => [ 'name' => 'Name', ], 'tabs' => [ 'data' => 'Data', 'permissions' => 'Permissions', ], 'form' => [ 'name' => 'Role name', 'slug' => 'Role slug', ], 'navigation' => [ 'back to index' => 'Back to roles index' ], 'select all' => 'Select all', 'deselect all' => 'Deselect all', 'swap' => 'Swap', ];
Test to make sure link to create playbook exists
from django.core.urlresolvers import reverse from django.test import TestCase from ansible.models import Playbook class PlaybookListViewTest(TestCase): fixtures = ['initial_data.json'] def test_view_url_exists_at_desired_location(self): resp = self.client.get('/playbooks/') self.assertEqual(resp.status_code, 200) def test_view_playbook_list_url_accessible_by_name(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) def test_view_playbook_list_has_create_playbook_link(self): resp = self.client.get(reverse('ansible:playbook-create')) self.assertEqual(resp.status_code, 200) def test_view_playbook_detail_url_accessible_by_name(self): resp = self.client.get( reverse('ansible:playbook-detail', kwargs={'pk':1}) ) self.assertEqual(resp.status_code, 200) def test_view_uses_correct_template(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'ansible/playbook_list.html')
from django.core.urlresolvers import reverse from django.test import TestCase from ansible.models import Playbook class PlaybookListViewTest(TestCase): fixtures = ['initial_data.json'] def test_view_url_exists_at_desired_location(self): resp = self.client.get('/playbooks/') self.assertEqual(resp.status_code, 200) def test_view_playbook_list_url_accessible_by_name(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) def test_view_playbook_detail_url_accessible_by_name(self): resp = self.client.get( reverse('ansible:playbook-detail', kwargs={'pk':1}) ) self.assertEqual(resp.status_code, 200) def test_view_uses_correct_template(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'ansible/playbook_list.html')
Use the right line terminator accordingly to the platform
'use strict'; /* global require */ /* global process */ var fs = require ('fs'); var path = require ('path'); var mkdirSync = function (path) { try { fs.mkdirSync (path); } catch (e) { if (e.code !== 'EEXIST') { throw e; } } }; var cwd = process.cwd ().replace (/\\/g, '/'); var suffix = '/node_modules/mai-chai'; if (cwd.endsWith (suffix)) { var root = cwd.substr (0, cwd.length - suffix.length); var test = path.join (root, 'test'); var files = fs.readdirSync (path.join (cwd, 'templates')); mkdirSync (test); mkdirSync (path.join (root, 'src')); mkdirSync (path.join (root, 'src.test')); var regex = /\r\n/g; var newline = '\n'; if (process.platform === 'win32') { regex = /[^\r]\n/g; newline = '\r\n'; } files.forEach (function (file) { var data = fs.readFileSync (path.join (cwd, 'templates', file)); if (file.substr (0, 2) === '--') { var name = file.substr (2, file.length - 2); fs.writeFileSync (path.join (root, name), data.replace (regex, newline)); } else { fs.writeFileSync (path.join (test, file), data.replace (regex, newline)); } }); }
'use strict'; /* global require */ /* global process */ var fs = require ('fs'); var path = require ('path'); var mkdirSync = function (path) { try { fs.mkdirSync (path); } catch (e) { if (e.code !== 'EEXIST') { throw e; } } }; var cwd = process.cwd ().replace (/\\/g, '/'); var suffix = '/node_modules/mai-chai'; if (cwd.endsWith (suffix)) { var root = cwd.substr (0, cwd.length - suffix.length); var test = path.join (root, 'test'); var files = fs.readdirSync (path.join (cwd, 'templates')); mkdirSync (test); mkdirSync (path.join (root, 'src')); mkdirSync (path.join (root, 'src.test')); files.forEach (function (file) { var data = fs.readFileSync (path.join (cwd, 'templates', file)); if (file.substr (0, 2) === '--') { var name = file.substr (2, file.length - 2); fs.writeFileSync (path.join (root, name), data); } else { fs.writeFileSync (path.join (test, file), data); } }); }
Fix for loading SiteMap entry on Spring 2.x
/* * Created on 11-Jan-2006 */ package uk.org.ponder.rsf.test.sitemap; import java.util.HashMap; import uk.org.ponder.rsf.bare.junit.PlainRSFTests; import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters; import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser; public class TestSiteMap extends PlainRSFTests { public TestSiteMap() { contributeConfigLocation("classpath:uk/org/ponder/rsf/test/sitemap/sitemap-context.xml"); } public void testParseECVP() { BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser"); HashMap attrmap = new HashMap(); attrmap.put("flowtoken", "ec38f0"); EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap); System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname); } }
/* * Created on 11-Jan-2006 */ package uk.org.ponder.rsf.test.sitemap; import java.util.HashMap; import uk.org.ponder.rsf.bare.junit.PlainRSFTests; import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters; import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser; public class TestSiteMap extends PlainRSFTests { public void testParseECVP() { BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser"); HashMap attrmap = new HashMap(); attrmap.put("flowtoken", "ec38f0"); EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap); System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname); } }
TXTResults: Use CouchPotato to get results from db.
import fetch from 'isomorphic-fetch'; import { TXT_RV_REQ, TXT_RV_RECV, TXT_RV_SELECT_ONE, TXT_RV_INVALIDATE, TXT_SELECTED_TEST, TXT_CANCEL_SELECTED_TEST } from '../constants/action_types'; export function txtRvSelectOne(txtRv) { return { type: TXT_RV_SELECT_ONE, txtRv }; } export function txtRvInvalidate(branch) { return { type: TXT_RV_INVALIDATE, branch }; } export function txtRvReq(branch) { return { type: TXT_RV_REQ, branch }; } export function txtRvRecv(json) { return { type: TXT_RV_RECV, txtRv: json, receivedAt: Date.now() }; } export function fetchTxtRv() { return dispatch => { return fetch('/api/couchpotato/txt_results/design/txtbrowser/view/txtbrowser') .then(req => req.json()) .then(json => dispatch(txtRvRecv(json))); } } export function selectedTest(testName) { return { type: TXT_SELECTED_TEST, selected : testName }; } export function cancelSelectedTest(index) { return { type: TXT_CANCEL_SELECTED_TEST, index : index }; }
import fetch from 'isomorphic-fetch'; import { TXT_RV_REQ, TXT_RV_RECV, TXT_RV_SELECT_ONE, TXT_RV_INVALIDATE, TXT_SELECTED_TEST, TXT_CANCEL_SELECTED_TEST } from '../constants/action_types'; export function txtRvSelectOne(txtRv) { return { type: TXT_RV_SELECT_ONE, txtRv }; } export function txtRvInvalidate(branch) { return { type: TXT_RV_INVALIDATE, branch }; } export function txtRvReq(branch) { return { type: TXT_RV_REQ, branch }; } export function txtRvRecv(json) { return { type: TXT_RV_RECV, txtRv: json, receivedAt: Date.now() }; } export function fetchTxtRv() { return dispatch => { return fetch('/api/txt/results') .then(req => req.json()) .then(json => dispatch(txtRvRecv(json))); } } export function selectedTest(testName) { return { type: TXT_SELECTED_TEST, selected : testName }; } export function cancelSelectedTest(index) { return { type: TXT_CANCEL_SELECTED_TEST, index : index }; }
Fix file path for config.json
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'development'; const config = require(`${__dirname}/../config/config.json`)[env]; config[env]; const db = {}; let sequelize; if (config.use_env_variable) { sequelize = new Sequelize(process.env[config.use_env_variable]); } else { sequelize = new Sequelize( config.database, config.username, config.password, config ); } fs .readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'development'; const config = require(`${__dirname}/config/config.json`)[env]; config[env]; const db = {}; let sequelize; if (config.use_env_variable) { sequelize = new Sequelize(process.env[config.use_env_variable]); } else { sequelize = new Sequelize( config.database, config.username, config.password, config ); } fs .readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
NEW: Add support for appengine update oauth2 token in deploy script.
from fabric.api import * from fabric.contrib.console import confirm cfg = dict( appengine_dir='appengine-web/src', goldquest_dir='src', appengine_token='', ) def update(): # update to latest code from repo local('git pull') def test(): local("nosetests -m 'Test|test_' -w %(goldquest_dir)s" % cfg) # jslint # pychecker # run jasmine tests def compile(): # Minimize javascript using google closure. local("java -jar ~/bin/compiler.jar --js %(appengine_dir)s/javascript/game.js --js_output_file %(appengine_dir)s/javascript/game.min.js" % cfg) def deploy_appengine(): local("appcfg.py --oauth2_refresh_token=%(appengine_token)s update %(appengine_dir)s" % cfg) def prepare_deploy(): test() compile() def deploy(): update() prepare_deploy() deploy_appengine() # tweet about release
from fabric.api import * from fabric.contrib.console import confirm appengine_dir='appengine-web/src' goldquest_dir='src' def update(): # update to latest code from repo local('git pull') def test(): local("nosetests -m 'Test|test_' -w %(path)s" % dict(path=goldquest_dir)) # jslint # pychecker # run jasmine tests def compile(): # Minimize javascript using google closure. local("java -jar ~/bin/compiler.jar --js %(path)s/javascript/game.js --js_output_file %(path)s/javascript/game.min.js" % dict(path=appengine_dir)) def deploy_appengine(): local("appcfg.py update " + appengine_dir) def prepare_deploy(): test() compile() def deploy(): update() prepare_deploy() deploy_appengine() # tweet about release
Increase timeout for request test
import should from 'should' import getJson from './getJson' let endpoint = '/stats/homepagev2' let query = { GameScope: 'Season', LeagueID: '00', PlayerOrTeam: 'Player', PlayerScope: 'All Players', Season: '2015-16', SeasonType: 'Regular Season', StatType: 'Traditional' } describe('utils/getJson', () => { it('returns response/error as a Promise', (done) => { let request = getJson(endpoint, { query }) request.should.be.Promise() done() }) it('resolves to JSON response', (done) => { getJson(endpoint, { query }).then((res) => { should.exist(res) res.should.have.property('body') done() }).catch((e) => { console.log(e) }) }).timeout(10000) it('throws 400 on invalid request', (done) => { getJson(endpoint, { query: {} }).catch((err) => { should.exist(err) err.statusCode.should.equal(400) done() }) }) })
import should from 'should' import getJson from './getJson' let endpoint = '/stats/homepagev2' let query = { GameScope: 'Season', LeagueID: '00', PlayerOrTeam: 'Player', PlayerScope: 'All Players', Season: '2015-16', SeasonType: 'Regular Season', StatType: 'Traditional' } describe('utils/getJson', () => { it('returns response/error as a Promise', (done) => { let request = getJson(endpoint, { query }) request.should.be.Promise() done() }) it('resolves to JSON response', (done) => { getJson(endpoint, { query }).then((res) => { should.exist(res) res.should.have.property('body') done() }) }) it('throws 400 on invalid request', (done) => { getJson(endpoint, { query: {} }).catch((err) => { should.exist(err) err.statusCode.should.equal(400) done() }) }) })
Allow Flask to get port from heroku environment
#!/usr/bin/env python """ Bootstrap and serve your application. This file also serves to not make your application completely reliant upon DotCloud's hosting service. If you're in a development environment, envoke the script with: $ python bootstrap.py In a production environment, your application can be run with the `gevent` Python library: $ python bootstrap.py --gevent """ import os import argparse from app import create_app def parse_arguments(): """Parse any additional arguments that may be passed to `bootstrap.py`.""" parser = argparse.ArgumentParser() parser.add_argument('--gevent', action='store_true', help="Run gevent's production server.") args = parser.parse_args() return args.gevent def serve_app(gevent_environment): """ Serve your application. If `dev_environment` is true, then the application will be served using gevent's WSGIServer. """ app = create_app() if gevent_environment: from gevent.wsgi import WSGIServer # Get the port if on heroku's environment. port = int(os.environ.get('PORT', 5000)) http_server = WSGIServer(('', port), app) http_server.serve_forever() else: app.run(debug=True) def main(): dev_environment = parse_arguments() serve_app(dev_environment) if __name__ == '__main__': main()
#!/usr/bin/env python """ Bootstrap and serve your application. This file also serves to not make your application completely reliant upon DotCloud's hosting service. If you're in a development environment, envoke the script with: $ python bootstrap.py In a production environment, your application can be run with the `gevent` Python library: $ python bootstrap.py --gevent """ import argparse from app import create_app def parse_arguments(): """Parse any additional arguments that may be passed to `bootstrap.py`.""" parser = argparse.ArgumentParser() parser.add_argument('--gevent', action='store_true', help="Run gevent's production server.") args = parser.parse_args() return args.gevent def serve_app(gevent_environment): """ Serve your application. If `dev_environment` is true, then the application will be served using gevent's WSGIServer. """ app = create_app() if gevent_environment: from gevent.wsgi import WSGIServer # The port should probably be set to 80. http_server = WSGIServer(('', 5000), app) http_server.serve_forever() else: app.run(debug=True) def main(): dev_environment = parse_arguments() serve_app(dev_environment) if __name__ == '__main__': main()
Undo "Make login the default view" (97c89395eb34093f103cc8816c1d2420e6c8e44d) Signed-off-by: Tillmann Karras <28ed73209cf4ae5252aebcefd0036a7597a64897@gmail.com>
<?php require_once('config.inc.php'); require_once('misc.inc.php'); require_once('db.inc.php'); require_once('html.inc.php'); date_default_timezone_set('Europe/Berlin'); setlocale(LC_TIME, 'de_DE'); session_start(); // Actual content generation: $db = new db(); switch ($_GET['view']) { case 'print': authenticate(VIEW_PRINT, 'index.php?view=print'); if (isset($_GET['date'])) { $source = new ovp_print($db, $_GET['date']); } else { $source = new ovp_print($db); } break; case 'author': authenticate(VIEW_AUTHOR, 'index.php?view=author'); $source = new ovp_author($db); break; case 'admin': authenticate(VIEW_ADMIN, 'index.php?view=admin'); $source = new ovp_admin($db); break; case 'login': $source = new ovp_login($db); break; case 'public': default: authenticate(VIEW_PUBLIC, 'index.php?view=public'); $source = new ovp_public($db); } $page = new ovp_page($source); exit($page->get_html()); ?>
<?php require_once('config.inc.php'); require_once('misc.inc.php'); require_once('db.inc.php'); require_once('html.inc.php'); date_default_timezone_set('Europe/Berlin'); setlocale(LC_TIME, 'de_DE'); session_start(); // Actual content generation: $db = new db(); switch ($_GET['view']) { case 'public': authenticate(VIEW_PUBLIC, 'index.php?view=public'); $source = new ovp_public($db); break; case 'print': authenticate(VIEW_PRINT, 'index.php?view=print'); if (isset($_GET['date'])) { $source = new ovp_print($db, $_GET['date']); } else { $source = new ovp_print($db); } break; case 'author': authenticate(VIEW_AUTHOR, 'index.php?view=author'); $source = new ovp_author($db); break; case 'admin': authenticate(VIEW_ADMIN, 'index.php?view=admin'); $source = new ovp_admin($db); break; case 'login': default: $source = new ovp_login($db); } $page = new ovp_page($source); exit($page->get_html()); ?>
Remove comment with debugging stuff
package com.codeski.nbt.tags; import java.nio.ByteBuffer; import java.nio.charset.Charset; public class NBTLong extends NBT { public static final byte LENGTH = 8; public static final byte TYPE = 4; private Long payload; public NBTLong(String name, long payload) { super(name); this.payload = payload; } @Override public int getLength() { int length = LENGTH; if (this.getName() != null) length += 3 + (short) this.getName().getBytes(Charset.forName("UTF-8")).length; return length; } @Override public Long getPayload() { return payload; } @Override public byte getType() { return TYPE; } public void setPayload(long payload) { this.payload = payload; } @Override public String toString() { if (name != null) return "[Long] " + name + ": " + payload; else return "[Long] null: " + payload; } @Override public void writePayload(ByteBuffer bytes) { bytes.putLong(this.getPayload()); } }
package com.codeski.nbt.tags; import java.nio.ByteBuffer; import java.nio.charset.Charset; public class NBTLong extends NBT { public static final byte LENGTH = 8; public static final byte TYPE = 4; private Long payload; public NBTLong(String name, long payload) { super(name); this.payload = payload; } @Override public int getLength() { int length = LENGTH; if (this.getName() != null) length += 3 + (short) this.getName().getBytes(Charset.forName("UTF-8")).length; // System.out.println(length + " of which " + LENGTH + " is payload."); return length; } @Override public Long getPayload() { return payload; } @Override public byte getType() { return TYPE; } public void setPayload(long payload) { this.payload = payload; } @Override public String toString() { if (name != null) return "[Long] " + name + ": " + payload; else return "[Long] null: " + payload; } @Override public void writePayload(ByteBuffer bytes) { bytes.putLong(this.getPayload()); } }
Update problem0004 to use streams
import java.util.stream.LongStream; /** * A palindromic number reads the same both ways. * The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. * <p> * Find the largest palindrome made from the product of two 3-digit numbers. * * @author David Clutter */ public class Problem0004 { public static void main(final String[] args) { final long largestPalindrome = LongStream.range(100, 1_000) .flatMap(i -> LongStream.range(100, 1_000) .map(j -> i * j)) .filter(Utilities::isPalindrome) .max() .getAsLong(); System.out.println(largestPalindrome); } }
/** * A palindromic number reads the same both ways. * The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. * * Find the largest palindrome made from the product of two 3-digit numbers. * * @author David Clutter */ public class Problem0004 { public static void main(final String[] args) { long largestPalindrome = 0; for(int i = 100; i < 1000; ++i) { for(int j = 100; j < 1000; ++j) { final long product = i * j; if(Utilities.isPalindrome(product) && product > largestPalindrome) { largestPalindrome = product; } } } System.out.println(largestPalindrome); } }
Change actual return type of SQL editor provider
package com.codenvy.ide.ext.datasource.client.sqleditor; import com.codenvy.ide.api.editor.CodenvyTextEditor; import com.codenvy.ide.api.editor.DocumentProvider; import com.codenvy.ide.api.editor.EditorProvider; import com.codenvy.ide.api.editor.TextEditorPartPresenter; import com.codenvy.ide.api.notification.NotificationManager; import com.codenvy.ide.util.loging.Log; import com.google.inject.Inject; import com.google.inject.Provider; public class SqlEditorProvider implements EditorProvider { private final DocumentProvider documentProvider; private final Provider<CodenvyTextEditor> editorProvider; private final NotificationManager notificationManager; @Inject public SqlEditorProvider(final DocumentProvider documentProvider, final Provider<CodenvyTextEditor> editorProvider, final NotificationManager notificationManager) { this.documentProvider = documentProvider; this.editorProvider = editorProvider; this.notificationManager = notificationManager; } @Override public TextEditorPartPresenter getEditor() { Log.info(SqlEditorProvider.class, "New instance of SQL editor requested."); CodenvyTextEditor textEditor = editorProvider.get(); textEditor.initialize(new SqlEditorConfiguration(), documentProvider, notificationManager); return textEditor; } }
package com.codenvy.ide.ext.datasource.client.sqleditor; import com.codenvy.ide.api.editor.CodenvyTextEditor; import com.codenvy.ide.api.editor.DocumentProvider; import com.codenvy.ide.api.editor.EditorPartPresenter; import com.codenvy.ide.api.editor.EditorProvider; import com.codenvy.ide.api.notification.NotificationManager; import com.google.inject.Inject; import com.google.inject.Provider; public class SqlEditorProvider implements EditorProvider { private final DocumentProvider documentProvider; private final Provider<CodenvyTextEditor> editorProvider; private final NotificationManager notificationManager; @Inject public SqlEditorProvider(final DocumentProvider documentProvider, final Provider<CodenvyTextEditor> editorProvider, final NotificationManager notificationManager) { this.documentProvider = documentProvider; this.editorProvider = editorProvider; this.notificationManager = notificationManager; } @Override public EditorPartPresenter getEditor() { CodenvyTextEditor textEditor = editorProvider.get(); textEditor.initialize(new SqlEditorConfiguration(), documentProvider, notificationManager); return textEditor; } }
Validate that user flag is given
'use strict'; const minimist = require('minimist'); const latestvid = require('./'); const version = require('./package.json').version; const defaults = { boolean: [ 'help', 'version', 'download' ], alias: { h: 'help', v: 'version', u: 'user', d: 'download' }, default: { help: false, version: false, download: false, user: '' } }; const help = ` Usage: latestvid [OPTIONS] Open/download the most recent video from any YouTube account. Options: -h --help Display this help dialog -v --version Display current version -d --download Download latest video instead of opening -u --user YouTube username Example: $ latestvid -u marquesbrownlee # open latest MKBHD video $ latestvid -u marquesbrownlee -d # download latest MKBHD video `; exports.stdout = process.stdout; exports.stderr = process.stderr; exports.exit = process.exit; exports.parse = argv => minimist(argv, defaults); exports.validate = opts => { return new Promise((resolve, reject) => { if (!opts.help && !opts.version && (opts.user === '' || typeof (opts.user) === 'boolean')) { reject(new Error(`Expected user account, run 'latestvid -h' for help.`)); } resolve(opts); }); };
'use strict'; const minimist = require('minimist'); const latestvid = require('./'); const version = require('./package.json').version; const defaults = { boolean: [ 'help', 'version', 'download' ], alias: { h: 'help', v: 'version', u: 'user', d: 'download' }, default: { help: false, version: false, download: false, user: '' } }; const help = ` Usage: latestvid [OPTIONS] Open/download the most recent video from any YouTube account. Options: -h --help Display this help dialog -v --version Display current version -d --download Download latest video instead of opening -u --user YouTube username Example: $ latestvid -u marquesbrownlee # open latest MKBHD video $ latestvid -u marquesbrownlee -d # download latest MKBHD video `; exports.stdout = process.stdout; exports.stderr = process.stderr; exports.exit = process.exit; exports.parse = argv => minimist(argv, defaults);
Fix assets test for debug version generated files
package assets import ( "os" "testing" "time" . "github.com/smartystreets/goconvey/convey" ) type testBindataFileInfo struct { name string size int64 mode os.FileMode modTime time.Time } func (fi testBindataFileInfo) Name() string { return fi.name } func (fi testBindataFileInfo) Size() int64 { return fi.size } func (fi testBindataFileInfo) Mode() os.FileMode { return fi.mode } func (fi testBindataFileInfo) ModTime() time.Time { return fi.modTime } func (fi testBindataFileInfo) IsDir() bool { return false } func (fi testBindataFileInfo) Sys() interface{} { return nil } func TestMain(t *testing.T) { Convey("ETags generated on startup", t, func() { So(etags, ShouldHaveLength, len(_bindata)) tag, err := GetAssetETag("path/doesnt/exist") So(tag, ShouldBeEmpty) So(err, ShouldEqual, ErrETagNotFound) _bindata["path/does/exist"] = func() (*asset, error) { return &asset{ bytes: []byte("test"), info: testBindataFileInfo{"test", 4, 0600, time.Now()}, }, nil } updateETags() tag, err = GetAssetETag("path/does/exist") So(tag, ShouldEqual, `W/"4-D87F7E0C"`) So(err, ShouldBeNil) }) }
package assets import ( "testing" "time" . "github.com/smartystreets/goconvey/convey" ) func TestMain(t *testing.T) { Convey("ETags generated on startup", t, func() { So(etags, ShouldHaveLength, len(_bindata)) tag, err := GetAssetETag("path/doesnt/exist") So(tag, ShouldBeEmpty) So(err, ShouldEqual, ErrETagNotFound) _bindata["path/does/exist"] = func() (*asset, error) { return &asset{ bytes: []byte("test"), info: bindataFileInfo{"test", 4, 0600, time.Now()}, }, nil } updateETags() tag, err = GetAssetETag("path/does/exist") So(tag, ShouldEqual, `W/"4-D87F7E0C"`) So(err, ShouldBeNil) }) }
Write to temp directories in such a way that files get cleaned up
import io import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), )) def test_pretty_format_json(filename, expected_retval): ret = pretty_format_json([get_resource_path(filename)]) assert ret == expected_retval def test_autofix_pretty_format_json(tmpdir): srcfile = tmpdir.join('to_be_json_formatted.json') with io.open(get_resource_path('not_pretty_formatted_json.json')) as f: srcfile.write_text(f.read(), 'UTF-8') # now launch the autofix on that file ret = pretty_format_json(['--autofix', srcfile.strpath]) # it should have formatted it assert ret == 1 # file was formatted (shouldn't trigger linter again) ret = pretty_format_json([srcfile.strpath]) assert ret == 0 def test_badfile_pretty_format_json(): ret = pretty_format_json([get_resource_path('ok_yaml.yaml')]) assert ret == 1
import tempfile import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), )) def test_pretty_format_json(filename, expected_retval): ret = pretty_format_json([get_resource_path(filename)]) assert ret == expected_retval def test_autofix_pretty_format_json(): toformat_file = tempfile.NamedTemporaryFile(delete=False, mode='w+') # copy our file to format there model_file = open(get_resource_path('not_pretty_formatted_json.json'), 'r') model_contents = model_file.read() model_file.close() toformat_file.write(model_contents) toformat_file.close() # now launch the autofix on that file ret = pretty_format_json(['--autofix', toformat_file.name]) # it should have formatted it assert ret == 1 # file already good ret = pretty_format_json([toformat_file.name]) assert ret == 0 def test_badfile_pretty_format_json(): ret = pretty_format_json([get_resource_path('ok_yaml.yaml')]) assert ret == 1
Set up our SimulatorManager on init(). git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@940 542714f4-19e9-0310-aa3c-eee0fc999fb1
// // $Id: SimpleServer.java,v 1.2 2002/02/05 22:57:10 mdb Exp $ package com.threerings.micasa.simulator.server; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.server.CrowdServer; /** * A simple simulator server implementation that extends the crowd server * and provides no special functionality. */ public class SimpleServer extends CrowdServer implements SimulatorServer { // documentation inherited public void init () throws Exception { super.init(); // create the simulator manager SimulatorManager simmgr = new SimulatorManager(); simmgr.init(config, invmgr, plreg, clmgr, omgr, this); } // documentation inherited public void fakeBodyMapping (String username, BodyObject bodobj) { _bodymap.put(username, bodobj); } }
// // $Id: SimpleServer.java,v 1.1 2002/02/05 22:12:42 mdb Exp $ package com.threerings.micasa.simulator.server; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.server.CrowdServer; /** * A simple simulator server implementation that extends the crowd server * and provides no special functionality. */ public class SimpleServer extends CrowdServer implements SimulatorServer { /** * Called by the simulator manager to map a username to a particular * body object. This should only be called from the dobjmgr thread. * * <p> This is copied from {@link CrowdServer#mapBody} as that * implementation is protected and cannot be referenced by classes in * the simulator package, but we know what we're doing and so we * knowingly expose this functionality to other classes in our * package. */ public void fakeBodyMapping (String username, BodyObject bodobj) { _bodymap.put(username, bodobj); } }
Update the URI for linking the events on google maps to the new URI scheme from google maps.
@if (!$event->isIREX()) <tr class="informational-meeting"> @elseif ($event->isCanceled()) <tr class="canceled-meeting"> @else <tr> @endif <td>{{ $event->getDate() }}</td> @if (trim($event->url) != "") <td><a href="{{{ $event->url }}}" target="_blank">{{ $event->title }}</a></td> @else <td>{{ $event->title }}</td> @endif @if (trim($event->location) == "Knights of Columbus") <td><a href="#knights-of-columbus">{{ $event->location }}</a></td> @elseif (trim($event->address) != "") <td><a href="https://www.google.com/maps/preview/place/{{{ $event->address }}}" target="_blank">{{ $event->location }}</a></td> @else <td>{{ $event->location }}</td> @endif </tr>
@if (!$event->isIREX()) <tr class="informational-meeting"> @elseif ($event->isCanceled()) <tr class="canceled-meeting"> @else <tr> @endif <td>{{ $event->getDate() }}</td> @if (trim($event->url) != "") <td><a href="{{{ $event->url }}}" target="_blank">{{ $event->title }}</a></td> @else <td>{{ $event->title }}</td> @endif @if (trim($event->location) == "Knights of Columbus") <td><a href="#knights-of-columbus">{{ $event->location }}</a></td> @elseif (trim($event->address) != "") <td><a href="https://maps.google.com/maps?q={{{ $event->address }}}&z=12" target="_blank">{{ $event->location }}</a></td> @else <td>{{ $event->location }}</td> @endif </tr>
Fix newlines in converted html
const Promise = require('bluebird') const readFile = Promise.promisify(require('fs').readFile) const showdown = require('showdown') class MarkdownRenderer { constructor (callback) { this.callback = callback this.converter = new showdown.Converter() } loadFile (fileName) { return readFile(fileName, 'utf8').then((markdown) => { return this.load(markdown) }) } load (markdown) { return this.convert(markdown).then((html) => { return this.callback(html) }).catch((error) => { throw error }) } convert (markdown) { return Promise.promisify((markdown, callback) => { var html = this.converter.makeHtml(markdown) html = '<div class="markdown-body">' + html + '</div>' html = 'data:text/html;charset=UTF-8,' + encodeURIComponent(html) callback(null, html) })(markdown) } } exports.MarkdownRenderer = MarkdownRenderer
const Promise = require('bluebird') const readFile = Promise.promisify(require('fs').readFile) const showdown = require('showdown') class MarkdownRenderer { constructor (callback) { this.callback = callback this.converter = new showdown.Converter() } loadFile (fileName) { return readFile(fileName, 'utf8').then((markdown) => { return this.load(markdown) }) } load (markdown) { return this.convert(markdown).then((html) => { return this.callback(html) }).catch((error) => { throw error }) } convert (markdown) { return Promise.promisify((markdown, callback) => { var html = this.converter.makeHtml(markdown) html = '<div class="markdown-body">' + html + '</div>' html = 'data:text/html;charset=UTF-8,' + html callback(null, html) })(markdown) } } exports.MarkdownRenderer = MarkdownRenderer
Fix issues in artisan command.
<?php namespace ConceptByte\TimeTraveller\Console; use DateTime; use Illuminate\Console\Command; use ConceptByte\TimeTraveller\Models\Revision; class ClearRevisionsCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'timetraveller:clear'; /** * The console command description. * * @var string */ protected $description = 'Clears the time traveller revisions'; /** * Execute the console command. * * @return mixed */ public function handle() { $date = new DateTime; $interval = config('timetraveller.clear'); if ($this->confirm('Do you wish to continue clearing revisions?')) { $date->modify("-$interval days")->format('Y-m-d H:i:s'); return Revision::where('created_at', '<=', $date)->delete(); } $this->info('Old revision cleared'); } }
<?php namespace ConceptByte\TimeTraveller\Console; use DateTime; use Illuminate\Console\Command; class ClearRevisionsCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'timetraveller:clear'; /** * The console command description. * * @var string */ protected $description = 'Clears the time traveller revisions'; /** * Execute the console command. * * @return mixed */ public function handle() { $date = new DateTime; $interval = config('timetraveller.clear'); if ($this->confirm('Do you wish to continue? [y|N]')) { $date->modify("-$interval days")->format('Y-m-d H:i:s'); return Revision::where('created_at', '<=', $date)->delete(); } } }
Fix to generate identical output to PySensors
package main import ( "fmt" "github.com/md14454/gosensors" ) func main() { gosensors.Init() defer gosensors.Cleanup() chips := gosensors.GetDetectedChips() for i := 0; i < len(chips); i++ { chip := chips[i] fmt.Printf("%v\n", chip) fmt.Printf("Adapter: %v\n", chip.AdapterName()) features := chip.GetFeatures() for j := 0; j < len(features); j++ { feature := features[j] fmt.Printf("%v ('%v'): %.1f\n", feature.Name, feature.GetLabel(), feature.GetValue()) subfeatures := feature.GetSubFeatures() for k := 0; k < len(subfeatures); k++ { subfeature := subfeatures[k] fmt.Printf(" %v: %.1f\n", subfeature.Name, subfeature.GetValue()) } } fmt.Printf("\n") } }
package main import ( "fmt" "github.com/md14454/gosensors" ) func main() { gosensors.Init() defer gosensors.Cleanup() chips := gosensors.GetDetectedChips() for i := 0; i < len(chips); i++ { chip := chips[i] fmt.Printf("%v\n", chip) fmt.Printf("Adapter: %v\n", chip.AdapterName()) features := chip.GetFeatures() for j := 0; j < len(features); j++ { feature := features[j] fmt.Printf("%v (%v): %.1f\n", feature.Name, feature.GetLabel(), feature.GetValue()) subfeatures := feature.GetSubFeatures() for k := 0; k < len(subfeatures); k++ { subfeature := subfeatures[k] fmt.Printf(" %v: %.1f\n", subfeature.Name, subfeature.GetValue()) } } fmt.Printf("\n") } }
Fix crash on feed search.
package com.newsblur.network; import java.util.ArrayList; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; import com.newsblur.domain.FeedResult; public class SearchAsyncTaskLoader extends AsyncTaskLoader<SearchLoaderResponse> { public static final String SEARCH_TERM = "searchTerm"; private String searchTerm; private APIManager apiManager; public SearchAsyncTaskLoader(Context context, String searchTerm) { super(context); this.searchTerm = searchTerm; apiManager = new APIManager(context); } @Override public SearchLoaderResponse loadInBackground() { SearchLoaderResponse response; try { ArrayList<FeedResult> list = new ArrayList<FeedResult>(); FeedResult[] results = apiManager.searchForFeed(searchTerm); if (results != null) { for (FeedResult result : results) { list.add(result); } } response = new SearchLoaderResponse(list); } catch (ServerErrorException ex) { response = new SearchLoaderResponse(ex.getMessage()); } return response; } }
package com.newsblur.network; import java.util.ArrayList; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; import com.newsblur.domain.FeedResult; public class SearchAsyncTaskLoader extends AsyncTaskLoader<SearchLoaderResponse> { public static final String SEARCH_TERM = "searchTerm"; private String searchTerm; private APIManager apiManager; public SearchAsyncTaskLoader(Context context, String searchTerm) { super(context); this.searchTerm = searchTerm; apiManager = new APIManager(context); } @Override public SearchLoaderResponse loadInBackground() { SearchLoaderResponse response; try { ArrayList<FeedResult> list = new ArrayList<FeedResult>(); for (FeedResult result : apiManager.searchForFeed(searchTerm)) { list.add(result); } response = new SearchLoaderResponse(list); } catch (ServerErrorException ex) { response = new SearchLoaderResponse(ex.getMessage()); } return response; } }
Support older JavaScript engine shells.
// Copyright 2018 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. const fs = require("fs"); const path = require("path"); const webpack = require("webpack"); module.exports = fs .readdirSync("src") .filter(filename => filename.endsWith(".js")) .map(filename => ({ context: path.resolve("src"), entry: `./${filename}`, output: { filename, path: path.resolve("dist") }, optimization: { minimize: false }, plugins: [ new webpack.BannerPlugin({ banner: "// Required for JavaScript engine shells.\n" + "if (typeof console === 'undefined') {\n" + " console = {log: print};\n" + "}", raw: true }) ] }));
// Copyright 2018 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. const fs = require("fs"); const path = require("path"); module.exports = fs .readdirSync("src") .filter(filename => filename.endsWith(".js")) .map(filename => ({ context: path.resolve("src"), entry: `./${filename}`, output: { filename, path: path.resolve("dist") }, optimization: { minimize: false } }));
Include requests module in requirements for use by the gh_issuereport script
#!/usr/bin/env python from setuptools import setup URL_BASE = 'https://github.com/astropy/astropy-tools/' setup( name='astropy-tools', version='0.0.0.dev0', author='The Astropy Developers', author_email='astropy.team@gmail.com', url=URL_BASE, download_url=URL_BASE + 'archive/master.zip', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Utilities' ], py_modules=[ 'gitastropyplots', 'gh_issuereport', 'issue2pr', 'suggest_backports' ], entry_points={ 'console_scripts': [ 'gh_issuereport = gh_issuereport:main', 'issue2pr = issue2pr:main', 'suggest_backports = suggest_backports:main' ] }, install_requires=['requests'] )
#!/usr/bin/env python from setuptools import setup URL_BASE = 'https://github.com/astropy/astropy-tools/' setup( name='astropy-tools', version='0.0.0.dev0', author='The Astropy Developers', author_email='astropy.team@gmail.com', url=URL_BASE, download_url=URL_BASE + 'archive/master.zip', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Utilities' ], py_modules=[ 'gitastropyplots', 'gh_issuereport', 'issue2pr', 'suggest_backports' ], entry_points={ 'console_scripts': [ 'gh_issuereport = gh_issuereport:main', 'issue2pr = issue2pr:main', 'suggest_backports = suggest_backports:main' ] } )
Set value when it exists, or just leave it blank
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'input', setupBootstrapDatepicker: function() { var self = this, element = this.$(); element. datepicker({ autoclose: this.get('autoclose') || true, format: this.get('format') || 'dd.mm.yyyy', weekStart: this.get('weekStart') || 1, todayHighlight: this.get('todayHighlight') || false, todayBtn: this.get('todayBtn') || false }). on('changeDate', function(event) { Ember.run(function() { self.didSelectDate(event); }); }); if (value) { element.datepicker('setDate', new Date(this.get('value'))); }; }.on('didInsertElement'), teardownBootstrapDatepicker: function() { // no-op }.on('willDestroyElement'), didSelectDate: function(event) { var date = this.$().datepicker('getUTCDate'); this.set('value', date.toISOString()); } });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'input', setupBootstrapDatepicker: function() { var self = this; this.$(). datepicker({ autoclose: this.get('autoclose') || true, format: this.get('format') || 'dd.mm.yyyy', weekStart: this.get('weekStart') || 1, todayHighlight: this.get('todayHighlight') || false, todayBtn: this.get('todayBtn') || false }). datepicker('setDate', new Date(this.get('value'))). on('changeDate', function(event) { Ember.run(function() { self.didSelectDate(event); }); }); }.on('didInsertElement'), teardownBootstrapDatepicker: function() { // no-op }.on('willDestroyElement'), didSelectDate: function(event) { var date = this.$().datepicker('getUTCDate'); this.set('value', date.toISOString()); } });
Add information about invalid filesystem
<?php declare(strict_types=1); namespace League\Flysystem; use LogicException; class UnableToMountFilesystem extends LogicException implements FilesystemException { /** * @param mixed $key */ public static function becauseTheKeyIsNotValid($key): UnableToMountFilesystem { return new UnableToMountFilesystem( 'Unable to mount filesystem, key was invalid. String expected, received: ' . gettype($key) ); } /** * @param mixed $filesystem */ public static function becauseTheFilesystemWasNotValid($filesystem): UnableToMountFilesystem { $received = is_object($filesystem) ? get_class($filesystem) : gettype($filesystem); return new UnableToMountFilesystem( 'Unable to mount filesystem, filesystem was invalid. Instance of ' . FilesystemOperator::class . ' expected, received: ' . $received ); } }
<?php declare(strict_types=1); namespace League\Flysystem; use LogicException; class UnableToMountFilesystem extends LogicException implements FilesystemException { /** * @param mixed $key */ public static function becauseTheKeyIsNotValid($key): UnableToMountFilesystem { return new UnableToMountFilesystem( 'Unable to mount filesystem, key was invalid. String expected, received: ' . gettype($key) ); } /** * @param mixed $filesystem */ public static function becauseTheFilesystemWasNotValid($filesystem): UnableToMountFilesystem { return new UnableToMountFilesystem( 'Unable to mount filesystem, key was invalid. Instance of ' . FilesystemOperator::class . ' expected, received: ' . gettype( $filesystem ) ); } }
Add ability to use wrap and mapping
import { RepeatWrapping, UVMapping, NearestFilter, LinearMipMapLinearFilter, TextureLoader, Vector2 } from 'three'; const loader = new TextureLoader(); export class TextureModule { static load(url) { return new TextureModule({url}).texture; } textures = []; constructor(...textures) { textures.forEach(({ url, type = 'map', offset = new Vector2(0, 0), repeat = new Vector2(1, 1), wrap = RepeatWrapping, mapping = UVMapping }) => { const texture = loader.load(url); if (wrap.length > 0) { texture.wrapS = wrap[0]; texture.wrapT = wrap[1]; } else texture.wrapS = texture.wrapT = wrap; texture.mapping = mapping; texture.offset.copy(offset); texture.repeat.copy(repeat); texture.magFilter = NearestFilter; texture.minFilter = LinearMipMapLinearFilter; this.textures.push([type, texture]); }); } bridge = { material(material, self) { self.textures.forEach(texture => { material[texture[0]] = texture[1]; }); return material; } } }
import { RepeatWrapping, NearestFilter, LinearMipMapLinearFilter, TextureLoader, Vector2 } from 'three'; const loader = new TextureLoader(); export class TextureModule { static load(url) { return new TextureModule({url}).texture; } textures = []; constructor(...textures) { textures.forEach(({url, type = 'map', offset = new Vector2(0, 0), repeat = new Vector2(1, 1)}) => { const texture = loader.load(url); texture.wrapS = texture.wrapT = RepeatWrapping; texture.offset.copy(offset); texture.repeat.copy(repeat); texture.magFilter = NearestFilter; texture.minFilter = LinearMipMapLinearFilter; this.textures.push([type, texture]); }); } bridge = { material(material, self) { self.textures.forEach(texture => { material[texture[0]] = texture[1]; }); return material; } } }
Make Array's commonLeft function length equal 1
// Returns index at which lists start to differ (looking from left) 'use strict'; var every = Array.prototype.every , call = Function.prototype.call , assertNotNull = require('../../assert-not-null') , toArray = require('../../Object/prototype/to-array') , sortMethod = call.bind(require('../../Object/get-compare-by')('length')); module.exports = function (list) { var lists, r, l; assertNotNull(this); lists = [this].concat(toArray.call(arguments)).sort(sortMethod); l = r = lists[0].length >>> 0; every.call(lists.slice(1), function (list) { var i; for (i = 0; i < l; ++i) { if (i > r) { break; } else if (this[i] === list[i]) { continue; } else { r = i; break; } } return r; }, lists[0]); return r; };
// Returns index at which lists start to differ (looking from left) 'use strict'; var every = Array.prototype.every , call = Function.prototype.call , assertNotNull = require('../../assert-not-null') , toArray = require('../../Object/prototype/to-array') , sortMethod = call.bind(require('../../Object/get-compare-by')('length')); module.exports = function () { var lists, r, l; assertNotNull(this); lists = [this].concat(toArray.call(arguments)).sort(sortMethod); l = r = lists[0].length >>> 0; every.call(lists.slice(1), function (list) { var i; for (i = 0; i < l; ++i) { if (i > r) { break; } else if (this[i] === list[i]) { continue; } else { r = i; break; } } return r; }, lists[0]); return r; };
Fix string using py3 only feature.
""" These functions are written assuming the under a moto call stack. TODO add check is a fake bucket? """ import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name} s3.put_object(Key="{}/readme.txt".format(prefix), **default_kwargs) s3.put_object(Key="{}/notes.md".format(prefix), **default_kwargs) # load items, 3 directories for i, _ in enumerate(range(500)): res = s3.put_object(Key="{}/images/myimage{i}.tif".format(prefix), **default_kwargs) for i, _ in enumerate(range(400)): s3.put_object(Key="{}/scripts/myscripts{i}.py".format(prefix), **default_kwargs) for i, _ in enumerate(range(110)): s3.put_object( Key="{}/scripts/subdir/otherscripts{i}.sh".format(prefix), **default_kwargs)
""" These functions are written assuming the under a moto call stack. TODO add check is a fake bucket? """ import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name} s3.put_object(Key=f"{prefix}/readme.txt", **default_kwargs) s3.put_object(Key=f"{prefix}/notes.md", **default_kwargs) # load items, 3 directories for i, _ in enumerate(range(500)): res = s3.put_object(Key=f"{prefix}/images/myimage{i}.tif", **default_kwargs) for i, _ in enumerate(range(400)): s3.put_object( Key=f"{prefix}/scripts/myscripts{i}.py", **default_kwargs ) for i, _ in enumerate(range(110)): s3.put_object( Key=f"{prefix}/scripts/subdir/otherscripts{i}.sh", **default_kwargs )
Fix karma config. Watch files when not CI environment.
const buble = require('rollup-plugin-buble'); const nodeResolve = require('rollup-plugin-node-resolve'); const commonJS = require('rollup-plugin-commonjs'); module.exports = { frameworks: ['jasmine', 'sinon'], files: [ { pattern: '../src/**/*.js', watched: process.env.CI !== 'true', included: false, }, { pattern: '../spec/**/*.spec.js', watched: process.env.CI !== 'true', }, ], preprocessors: { '../spec/**/*.spec.js': ['rollup'], }, rollupPreprocessor: { format: 'iife', sourceMap: 'inline', plugins: [commonJS(), nodeResolve(), buble()], }, plugins: [ 'karma-jasmine', 'karma-sinon', 'karma-rollup-plugin', 'karma-spec-reporter', ], reporters: ['spec'], };
const buble = require('rollup-plugin-buble'); const nodeResolve = require('rollup-plugin-node-resolve'); const commonJS = require('rollup-plugin-commonjs'); module.exports = { frameworks: ['jasmine', 'sinon'], files: [ { pattern: '../src/**/*.js', watched: process.env.CI === 'true', included: false, }, { pattern: '../spec/**/*.spec.js', watched: process.env.CI === 'true', }, ], preprocessors: { '../spec/**/*.spec.js': ['rollup'], }, rollupPreprocessor: { format: 'iife', sourceMap: 'inline', plugins: [commonJS(), nodeResolve(), buble()], }, plugins: [ 'karma-jasmine', 'karma-sinon', 'karma-rollup-plugin', 'karma-spec-reporter', ], reporters: ['spec'], };
Initialize core before anything else gets required That makes sure you can import e.g. `rxjs` before importing `react-native` and will not receive errors that certain APIs are missing (like `setTimeout`) CC: da39a3ee5e6b4b0d3255bfef95601890afd80709@ferrannp
/** * Copyright 2017-present, Callstack. * All rights reserved. * * polyfillEnvironment.js * * This file is loaded as a part of user bundle */ /* eslint-disable import/no-extraneous-dependencies */ require('react-native/packager/src/Resolver/polyfills/polyfills.js'); require('react-native/packager/src/Resolver/polyfills/console.js'); require('react-native/packager/src/Resolver/polyfills/error-guard.js'); require('react-native/packager/src/Resolver/polyfills/Number.es6.js'); require('react-native/packager/src/Resolver/polyfills/String.prototype.es6.js'); require('react-native/packager/src/Resolver/polyfills/Array.prototype.es6.js'); require('react-native/packager/src/Resolver/polyfills/Array.es6.js'); require('react-native/packager/src/Resolver/polyfills/Object.es7.js'); require('react-native/packager/src/Resolver/polyfills/babelHelpers.js'); require('InitializeCore');
/** * Copyright 2017-present, Callstack. * All rights reserved. * * polyfillEnvironment.js * * This file is loaded as a part of user bundle /* eslint-disable import/no-extraneous-dependencies */ require('react-native/packager/src/Resolver/polyfills/polyfills.js'); require('react-native/packager/src/Resolver/polyfills/console.js'); require('react-native/packager/src/Resolver/polyfills/error-guard.js'); require('react-native/packager/src/Resolver/polyfills/Number.es6.js'); require('react-native/packager/src/Resolver/polyfills/String.prototype.es6.js'); require('react-native/packager/src/Resolver/polyfills/Array.prototype.es6.js'); require('react-native/packager/src/Resolver/polyfills/Array.es6.js'); require('react-native/packager/src/Resolver/polyfills/Object.es7.js'); require('react-native/packager/src/Resolver/polyfills/babelHelpers.js');
Add missing negation to documentation.
package com.bbn.bue.common.evaluation; import java.io.File; import java.io.IOException; /** * An object which records scoring events of objects where the expected (gold) item is of type {@link KeyT} and the * predicted (system) item is of type {@link TestT}. * * {@link #finish(File)} is expected to be called when there are no more items to inspect. What happens if more items * are observed after finishing is not defined by the interface contract. * * Implementations may silently take no action for some types of observations. For example, an F-score related observer * would take no action upon observation of a true negative. However, an implementation should not raise an exception * simply because it is asked to observe an event for which it will take no action. * * @author Constantine Lignos */ public interface ScoringEventObserver<KeyT, TestT> { /** * Records a true positive event. */ void observeTruePositive(KeyT gold, TestT predicted, double score); /** * Records a true negative event. */ void observeTrueNegative(KeyT gold, TestT predicted, double score); /** * Records a false positive event. */ void observeFalsePositive(TestT predicted, double score); /** * Records a false negative event. */ void observeFalseNegative(KeyT gold, double score); /** * Performs any final tasks, using the specified output directory as the base for output. */ void finish(File outputDirectory) throws IOException; }
package com.bbn.bue.common.evaluation; import java.io.File; import java.io.IOException; /** * An object which records scoring events of objects where the expected (gold) item is of type {@link KeyT} and the * predicted (system) item is of type {@link TestT}. * * {@link #finish(File)} is expected to be called when there are no more items to inspect. What happens if more items * are observed after finishing is not defined by the interface contract. * * Implementations may silently take no action for some types of observations. For example, an F-score related observer * would take no action upon observation of a true negative. However, an implementation should raise an exception simply * because it is asked to observe an event for which it will take no action. * * @author Constantine Lignos */ public interface ScoringEventObserver<KeyT, TestT> { /** * Records a true positive event. */ void observeTruePositive(KeyT gold, TestT predicted, double score); /** * Records a true negative event. */ void observeTrueNegative(KeyT gold, TestT predicted, double score); /** * Records a false positive event. */ void observeFalsePositive(TestT predicted, double score); /** * Records a false negative event. */ void observeFalseNegative(KeyT gold, double score); /** * Performs any final tasks, using the specified output directory as the base for output. */ void finish(File outputDirectory) throws IOException; }
Support standard `objectID` for article importer `$additionalData['articleID']` is used by the wordpress importer and kept as a fallback.
<?php namespace wcf\system\importer; use wcf\data\article\Article; use wcf\data\object\type\ObjectTypeCache; /** * Imports article comments. * * @author Marcel Werk * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Importer */ class ArticleCommentImporter extends AbstractCommentImporter { /** * @inheritDoc */ protected $objectTypeName = 'com.woltlab.wcf.article.comment'; /** * Creates a new ArticleCommentImporter object. */ public function __construct() { $objectType = ObjectTypeCache::getInstance()->getObjectTypeByName('com.woltlab.wcf.comment.commentableContent', 'com.woltlab.wcf.articleComment'); $this->objectTypeID = $objectType->objectTypeID; } /** * @inheritDoc */ public function import($oldID, array $data, array $additionalData = []) { $articleID = ImportHandler::getInstance()->getNewID('com.woltlab.wcf.article', $data['objectID'] ?? $additionalData['articleID']); if (!$articleID) return 0; $article = new Article($articleID); $contents = $article->getArticleContents(); $data['objectID'] = reset($contents)->articleContentID; return parent::import($oldID, $data); } }
<?php namespace wcf\system\importer; use wcf\data\article\Article; use wcf\data\object\type\ObjectTypeCache; /** * Imports article comments. * * @author Marcel Werk * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Importer */ class ArticleCommentImporter extends AbstractCommentImporter { /** * @inheritDoc */ protected $objectTypeName = 'com.woltlab.wcf.article.comment'; /** * Creates a new ArticleCommentImporter object. */ public function __construct() { $objectType = ObjectTypeCache::getInstance()->getObjectTypeByName('com.woltlab.wcf.comment.commentableContent', 'com.woltlab.wcf.articleComment'); $this->objectTypeID = $objectType->objectTypeID; } /** * @inheritDoc */ public function import($oldID, array $data, array $additionalData = []) { $articleID = ImportHandler::getInstance()->getNewID('com.woltlab.wcf.article', $additionalData['articleID']); if (!$articleID) return 0; $article = new Article($articleID); $contents = $article->getArticleContents(); $data['objectID'] = reset($contents)->articleContentID; return parent::import($oldID, $data); } }
Add specific indicator functionality to page indicators Allows us to specify the precise location we'd like the page indicators to appear.
define(['jquery', 'Templates', 'IndicatorFilter'], function($, Templates, IndicatorFilter) { /** * Renders the page indicators specified by spec.page_indicators * into the container specified by spec.page_indicator_box */ var constructor = function(spec, indicatorContainer) { var indicatorFilter = new IndicatorFilter(spec, null); return { handle: function(pulls) { indicatorContainer.empty(); indicatorFilter.filter(pulls, $('body'), function(elem, filterName) { // elem will be the body tag. We'll ignore in in here. // Render the 'global_indicator' template into the indicators element return Templates.renderIntoContainer('global_indicator', {name: filterName}, indicatorContainer); // Notice that we render using the indicatorContainer as the // holder. That's because that's where autocreated indicators // are supposed to be rendered into }); } }; }; return constructor; });
define(['jquery', 'Templates', 'IndicatorFilter'], function($, Templates, IndicatorFilter) { /** * Renders the page indicators specified by spec.page_indicators * into the container specified by spec.page_indicator_box */ var constructor = function(spec, indicatorContainer) { var indicatorFilter = new IndicatorFilter(spec, null); return { handle: function(pulls) { indicatorContainer.empty(); indicatorFilter.filter(pulls, indicatorContainer, function(elem, filterName) { // Render the 'indicator' template into the indicators element return Templates.renderIntoContainer('global_indicator', {name: filterName}, elem); }); } }; }; return constructor; });
Add method description to `conduit.query` Summary: As suggested in T6950, add the method description to the response from `conduit.query`. Test Plan: Called `echo '{}' | arc call-conduit conduit.query` and verified that the response contained the method description. Reviewers: epriestley, #blessed_reviewers Reviewed By: epriestley, #blessed_reviewers Subscribers: Korvin, epriestley Differential Revision: https://secure.phabricator.com/D11467
<?php final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod { public function getAPIMethodName() { return 'conduit.query'; } public function getMethodDescription() { return 'Returns the parameters of the Conduit methods.'; } public function defineParamTypes() { return array(); } public function defineReturnType() { return 'dict<dict>'; } public function defineErrorTypes() { return array(); } protected function execute(ConduitAPIRequest $request) { $classes = id(new PhutilSymbolLoader()) ->setAncestorClass('ConduitAPIMethod') ->setType('class') ->loadObjects(); $names_to_params = array(); foreach ($classes as $class) { $names_to_params[$class->getAPIMethodName()] = array( 'description' => $class->getMethodDescription(), 'params' => $class->defineParamTypes(), 'return' => $class->defineReturnType(), ); } return $names_to_params; } }
<?php final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod { public function getAPIMethodName() { return 'conduit.query'; } public function getMethodDescription() { return 'Returns the parameters of the Conduit methods.'; } public function defineParamTypes() { return array(); } public function defineReturnType() { return 'dict<dict>'; } public function defineErrorTypes() { return array(); } protected function execute(ConduitAPIRequest $request) { $classes = id(new PhutilSymbolLoader()) ->setAncestorClass('ConduitAPIMethod') ->setType('class') ->loadObjects(); $names_to_params = array(); foreach ($classes as $class) { $names_to_params[$class->getAPIMethodName()] = array( 'params' => $class->defineParamTypes(), 'return' => $class->defineReturnType(), ); } return $names_to_params; } }
Clean up the configuration before and after the test.
package com.rackspacecloud.blueflood.service; import com.rackspacecloud.blueflood.utils.Util; import org.junit.*; import java.io.IOException; import java.util.Collection; import java.util.Collections; public class RollupServiceTest { @Before public void setup() throws IOException { Configuration.getInstance().init(); } @After public void tearDown() throws IOException { Configuration.getInstance().init(); } @Test public void testRollupServiceWithDefaultConfigs() { Configuration config = Configuration.getInstance(); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final ScheduleContext rollupContext = "NONE".equals(zkCluster) ? new ScheduleContext(System.currentTimeMillis(), shards) : new ScheduleContext(System.currentTimeMillis(), shards, zkCluster); RollupService service = new RollupService(rollupContext); Assert.assertNotNull(service); service.run(null, 120000L); // default SCHEDULE_POLL_PERIOD is 60 seconds Assert.assertTrue(true); } }
package com.rackspacecloud.blueflood.service; import com.rackspacecloud.blueflood.utils.Util; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.Collection; import java.util.Collections; public class RollupServiceTest { @Test public void testRollupServiceWithDefaultConfigs() { Configuration config = Configuration.getInstance(); final Collection<Integer> shards = Collections.unmodifiableCollection( Util.parseShards(config.getStringProperty(CoreConfig.SHARDS))); final String zkCluster = config.getStringProperty(CoreConfig.ZOOKEEPER_CLUSTER); final ScheduleContext rollupContext = "NONE".equals(zkCluster) ? new ScheduleContext(System.currentTimeMillis(), shards) : new ScheduleContext(System.currentTimeMillis(), shards, zkCluster); RollupService service = new RollupService(rollupContext); Assert.assertNotNull(service); service.run(null, 120000L); // default SCHEDULE_POLL_PERIOD is 60 seconds Assert.assertTrue(true); } }
Fix NAVY_EXTERNAL_IP and NAVY_HOST not working
/* @flow */ import {getExternalIP} from './external-ip' const BASE = 'xip.io' function isValidIpv4Addr(ip) { return /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/g.test(ip) } export function getXIPSubdomain() { const externalIP = getExternalIP() if (externalIP === '127.0.0.1') { // shorten return `0.${BASE}` } if (isValidIpv4Addr(externalIP)) { // invalid IP address, fallback to local return `0.${BASE}` } return `${externalIP}.${BASE}` } export function getHostForService(service: string, navyNormalisedName: string) { return `${service}.${navyNormalisedName}.${process.env.NAVY_EXTERNAL_SUBDOMAIN || getXIPSubdomain()}` } export function getUrlForService(service: string, navyNormalisedName: string) { return `http://${getHostForService(service, navyNormalisedName)}` }
/* @flow */ import {getExternalIP} from './external-ip' const BASE = 'xip.io' function isValidIpv4Addr(ip) { return /^(?=\d+\.\d+\.\d+\.\d+$)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.?){4}$/.test(ip) } export function getXIPSubdomain() { const externalIP = getExternalIP() if (externalIP === '127.0.0.1') { // shorten return `0.${BASE}` } if (isValidIpv4Addr(externalIP)) { // invalid IP address, fallback to local return `0.${BASE}` } return `${externalIP}.${BASE}` } export function getHostForService(service: string, navyNormalisedName: string) { return `${service}.${navyNormalisedName}.${process.env.NAVY_EXTERNAL_SUBDOMAIN || getXIPSubdomain()}` } export function getUrlForService(service: string, navyNormalisedName: string) { return `http://${getHostForService(service, navyNormalisedName)}` }
Fix and re-enable the reset management command test. Not 100% sure of why this fixes the issue - it appears that changes to django.test.TestCase in Django 2.0 led to the test failing.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TransactionTestCase from django.contrib.auth.models import User from django.core.management import call_command from core.models import Child class CommandsTestCase(TransactionTestCase): def test_migrate(self): call_command('migrate', verbosity=0) self.assertIsInstance(User.objects.get(username='admin'), User) def test_fake(self): call_command('migrate', verbosity=0) call_command('fake', children=1, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 1) call_command('fake', children=2, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 3) def test_reset(self): call_command('reset', verbosity=0, interactive=False) self.assertIsInstance(User.objects.get(username='admin'), User) self.assertEqual(Child.objects.count(), 1)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth.models import User from django.core.management import call_command from core.models import Child class CommandsTestCase(TestCase): def test_migrate(self): call_command('migrate', verbosity=0) self.assertIsInstance(User.objects.get(username='admin'), User) def test_fake(self): call_command('migrate', verbosity=0) call_command('fake', children=1, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 1) call_command('fake', children=2, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 3) """def test_reset(self): call_command('reset', verbosity=0, interactive=False) self.assertIsInstance(User.objects.get(username='admin'), User) self.assertEqual(Child.objects.count(), 1)"""
Use keyword based `format` to maintain 2.6 compatibility
from six import string_types from django.db.models import signals from .invalidation import invalidate_paths def register(model): register_instance_function_at_save(model, invalidate_model_paths) def register_instance_function_at_save(model, function): def save_function(sender, instance, **kwargs): function(instance) signals.post_save.connect(save_function, model, weak=False) signals.pre_delete.connect(save_function, model, weak=False) def get_paths_from_model(model): paths = model.dependent_paths() if isinstance(paths, string_types): model_name = model.__class__.__name__ raise TypeError( ('dependent_paths on {model_name} should return a list of paths, ' ' not a string'.format(model_name=model_name)) ) return paths def invalidate_model_paths(model): paths = get_paths_from_model(model) invalidate_paths(paths)
from six import string_types from django.db.models import signals from .invalidation import invalidate_paths def register(model): register_instance_function_at_save(model, invalidate_model_paths) def register_instance_function_at_save(model, function): def save_function(sender, instance, **kwargs): function(instance) signals.post_save.connect(save_function, model, weak=False) signals.pre_delete.connect(save_function, model, weak=False) def get_paths_from_model(model): paths = model.dependent_paths() if isinstance(paths, string_types): model_name = model.__class__.__name__ raise TypeError( ('dependent_paths on {} should return a list of paths, not a' 'string'.format(model_name)) ) return paths def invalidate_model_paths(model): paths = get_paths_from_model(model) invalidate_paths(paths)
Add yaml to installation requirements
from setuptools import setup, find_packages setup(name='aacrgenie', version='1.6.2', description='Processing and validation for GENIE', url='https://github.com/Sage-Bionetworks/Genie', author='Thomas Yu', author_email='thomasyu888@gmail.com', license='MIT', packages=find_packages(), zip_safe=False, data_files=[('genie',['genie/addFeatureType.sh','genie/createGTF.sh'])], entry_points = { 'console_scripts': ['genie = genie.__main__:main']}, install_requires=[ 'pandas>=0.20.0', 'synapseclient>=1.9', 'httplib2>=0.11.3', 'pycrypto>=2.6.1', 'yaml>=3.11'])
from setuptools import setup, find_packages setup(name='aacrgenie', version='1.6.2', description='Processing and validation for GENIE', url='https://github.com/Sage-Bionetworks/Genie', author='Thomas Yu', author_email='thomasyu888@gmail.com', license='MIT', packages=find_packages(), zip_safe=False, data_files=[('genie',['genie/addFeatureType.sh','genie/createGTF.sh'])], entry_points = { 'console_scripts': ['genie = genie.__main__:main']}, install_requires=[ 'pandas>=0.20.0', 'synapseclient', 'httplib2', 'pycrypto'])
Fix Content-Security-Policy warnings in the dummy app.
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', contentSecurityPolicy: { 'img-src': "'self' data:", 'media-src': "'self' http://vjs.zencdn.net" }, 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') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', 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') { } return ENV; };
Make compatible with py-redis 3.x Fixes https://github.com/thumbor/remotecv/issues/25
from redis import Redis from remotecv.result_store import BaseStore from remotecv.utils import logger class ResultStore(BaseStore): WEEK = 604800 redis_instance = None def __init__(self, config): super(ResultStore, self).__init__(config) if not ResultStore.redis_instance: ResultStore.redis_instance = Redis( host=config.redis_host, port=config.redis_port, db=config.redis_database, password=config.redis_password, ) self.storage = ResultStore.redis_instance def store(self, key, points): result = self.serialize(points) logger.debug("Points found: %s", result) redis_key = "thumbor-detector-%s" % key self.storage.setex( name=redis_key, value=result, time=2 * self.WEEK, )
from redis import Redis from remotecv.result_store import BaseStore from remotecv.utils import logger class ResultStore(BaseStore): WEEK = 604800 redis_instance = None def __init__(self, config): super(ResultStore, self).__init__(config) if not ResultStore.redis_instance: ResultStore.redis_instance = Redis( host=config.redis_host, port=config.redis_port, db=config.redis_database, password=config.redis_password, ) self.storage = ResultStore.redis_instance def store(self, key, points): result = self.serialize(points) logger.debug("Points found: %s", result) redis_key = "thumbor-detector-%s" % key self.storage.setex(redis_key, result, 2 * self.WEEK)
Handle null found project for default java project finder
package org.springframework.ide.vscode.commons.languageserver.java; import org.springframework.ide.vscode.commons.java.IJavaProject; import org.springframework.ide.vscode.commons.languageserver.util.IDocument; public class DefaultJavaProjectFinder implements JavaProjectFinder { private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] { new JavaProjectWithClasspathFileFinderStrategy(), new MavenProjectFinderStrategy() }; @Override public IJavaProject find(IDocument d) { for (IJavaProjectFinderStrategy strategy : STRATEGIES) { try { IJavaProject project = strategy.find(d); if (project != null) { return project; } } catch (Throwable t) { // Log perhaps? } } return null; } }
package org.springframework.ide.vscode.commons.languageserver.java; import org.springframework.ide.vscode.commons.java.IJavaProject; import org.springframework.ide.vscode.commons.languageserver.util.IDocument; public class DefaultJavaProjectFinder implements JavaProjectFinder { private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] { new JavaProjectWithClasspathFileFinderStrategy(), new MavenProjectFinderStrategy() }; @Override public IJavaProject find(IDocument d) { for (IJavaProjectFinderStrategy strategy : STRATEGIES) { try { return strategy.find(d); } catch (Throwable t) { // Log perhaps? } } return null; } }
Fix for using defaultClickHandler in pages that do not have Backbone.history initialized.
/* Add a default clickhandler so we can use hrefs */ Backbone.View.prototype.defaultClickHandler = function( e ) { // Return if a modifier key is pressed or when Backbone has not properly been initialized // Make sure we return "true" so other functions can determine what happened // Note that the capitalization in Backbone.[H]istory is intentional if ( e.metaKey || e.ctrlKey || e.altKey || !Backbone.History.started ) return true; var routeTo = $(e.target).closest('a').attr('href'); console.log("Navigating to "+ routeTo, 'from /'+ Backbone.history.fragment); if ('/' + Backbone.history.fragment == routeTo) { Backbone.history.fragment = null; Backbone.history.navigate(routeTo, {trigger: true, replace: true}); } else { Backbone.history.navigate(routeTo, {trigger: true}); } e.preventDefault(); return false; }; /* HACK: this is needed because internal events did not seem to work*/ $(":not(div.modal) a[rel=backbone]").live("click",Backbone.View.prototype.defaultClickHandler);
/* Add a default clickhandler so we can use hrefs */ Backbone.View.prototype.defaultClickHandler = function( e ) { if ( e.metaKey || e.ctrlKey || e.altKey ) return; var routeTo = $(e.target).closest('a').attr('href'); console.log("Navigating to "+ routeTo, 'from /'+ Backbone.history.fragment); if ('/' + Backbone.history.fragment == routeTo) { Backbone.history.fragment = null; Backbone.history.navigate(routeTo, {trigger: true, replace: true}); } else { Backbone.history.navigate(routeTo, {trigger: true}); } e.preventDefault(); return false; }; /* HACK: this is needed because internal events did not seem to work*/ $(":not(div.modal) a[rel=backbone]").live("click",Backbone.View.prototype.defaultClickHandler);
Update feedparse() for PHP 5
<?php /* * Core functions. * * Don't forget to add own ones. */ // `encrypt` // // Encrypts `$str` in rot13. function encrypt($str) { echo str_rot13($str); } // `decrypt` // // Decrypts `$str` in rot13. Gives `$str` as output. function decrypt($str) { echo str_rot13(str_rot13($str)); } // `cfile` // // Checks for current file. Change the target class name if necessary. function cfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `fcount` // // Counts number of files in a directory. function fcount($dir) { $i = 0; if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) { $i++; } } } } // `feedparse` // // Parses RSS or Atom feeds. function feedparse($url) { $feed = fopen("$url", 'r'); $data = stream_get_contents($feed); fclose($feed); echo $data; } ?>
<?php /* * Core functions. * * Don't forget to add own ones. */ // `encrypt` // // Encrypts `$str` in rot13. function encrypt($str) { echo str_rot13($str); } // `decrypt` // // Decrypts `$str` in rot13. Gives `$str` as output. function decrypt($str) { echo str_rot13(str_rot13($str)); } // `cfile` // // Checks for current file. Change the target class name if necessary. function cfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `fcount` // // Counts number of files in a directory. function fcount($dir) { $i = 0; if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) { $i++; } } } } // `feedparse` // // Parses RSS or Atom feeds. function feedparse($url) { $feed = @fopen("$url", 'r'); if ($feed) { $data = ''; while (!feof($feed)) { $data .= fread($feed, 8192); } } fclose($feed); echo $data; } ?>
Remove whitespace at end of file
from rest_framework import serializers from dwitter.models import Dweet, Comment from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'username') class CommentSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') posted = serializers.ReadOnlyField() class Meta: model = Comment fields = ('text', 'posted', 'reply_to', 'author') class DweetSerializer(serializers.ModelSerializer): latest_comments = serializers.SerializerMethodField() reply_to = serializers.PrimaryKeyRelatedField(queryset=Dweet.objects.all()) class Meta: model = Dweet fields = ('pk', 'code', 'posted', 'author', 'likes','reply_to', 'latest_comments') def get_latest_comments(self, obj): cmnts = obj.comments.all().order_by('-posted') return CommentSerializer(cmnts[:3], many=True).data
from rest_framework import serializers from dwitter.models import Dweet, Comment from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'username') class CommentSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') posted = serializers.ReadOnlyField() class Meta: model = Comment fields = ('text', 'posted', 'reply_to', 'author') class DweetSerializer(serializers.ModelSerializer): latest_comments = serializers.SerializerMethodField() reply_to = serializers.PrimaryKeyRelatedField(queryset=Dweet.objects.all()) class Meta: model = Dweet fields = ('pk', 'code', 'posted', 'author', 'likes','reply_to', 'latest_comments') def get_latest_comments(self, obj): cmnts = obj.comments.all().order_by('-posted') return CommentSerializer(cmnts[:3], many=True).data
Consolidate quotation of HTML attributes in dumps
<?php namespace Gobie\Debug\Dumpers; use Gobie\Debug\DumperManager\IDumperManager; use Gobie\Debug\Helpers; /** * Dumper řetězce. */ class StringDumper extends AbstractDumper { /** * Nastaví typ proménné na 'string'. * * Zkontroluje dostupnost potřebné extenze. */ public function __construct() { $this->setTypes(IDumperManager::T_STRING); } public function dump(&$var, $level = 1, $depth = 4) { $varEnc = Helpers::encodeString($var); $varLen = strlen($var); return '<span class="dump_arg_string">' . $varEnc . '</span>' . ($varLen ? ' <span class="dump_arg_desc">(' . $varLen . ')</span>' : ''); } }
<?php namespace Gobie\Debug\Dumpers; use Gobie\Debug\DumperManager\IDumperManager; use Gobie\Debug\Helpers; /** * Dumper řetězce. */ class StringDumper extends AbstractDumper { /** * Nastaví typ proménné na 'string'. * * Zkontroluje dostupnost potřebné extenze. */ public function __construct() { $this->setTypes(IDumperManager::T_STRING); } public function dump(&$var, $level = 1, $depth = 4) { $varEnc = Helpers::encodeString($var); $varLen = strlen($var); return "<span class='dump_arg_string'>" . $varEnc . "</span>" . ($varLen ? " <span class='dump_arg_desc'>(" . $varLen . ')</span>' : ''); } }