text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix issue when source and destination has the same path It should override the source rather than creating an empty file. Ref. #17.
var Compressor = require('node-minify').minify; exports.init = function(grunt) { // Refactored out the `min_max_info` and `concat` helpers here // because `grunt.helper` is removed in future Grunt versions var minMax = require('grunt-lib-contrib').init(grunt).minMaxInfo, concat = function(source) { // Kinda hacky, but that’s how I roll… return source.map(function(filepath) { return grunt.file.read(filepath); }).join('\n'); }; return function(options) { var source = grunt.file.expand(options.source), destination = options.destination, max = concat(source), min, report = options.report; if (source.indexOf(destination) === -1) { // Ugly hack to create the destination path automatically if needed grunt.file.write(destination, ''); } // Minify all the things! new Compressor({ 'type': 'yui-' + options.type, 'fileIn': source, 'fileOut': destination, 'callback': function(error) { if (error) { grunt.warn(error); return options.fn(); } min = grunt.file.read(destination); grunt.log.writeln('File `' + destination + '` created.'); minMax(min, max, report); // Let Grunt know the asynchronous task has completed options.fn(); } }); }; };
var Compressor = require('node-minify').minify; exports.init = function(grunt) { // Refactored out the `min_max_info` and `concat` helpers here // because `grunt.helper` is removed in future Grunt versions var minMax = require('grunt-lib-contrib').init(grunt).minMaxInfo, concat = function(source) { // Kinda hacky, but that’s how I roll… return source.map(function(filepath) { return grunt.file.read(filepath); }).join('\n'); }; return function(options) { var source = grunt.file.expand(options.source), destination = options.destination, max = concat(source), min, report = options.report; // Ugly hack to create the destination path automatically if needed grunt.file.write(destination, ''); // Minify all the things! new Compressor({ 'type': 'yui-' + options.type, 'fileIn': source, 'fileOut': destination, 'callback': function(error) { if (error) { grunt.warn(error); return options.fn(); } min = grunt.file.read(destination); grunt.log.writeln('File `' + destination + '` created.'); minMax(min, max, report); // Let Grunt know the asynchronous task has completed options.fn(); } }); }; };
Remove tests that are not relevant anymore.
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'generates a unique ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, {} ); expect( props ).toHaveProperty( 'id' ); } ); it( 'uses the existing anchor attribute as the ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { anchor: 'foo' } ); expect( props ).toStrictEqual( { id: 'foo' } ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
Add a utility that checks if a user has a certain role
/** * Created by djarosz on 11/6/15. */ /** * The purpose of this file is to store all functions and utilities that are used by multiple routes. */ function filterBody(strings) { return function (req, res, next) { var k, found = false; for (k in req.body) { if (req.body.hasOwnProperty(k)) { if (strings.indexOf(k) !== -1) { found = true; } else { req.body[k] = null; } } } if (found) { next(); } else { return res.send(400, 'cannot find required information in body'); } }; } function checkUserRole(req, role){ if(req.session.roles != undefined && req.session.roles.indexOf(role) != -1) { return true; } else { return false; } } module.exports = { filterBody: filterBody, checkUserRole: checkUserRole };
/** * Created by djarosz on 11/6/15. */ /** * The purpose of this file is to store all functions and utilities that are used by multiple routes. */ function filterBody(strings) { return function (req, res, next) { var k, found = false; for (k in req.body) { if (req.body.hasOwnProperty(k)) { if (strings.indexOf(k) !== -1) { found = true; } else { req.body[k] = null; } } } if (found) { next(); } else { return res.send(400, 'cannot find required information in body'); } }; } module.exports = { filterBody: filterBody };
Implement Put for Document struct
package data import ( "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Document struct { ID bson.ObjectId `bson:"_id"` ShortID string `bson:"short_id"` Title string `bson:"title"` Content string `bson:"content"` Tags []string `bson:"tags"` Published bool `bson:"publishd"` PublishedAt time.Time `bson:"pushlished_at"` AccessToken string `bson:"access_token"` CreatedAt time.Time `bson:"created_at"` ModifiedAt time.Time `bson:"modified_at"` } func GetDocument(id bson.ObjectId) (*Document, error) { doc := Document{} err := sess.DB("").C(documentC).FindId(id).One(&doc) if err == mgo.ErrNotFound { return nil, nil } if err != nil { return nil, err } return &doc, nil } func (d *Document) Put() error { d.ModifiedAt = time.Now() if d.ID == "" { d.ID = bson.NewObjectId() d.CreatedAt = d.ModifiedAt } _, err := sess.DB("").C(documentC).UpsertId(d.ID, d) return err }
package data import ( "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Document struct { ID bson.ObjectId `bson:"_id"` ShortId string `bson:"short_id"` Title string `bson:"title"` Content string `bson:"content"` Tags []string `bson:"tags"` Published bool `bson:"publishd"` PublishedAt time.Time `bson:"pushlished_at"` AccessToken string `bson:"access_token"` CreatedAt time.Time `bson:"created_at"` ModifiedAt time.Time `bson:"modified_at"` } func GetDocument(id bson.ObjectId) (*Document, error) { doc := Document{} err := sess.DB("").C(documentC).FindId(id).One(&doc) if err == mgo.ErrNotFound { return nil, nil } if err != nil { return nil, err } return &doc, nil }
Use DjangoModelFactory subclass for images test
from __future__ import unicode_literals from django.contrib.auth.models import User from django.test import TestCase import factory from faker import Faker from imager_profile.models import ImagerProfile from .models import Album, Photo # Create your tests here. fake = Faker() class UserFactory(factory.django.DjangoModelFactory): """Create a fake user.""" class Meta: model = User username = factory.Sequence(lambda n: 'user{}'.format(n)) first_name = fake.first_name() last_name = fake.last_name() email = fake.email() class PhotoFactory(factory.django.DjangoModelFactory): """Create a fake photo.""" class Meta: model = Photo photo = factory.django.ImageField() title = fake.sentence() description = fake.text() class AlbumFactory(factory.django.DjangoModelFactory): """Create a fake album.""" class Meta: model = Album title = fake.sentence() description = fake.text()
from __future__ import unicode_literals from django.contrib.auth.models import User from django.test import TestCase import factory from faker import Faker from imager_profile.models import ImagerProfile from .models import Album, Photo # Create your tests here. fake = Faker() class UserFactory(factory.Factory): """Create a fake user.""" class Meta: model = User username = factory.Sequence(lambda n: 'user{}'.format(n)) first_name = fake.first_name() last_name = fake.last_name() email = fake.email() class PhotoFactory(factory.django.DjangoModelFactory): """Create a fake photo.""" class Meta: model = Photo photo = factory.django.ImageField() title = fake.sentence() description = fake.text()
Use mutex to avoid concurrent write to metrics log file
package middlewares import ( "fmt" "io" "net/http" "sync" "github.com/urfave/negroni" "os" "time" "github.com/pkg/errors" ) type MetricsMiddleware struct { writer io.Writer writerMutex sync.Mutex } func NewMetricsMiddlewareFromFilename(filename string) *MetricsMiddleware { fileWriter, e := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0664) if e != nil { panic(errors.Wrapf(e, "Could not open file '%v' for appending", filename)) } return &MetricsMiddleware{writer: fileWriter} } func NewMetricsMiddleware(writer io.Writer) *MetricsMiddleware { return &MetricsMiddleware{writer: writer} } func (middleware *MetricsMiddleware) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request, next http.HandlerFunc) { startTime := time.Now() negroniResponseWriter, ok := responseWriter.(negroni.ResponseWriter) if !ok { negroniResponseWriter = negroni.NewResponseWriter(responseWriter) } next(negroniResponseWriter, request) middleware.writerMutex.Lock() defer middleware.writerMutex.Unlock() fmt.Fprintf(middleware.writer, "%v %v %v;%v;%v\n", request.Method, request.URL.Path, request.Proto, time.Since(startTime).Seconds(), negroniResponseWriter.Size()) }
package middlewares import ( "fmt" "io" "net/http" "github.com/urfave/negroni" "os" "time" "github.com/pkg/errors" ) type MetricsMiddleware struct { writer io.Writer } func NewMetricsMiddlewareFromFilename(filename string) *MetricsMiddleware { fileWriter, e := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0664) if e != nil { panic(errors.Wrapf(e, "Could not open file '%v' for appending", filename)) } return &MetricsMiddleware{writer: fileWriter} } func NewMetricsMiddleware(writer io.Writer) *MetricsMiddleware { return &MetricsMiddleware{writer: writer} } func (middleware *MetricsMiddleware) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request, next http.HandlerFunc) { startTime := time.Now() negroniResponseWriter, ok := responseWriter.(negroni.ResponseWriter) if !ok { negroniResponseWriter = negroni.NewResponseWriter(responseWriter) } next(negroniResponseWriter, request) fmt.Fprintf(middleware.writer, "%v %v %v;%v;%v\n", request.Method, request.URL.Path, request.Proto, time.Since(startTime).Seconds(), negroniResponseWriter.Size()) }
Make mutable table suffix shorter Pull request: https://github.com/prestodb/tempto/pull/214
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.teradata.tempto.internal.fulfillment.table; import static org.apache.commons.lang3.RandomStringUtils.random; public class TableNameGenerator { private static final String MUTABLE_TABLE_NAME_PREFIX = "tempto_mut_"; public String generateMutableTableNameInDatabase(String baseTableName) { return MUTABLE_TABLE_NAME_PREFIX + baseTableName + "_" + random(8); } public boolean isMutableTableName(String tableNameInDatabase) { return tableNameInDatabase.startsWith(MUTABLE_TABLE_NAME_PREFIX); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.teradata.tempto.internal.fulfillment.table; import java.util.UUID; public class TableNameGenerator { private static final String MUTABLE_TABLE_NAME_PREFIX = "tempto_mut_"; public String generateMutableTableNameInDatabase(String baseTableName) { String tableSuffix = randomUUID().replace("-", ""); return MUTABLE_TABLE_NAME_PREFIX + baseTableName + "_" + tableSuffix; } public boolean isMutableTableName(String tableNameInDatabase) { return tableNameInDatabase.startsWith(MUTABLE_TABLE_NAME_PREFIX); } private String randomUUID() { return UUID.randomUUID().toString(); } }
Apply monkeypatching from eventlet before the tests starts This should prevent issues with classes which may not have been otherwise instrumented (and sahara_engine and sahara_all do the instrumentation at the beginning anyway). Issues have been notices with eventlet 0.20.1 which now instruments subprocess. Change-Id: I17adb877483dbf0b0aa559029c61715d1cef9d7b
# Copyright (c) 2014 Mirantis Inc. # # 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 sahara.utils import patches patches.patch_all() import oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
# Copyright (c) 2014 Mirantis Inc. # # 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 oslo_i18n # NOTE(slukjanov): i18n.enable_lazy() must be called before # sahara.utils.i18n._() is called to ensure it has the desired # lazy lookup behavior. oslo_i18n.enable_lazy()
Set wait variable to 10 seconds.
Class Application(object): def __init__(sefl, driver): self.driver = driver self.wait = WebDriverWait(driver, 10) def go_to_homepage(self): self.driver.get("http://hub.wart.ru/php4dvd/") def login(self, user): driver = self.driver driver.find_element_by_id("username").clear() driver.find_element_by_id("username").send_keys(user.username) driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys(user.password) driver.find_element_by_id("submit").click() def logout(self): driver = self.driver driver.find_element_by_link_text("Log out").click() driver.switch_to_alert().accept() def is_element_present(driver, how, what): try: driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True
Class Application(object): def __init__(sefl, driver): self.driver = driver def go_to_homepage(self): self.driver.get("http://hub.wart.ru/php4dvd/") def login(self, user): driver = self.driver driver.find_element_by_id("username").clear() driver.find_element_by_id("username").send_keys(user.username) driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys(user.password) driver.find_element_by_id("submit").click() def logout(self): driver = self.driver driver.find_element_by_link_text("Log out").click() driver.switch_to_alert().accept() def is_element_present(driver, how, what): try: driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True
Update redux devtools global variable
import React from 'react' import {createStore} from 'redux' import {Provider} from 'react-redux' import deref from 'json-schema-deref-local' import Root from './components/Root' import rootReducer from './reducers' import {init} from './actions' import {importData, exportData} from './utilities/data' import './index.css' const store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) const PropertyGrid = ({schema, data = {}, title = 'Properties', onChange}) => { store.dispatch(init(deref(schema), importData(data))) if (onChange != null) { store.subscribe(() => onChange(exportData(store.getState().data))) } if (module.hot) { module.hot.accept('./reducers', () => { const nextRootReducer = require('./reducers').default store.replaceReducer(nextRootReducer) }) } return ( <Provider store={store}> <Root title={title} onChange={onChange} /> </Provider> ) } export default PropertyGrid
import React from 'react' import {createStore} from 'redux' import {Provider} from 'react-redux' import deref from 'json-schema-deref-local' import Root from './components/Root' import rootReducer from './reducers' import {init} from './actions' import {importData, exportData} from './utilities/data' import './index.css' const PropertyGrid = ({schema, data = {}, title = 'Properties', onChange}) => { const store = createStore(rootReducer, null, window.devToolsExtension ? window.devToolsExtension() : f => f ) store.dispatch(init(deref(schema), importData(data))) if (onChange != null) { store.subscribe(() => onChange(exportData(store.getState().data))) } if (module.hot) { module.hot.accept('./reducers', () => { const nextRootReducer = require('./reducers').default store.replaceReducer(nextRootReducer) }) } return ( <Provider store={store}> <Root title={title} onChange={onChange} /> </Provider> ) } export default PropertyGrid
Use min of specified byte count and limit, not max.
from astral.api.handlers.base import BaseHandler from astral.conf import settings import logging log = logging.getLogger(__name__) class PingHandler(BaseHandler): def get(self): """If 'bytes' is specified in the query string, return that number of random bytes (for the purposes of a downstream bandwidth measurement). Otherwise, returns a simple 200 OK HTTP response, to check the RTT. """ byte_count = self.get_argument('bytes', None) if byte_count: byte_count = int(byte_count) log.debug("Returning %s bytes for a downstream bandwidth test", byte_count) with open('/dev/urandom') as random_file: self.write(random_file.read( min(byte_count, settings.DOWNSTREAM_CHECK_LIMIT))) else: self.write("Pong!") log.debug("Responded to a ping") def post(self): """Accept arbitrary POST data to check upstream bandwidth. Limit the size to make sure we aren't DoS'd. """ log.debug("Received an upstream bandwidth check with %s bytes", len(self.request.body))
from astral.api.handlers.base import BaseHandler from astral.conf import settings import logging log = logging.getLogger(__name__) class PingHandler(BaseHandler): def get(self): """If 'bytes' is specified in the query string, return that number of random bytes (for the purposes of a downstream bandwidth measurement). Otherwise, returns a simple 200 OK HTTP response, to check the RTT. """ byte_count = self.get_argument('bytes', None) if byte_count: byte_count = int(byte_count) log.debug("Returning %s bytes for a downstream bandwidth test", byte_count) with open('/dev/urandom') as random_file: self.write(random_file.read( max(byte_count, settings.DOWNSTREAM_CHECK_LIMIT))) else: self.write("Pong!") log.debug("Responded to a ping") def post(self): """Accept arbitrary POST data to check upstream bandwidth. Limit the size to make sure we aren't DoS'd. """ log.debug("Received an upstream bandwidth check with %s bytes", len(self.request.body))
Enable latest version of basictracer
from setuptools import setup, find_packages setup( name='lightstep', version='4.1.0', description='LightStep Python OpenTracing Implementation', long_description='', author='LightStep', license='', install_requires=['thrift>=0.10.0,<0.12.0', 'jsonpickle', 'six', 'basictracer>=3.0,<4', 'googleapis-common-protos>=1.5.3,<2.0', 'requests>=2.19,<3.0', 'protobuf>=3.6.0,<4.0'], tests_require=['pytest', 'sphinx', 'sphinx-epytext'], classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', ], keywords=[ 'opentracing', 'lightstep', 'traceguide', 'tracing', 'microservices', 'distributed' ], packages=find_packages(exclude=['docs*', 'tests*', 'sample*']), )
from setuptools import setup, find_packages setup( name='lightstep', version='4.1.0', description='LightStep Python OpenTracing Implementation', long_description='', author='LightStep', license='', install_requires=['thrift>=0.10.0,<0.12.0', 'jsonpickle', 'six', 'basictracer>=3.0,<3.1', 'googleapis-common-protos>=1.5.3,<2.0', 'requests>=2.19,<3.0', 'protobuf>=3.6.0,<4.0'], tests_require=['pytest', 'sphinx', 'sphinx-epytext'], classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', ], keywords=[ 'opentracing', 'lightstep', 'traceguide', 'tracing', 'microservices', 'distributed' ], packages=find_packages(exclude=['docs*', 'tests*', 'sample*']), )
Fix gate for neutron-lib v2.14 A patch [1] that updates upper-constraints.txt for neutron-lib 2.14 fails to pass check pipeline. Due to development sequence it's necessary to append a new rule type to VALID_RULE_TYPES in Neutron first, and then move it to neutron-lib. Because of this process, there's a risk that the new rule type is present in both Neutron and in neutron-lib. This is why check pipeline keeps failing with neutron-lib v2.14, as it contains 'packet_rate_limit' and in Neutron we append it to the list anyways, ending up with duplicates. This patch ensures that there are no duplicates in VALID_RULE_TYPES. [1] https://review.opendev.org/c/openstack/requirements/+/805352 Change-Id: Ib6963f402c9fec8169afcf467d613bba4e06130d
# # 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 neutron_lib.services.qos import constants as qos_consts # TODO(liuyulong): Because of the development sequence, the rule must # be implemented in Neutron first. Then the following can be moved # to neutron-lib after neutron has the new rule. # Add qos rule packet rate limit RULE_TYPE_PACKET_RATE_LIMIT = 'packet_rate_limit' # NOTE(przszc): Ensure that there are no duplicates in the list. Order of the # items in the list must be stable, as QosRuleType OVO hash value depends on # it. # TODO(przszc): When a rule type is moved to neutron-lib, it can be removed # from the list below. VALID_RULE_TYPES = (qos_consts.VALID_RULE_TYPES + ([RULE_TYPE_PACKET_RATE_LIMIT] if RULE_TYPE_PACKET_RATE_LIMIT not in qos_consts.VALID_RULE_TYPES else []) )
# # 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 neutron_lib.services.qos import constants as qos_consts # TODO(liuyulong): Because of the development sequence, the rule must # be implemented in Neutron first. Then the following can be moved # to neutron-lib after neutron has the new rule. # Add qos rule packet rate limit RULE_TYPE_PACKET_RATE_LIMIT = 'packet_rate_limit' VALID_RULE_TYPES = qos_consts.VALID_RULE_TYPES + [RULE_TYPE_PACKET_RATE_LIMIT]
Mark package as Python 3.6-compatible.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-envelope', version=__import__('envelope').__version__, description='A contact form app for Django', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='http://github.com/zsiciarz/django-envelope', download_url='http://pypi.python.org/pypi/django-envelope', license='MIT', install_requires=['Django>=1.8'], packages=find_packages(exclude=['example_project', 'tests']), include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', ], )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-envelope', version=__import__('envelope').__version__, description='A contact form app for Django', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='zbigniew@siciarz.net', url='http://github.com/zsiciarz/django-envelope', download_url='http://pypi.python.org/pypi/django-envelope', license='MIT', install_requires=['Django>=1.8'], packages=find_packages(exclude=['example_project', 'tests']), include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], )
Remove reference to removed view
package org.vaadin.alump.searchdropdown.demo; import javax.servlet.annotation.WebServlet; import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.navigator.Navigator; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.ui.*; @Theme("demo") @Title("SearchDropDown Add-on Demo") @Push @SuppressWarnings("serial") public class DemoUI extends UI { @WebServlet(value = "/*", asyncSupported = true) @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.alump.searchdropdown.demo.WidgetSet") public static class Servlet extends VaadinServlet { } @Override protected void init(VaadinRequest request) { Navigator navigator = new Navigator(this, this); navigator.addView(MenuView.VIEW_NAME, MenuView.class); navigator.addView(TestView.VIEW_NAME, TestView.class); navigator.addView(ExampleView.VIEW_NAME, ExampleView.class); navigator.addView(SimpleView.VIEW_NAME, SimpleView.class); navigator.setErrorView(MenuView.class); setNavigator(navigator); } }
package org.vaadin.alump.searchdropdown.demo; import javax.servlet.annotation.WebServlet; import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.navigator.Navigator; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.ui.*; @Theme("demo") @Title("SearchDropDown Add-on Demo") @Push @SuppressWarnings("serial") public class DemoUI extends UI { @WebServlet(value = "/*", asyncSupported = true) @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.alump.searchdropdown.demo.WidgetSet") public static class Servlet extends VaadinServlet { } @Override protected void init(VaadinRequest request) { Navigator navigator = new Navigator(this, this); navigator.addView(MenuView.VIEW_NAME, MenuView.class); navigator.addView(TestView.VIEW_NAME, TestView.class); navigator.addView(ExampleView.VIEW_NAME, ExampleView.class); navigator.addView(JustTesting.VIEW_NAME, JustTesting.class); navigator.addView(SimpleView.VIEW_NAME, SimpleView.class); navigator.setErrorView(MenuView.class); setNavigator(navigator); } }
Disable SSL/HTTPS (reverts to default values) Needing to explicitly set something to it’s default value perhaps isn’t ideal.
import os from service.settings.production import * DEBUG = { 0: False, 1: True }[int(os.getenv('DEBUG'))] # SSL/HTTPS Security ## Set SECURE_SSL_REDIRECT to True, so that requests over HTTP are redirected to HTTPS. SECURE_PROXY_SSL_HEADER = None SECURE_SSL_REDIRECT = False ## Use ‘secure’ cookies. SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False ## Use HTTP Strict Transport Security (HSTS) SECURE_HSTS_SECONDS = 0 SECURE_HSTS_INCLUDE_SUBDOMAINS = False if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] INTERNAL_IPS = ( '127.0.0.1', # Docker IPs # '172.20.0.1', # '172.20.0.5', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': 'service.settings.local.show_toolbar', } def is_running_in_docker(*args): import subprocess return 'docker' in subprocess.getoutput('cat /proc/1/cgroup') def show_toolbar(request): if request.is_ajax(): return False return True
import os from service.settings.production import * DEBUG = { 0: False, 1: True }[int(os.getenv('DEBUG'))] if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] INTERNAL_IPS = ( '127.0.0.1', # Docker IPs # '172.20.0.1', # '172.20.0.5', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': 'service.settings.local.show_toolbar', } def is_running_in_docker(*args): import subprocess return 'docker' in subprocess.getoutput('cat /proc/1/cgroup') def show_toolbar(request): if request.is_ajax(): return False return True
Fix proto lang handler to work minified and to use the type style for types like uint32.
// Copyright (C) 2006 Google Inc. // // 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. /** * @fileoverview * Registers a language handler for Protocol Buffers as described at * http://code.google.com/p/protobuf/. * * Based on the lexical grammar at * http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715 * * @author mikesamuel@gmail.com */ PR['registerLangHandler'](PR['sourceDecorator']({ 'keywords': ( 'bytes,default,double,enum,extend,extensions,false,' + 'group,import,max,message,option,' + 'optional,package,repeated,required,returns,rpc,service,' + 'syntax,to,true'), 'types': /^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/, 'cStyleComments': true }), ['proto']);
// Copyright (C) 2006 Google Inc. // // 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. /** * @fileoverview * Registers a language handler for Protocol Buffers as described at * http://code.google.com/p/protobuf/. * * Based on the lexical grammar at * http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715 * * @author mikesamuel@gmail.com */ PR['registerLangHandler'](PR['sourceDecorator']({ keywords: ( 'bool bytes default double enum extend extensions false fixed32 ' + 'fixed64 float group import int32 int64 max message option ' + 'optional package repeated required returns rpc service ' + 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 ' + 'uint64'), cStyleComments: true }), ['proto']);
Make timestamps relative to start time
#!/usr/bin/env node const fs = require( 'fs' ); const path = require( 'path' ); const readline = require( 'readline' ); const eol = require( 'os' ).EOL; if ( process.argv.length !== 3 ) printUsageAndExit(); const FILENAME = `${process.argv[2]}.txt`; const FILEPATH = path.resolve( process.cwd(), './', FILENAME ); const timestamp = function() { let seconds = process.hrtime(time)[0]; return calculateTimestamp(seconds); } const calculateTimestamp = function(seconds) { const minutes = Math.floor(seconds / 60).toString(); let remainingSeconds = (seconds % 60).toString(); let formatedSeconds = remainingSeconds.length === 1 ? remainingSeconds + '0' : remainingSeconds; return `${minutes}:${formatedSeconds}`; } const rli = readline.createInterface({ input: process.stdin, output: fs.createWriteStream( FILEPATH, { flags: 'a' } ) }); let time = process.hrtime(); rli.on( 'line', function ( line ) { rli.output.write( timestamp() + ' - ' + String( line ) + eol ); process.stdout.write( '> ' ); }); process.on( 'SIGINT', function() { rli.output.write( eol ); process.stdout.write( eol + 'Note saved!' + eol ); process.exit( 0 ); }); process.stdout.write( '> ' ); rli.output.write( timestamp() + eol ); function printUsageAndExit () { console.log('Usage: timestamp <filename>'); process.exit(1); }
#!/usr/bin/env node const fs = require( 'fs' ); const path = require( 'path' ); const readline = require( 'readline' ); const eol = require( 'os' ).EOL; const moment = require( 'moment' ); const now = moment(); if ( process.argv.length !== 3 ) printUsageAndExit(); const FILENAME = `${process.argv[2]}.txt`; const FILEPATH = path.resolve( process.cwd(), './', FILENAME ); const timestamp = function() { return moment().format( 'hh:mm:ss A' ); } const rli = readline.createInterface({ input: process.stdin, output: fs.createWriteStream( FILEPATH, { flags: 'a' } ) }); rli.on( 'line', function ( line ) { rli.output.write( timestamp() + ' > ' + String( line ) + eol ); process.stdout.write( '> ' ); }); process.on( 'SIGINT', function() { rli.output.write( eol ); process.stdout.write( eol + 'Note saved!' + eol ); process.exit( 0 ); }); process.stdout.write( '> ' ); rli.output.write( timestamp() + eol ); function printUsageAndExit () { console.log('Usage: timestamp <filename>'); process.exit(1); }
Set HomePage to use preact layout
import { h } from 'preact' /** @jsx h */ import { connect } from 'preact-redux' import ButtonPrimary from '../components/ButtonPrimary' import * as MenuActions from '../../menu/redux/action-creators' import { Header, MyLayout } from '../tags/layout' const Home = ({ setMenuActive }) => ( <div className="page page__home"> <div className="card splash"> <button className="menu" onClick={() => setMenuActive(true)}> <img src="/img/icone_menu.png" alt="hamburguer menu" /> </button> <h1><img src="/img/logo-vivos-em-nos.png" alt="logo vivos em nos" /></h1> <p> Vamos usar a memória como ferramenta para mudança. Homenageando aqueles que estão #VivosEmNós, podemos transformar saudade em mobilização e, juntos, lutar por mais respeito à vida. </p> <ButtonPrimary text="crie sua homenagem" href="/homenagem" /> </div> </div> ) const HomePage = ({ setMenuActive }) => { return ( <MyLayout> <Home setMenuActive={ setMenuActive } /> </MyLayout> ) } const mapDispatchToProps = { setMenuActive: MenuActions.setActive } export default connect(undefined, mapDispatchToProps)(HomePage)
import { h } from 'preact' /** @jsx h */ import { connect } from 'preact-redux' import ButtonPrimary from '../components/ButtonPrimary' import * as MenuActions from '../../menu/redux/action-creators' const Home = ({ setMenuActive }) => ( <div className="page page__home"> <div className="card splash"> <button className="menu" onClick={() => setMenuActive(true)}> <img src="/img/icone_menu.png" alt="hamburguer menu" /> </button> <h1><img src="/img/logo-vivos-em-nos.png" alt="logo vivos em nos" /></h1> <p> Vamos usar a memória como ferramenta para mudança. Homenageando aqueles que estão #VivosEmNós, podemos transformar saudade em mobilização e, juntos, lutar por mais respeito à vida. </p> <ButtonPrimary text="crie sua homenagem" href="/homenagem" /> </div> </div> ) const mapDispatchToProps = { setMenuActive: MenuActions.setActive } export default connect(undefined, mapDispatchToProps)(Home)
Make usertagging in comments case insensitive
<?php namespace App\Http\Controllers\Api; use App\LaraBin\Helpers\UserCache; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct(UserCache $userCache) { $this->userCache = $userCache; } public function search(Request $request) { $query = $request->input('q'); $users = $this->userCache->usernames(); $found = array_filter($users, function($users) use ($query) { return ( stripos($users, $query) !== false ); }); $usernames = array_values($found); return response()->json($usernames, 200); } }
<?php namespace App\Http\Controllers\Api; use App\LaraBin\Helpers\UserCache; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct(UserCache $userCache) { $this->userCache = $userCache; } public function search(Request $request) { $query = $request->input('q'); $users = $this->userCache->usernames(); $found = array_filter($users, function($users) use ($query) { return ( strpos($users, $query) !== false ); }); $usernames = array_values($found); return response()->json($usernames, 200); } }
Add dbconnection to env support.
package main import ( "flag" "fmt" "github.com/BurntSushi/toml" log "github.com/Sirupsen/logrus" "os" ) func StartServer(config *SiteConfig) { gb := NewGoblin(config) err := gb.Init() if err != nil { log.Errorf("Goblin init fail. %s", err) return } gb.StartServer() } func main() { configPtr := flag.String("c", "config.toml", "Config file path.") flag.Parse() if len(*configPtr) < 1 { log.Error("Config file path must set.Use -h to get some help.") } var config SiteConfig if _, err := toml.DecodeFile(*configPtr, &config); err != nil { fmt.Println(err) return } dbUrl := os.Getenv("DATABASE_URL") if dbUrl != "" { config.DBConnection = dbUrl } fmt.Printf("%#v \n", config) StartServer(&config) }
package main import ( "flag" "fmt" "github.com/BurntSushi/toml" log "github.com/Sirupsen/logrus" ) func StartServer(config *SiteConfig) { gb := NewGoblin(config) err := gb.Init() if err != nil { log.Errorf("Goblin init fail. %s", err) return } gb.StartServer() } func main() { configPtr := flag.String("c", "config.toml", "Config file path.") flag.Parse() if len(*configPtr) < 1 { log.Error("Config file path must set.Use -h to get some help.") } var config SiteConfig if _, err := toml.DecodeFile(*configPtr, &config); err != nil { fmt.Println(err) return } fmt.Printf("%#v \n", config) StartServer(&config) }
Allow access to vagrant webserver
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup // for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '10.0.2.2', 'fe80::1', '::1']) || php_sapi_name() === 'cli-server') ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } /** * @var Composer\Autoload\ClassLoader $loader */ $loader = require __DIR__.'/../app/autoload.php'; Debug::enable(); $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup // for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', 'fe80::1', '::1']) || php_sapi_name() === 'cli-server') ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } /** * @var Composer\Autoload\ClassLoader $loader */ $loader = require __DIR__.'/../app/autoload.php'; Debug::enable(); $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Make some routes depend on loggedinness
<?php namespace Koseu\Core; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use \Tsugi\Core\LTIX; class Application extends \Tsugi\Silex\Application { public function __construct($launch) { // $app = new \Tsugi\Silex\Application($launch); parent::__construct($launch); $this['tsugi']->output->buffer = false; // Hook up the Koseu and Tsugi tools \Tsugi\Controllers\Login::routes($this); \Tsugi\Controllers\Logout::routes($this); \Koseu\Controllers\Lessons::routes($this); // Tools that require logged in user if ( isset($launch->user->id) ) { \Tsugi\Controllers\Profile::routes($this); \Tsugi\Controllers\Map::routes($this); \Koseu\Controllers\Badges::routes($this); \Koseu\Controllers\Assignments::routes($this); \Koseu\Controllers\Courses::routes($this); } } }
<?php namespace Koseu\Core; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use \Tsugi\Core\LTIX; class Application extends \Tsugi\Silex\Application { public function __construct($launch) { // $app = new \Tsugi\Silex\Application($launch); parent::__construct($launch); $this['tsugi']->output->buffer = false; // Hook up the Koseu and Tsugi tools \Tsugi\Controllers\Login::routes($this); \Tsugi\Controllers\Logout::routes($this); \Tsugi\Controllers\Profile::routes($this); \Tsugi\Controllers\Map::routes($this); \Koseu\Controllers\Badges::routes($this); \Koseu\Controllers\Assignments::routes($this); \Koseu\Controllers\Lessons::routes($this); \Koseu\Controllers\Courses::routes($this); } }
openid: Fix notice about unititialized variable.
<?php /* Find the authentication state. */ if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) { throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState'); } $authState = $_REQUEST['AuthState']; $state = SimpleSAML_Auth_State::loadState($authState, 'openid:init'); $sourceId = $state['openid:AuthId']; $authSource = SimpleSAML_Auth_Source::getById($sourceId); if ($authSource === NULL) { throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.'); } $error = NULL; try { if (!empty($_GET['openid_url'])) { $authSource->doAuth($state, (string)$_GET['openid_url']); } } catch (Exception $e) { $error = $e->getMessage(); } $config = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid'); $t->data['error'] = $error; $t->data['AuthState'] = $authState; $t->show();
<?php /* Find the authentication state. */ if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) { throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState'); } $authState = $_REQUEST['AuthState']; $state = SimpleSAML_Auth_State::loadState($authState, 'openid:init'); $sourceId = $state['openid:AuthId']; $authSource = SimpleSAML_Auth_Source::getById($sourceId); if ($authSource === NULL) { throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.'); } try { if (!empty($_GET['openid_url'])) { $authSource->doAuth($state, (string)$_GET['openid_url']); } } catch (Exception $e) { $error = $e->getMessage(); } $config = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid'); $t->data['error'] = $error; $t->data['AuthState'] = $authState; $t->show();
Revert "Another attempt to fix the RTD build." This reverts commit 43807c085493962ca0f79105b64b3be8ddc6fc39.
from setuptools import setup, find_packages from os.path import dirname, abspath HERE = abspath(dirname(__file__)) VERSION = open(HERE + '/puresnmp/version.txt').read().strip() setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open(HERE + "/README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
from setuptools import setup, find_packages VERSION = '1.1.4' setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open("README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
Add context to decoded messages
package io.elssa.net; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; public class MessageDecoder extends ReplayingDecoder<DecoderState> { private int length; public MessageDecoder() { super(DecoderState.READ_LENGTH); } @Override protected void decode( ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { switch (state()) { case READ_LENGTH: length = buf.readInt(); checkpoint(DecoderState.READ_CONTENT); /* Fall through to the next state; the entire message may be * available */ case READ_CONTENT: ByteBuf frame = buf.readBytes(length); checkpoint(DecoderState.READ_LENGTH); byte[] payload = new byte[frame.readableBytes()]; frame.readBytes(payload); MessageContext context = new MessageContext(ctx); ElssaMessage msg = new ElssaMessage(payload, context); out.add(msg); break; default: throw new Error("Unknown decoder state"); } } }
package io.elssa.net; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; public class MessageDecoder extends ReplayingDecoder<DecoderState> { private int length; public MessageDecoder() { super(DecoderState.READ_LENGTH); } @Override protected void decode( ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { switch (state()) { case READ_LENGTH: length = buf.readInt(); checkpoint(DecoderState.READ_CONTENT); /* Fall through to the next state; the entire message may be * available */ case READ_CONTENT: ByteBuf frame = buf.readBytes(length); checkpoint(DecoderState.READ_LENGTH); byte[] payload = new byte[frame.readableBytes()]; frame.readBytes(payload); ElssaMessage msg = new ElssaMessage(payload); out.add(msg); break; default: throw new Error("Unknown decoder state"); } } }
Rename extension to .so so python can import
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copyfile( SO_PATH, os.path.join(PIP_DIR, 'storehouse', 'libstorehouse.so')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*.so', ] }, license='Apache 2.0' )
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copy(SO_PATH, os.path.join(PIP_DIR, 'storehouse')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*' + EXT, ] }, license='Apache 2.0' )
Add auto-generated class UID to ICA filter
package students.filters; import weka.core.Attribute; import weka.core.Instances; import weka.core.RevisionUtils; import weka.filters.SimpleBatchFilter; public class IndependentComponetFilter extends SimpleBatchFilter { /** for serialization. */ private static final long serialVersionUID = -5416810876710954131L; @Override public String globalInfo() { return "Performs Independent Component Analysis and transformation " + "of the data using the FastICA algorithm ignoring the class " + "label."; } @Override protected Instances determineOutputFormat(Instances inputFormat) throws Exception { return new Instances(inputFormat, 0); } @Override protected Instances process(Instances instances) throws Exception { // Test that there is no missing data and only contains numeric attributes // TODO: needs args for max_iter, tolerance // Convert instances to matrix ignoring class labels // Process the data through FastICA // Convert results back to Instances return null; } public String getRevision() { return RevisionUtils.extract("$Revision: 1.0 $"); } }
package students.filters; import weka.core.Attribute; import weka.core.Instances; import weka.core.RevisionUtils; import weka.filters.SimpleBatchFilter; public class IndependentComponetFilter extends SimpleBatchFilter { static final long serialVersionUID = 0; @Override public String globalInfo() { return "Performs Independent Component Analysis and transformation " + "of the data using the FastICA algorithm ignoring the class " + "label."; } @Override protected Instances determineOutputFormat(Instances inputFormat) throws Exception { return new Instances(inputFormat, 0); } @Override protected Instances process(Instances instances) throws Exception { // Test that there is no missing data and only contains numeric attributes // TODO: needs args for max_iter, tolerance // Convert instances to matrix ignoring class labels // Process the data through FastICA // Convert results back to Instances return null; } public String getRevision() { return RevisionUtils.extract("$Revision: 1.0 $"); } }
Make ChannelLevel actually a valid module
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ChannelLevel(ModuleData): implements(IPlugin, IModuleData) name = "ChannelLevel" core = True def actions(self): return [ ("checkchannellevel", 1, self.levelCheck), ("checkexemptchanops", 1, self.exemptCheck) ] def minLevelFromConfig(self, configKey, checkType, defaultLevel): configLevel = self.ircd.config.get(configKey, {}).get(checkType, defaultLevel) try: minLevel = int(configLevel) except ValueError: if configLevel not in self.ircd.channelStatuses: return False # If the status doesn't exist, then, to be safe, we must assume NOBODY is above the line. minLevel = self.ircd.channelStatuses[configLevel][1] return minLevel def levelCheck(self, levelType, channel, user): minLevel = self.minLevelFromConfig("channel_minimum_level", levelType, 100) return channel.userRank(user) >= minLevel def exemptCheck(self, exemptType, channel, user): minLevel = self.minLevelFromConfig("channel_exempt_level", exemptType, 0) if not minLevel: return False # No minimum level == no exemptions return channel.userRank(user) >= minLevel chanLevel = ChannelLevel()
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ChannelLevel(ModuleData): implements(IModuleData) name = "ChannelLevel" core = True def actions(self): return [ ("checkchannellevel", 1, self.levelCheck), ("checkexemptchanops", 1, self.exemptCheck) ] def minLevelFromConfig(self, configKey, checkType, defaultLevel): configLevel = self.ircd.config.get(configKey, {}).get(checkType, defaultLevel) try: minLevel = int(configLevel) except ValueError: if configLevel not in self.ircd.channelStatuses: return False # If the status doesn't exist, then, to be safe, we must assume NOBODY is above the line. minLevel = self.ircd.channelStatuses[configLevel][1] return minLevel def levelCheck(self, levelType, channel, user): minLevel = self.minLevelFromConfig("channel_minimum_level", levelType, 100) return channel.userRank(user) >= minLevel def exemptCheck(self, exemptType, channel, user): minLevel = self.minLevelFromConfig("channel_exempt_level", exemptType, 0) if not minLevel: return False # No minimum level == no exemptions return channel.userRank(user) >= minLevel chanLevel = ChannelLevel()
Fix reducer for removing category threshold
import _ from 'lodash'; import { ADD_CATEGORY_THRESHOLD, REMOVE_CATEGORY_THRESHOLD, SET_GLOBAL_THRESHOLD, RESET_ADD_THRESHOLD_FORM, } from '../constants/ActionTypes'; const initialState = { value: 0, date: null, categories: [], }; export default (state = initialState, action) => { switch (action.type) { case ADD_CATEGORY_THRESHOLD: return { ...state, categories: [ ...state.categories, { categoryId: action.categoryId, value: action.value, } ], }; case REMOVE_CATEGORY_THRESHOLD: const filteredCategories = _.filter(state.categories, (c) => c.categoryId !== action.categoryId); return { ...state, categories: filteredCategories, }; case SET_GLOBAL_THRESHOLD: return { ...state, value: action.value }; case RESET_ADD_THRESHOLD_FORM: return { ...initialState }; default: return state; } };
import _ from 'lodash'; import { ADD_CATEGORY_THRESHOLD, REMOVE_CATEGORY_THRESHOLD, SET_GLOBAL_THRESHOLD, RESET_ADD_THRESHOLD_FORM, } from '../constants/ActionTypes'; const initialState = { value: 0, date: null, categories: [], }; export default (state = initialState, action) => { switch (action.type) { case ADD_CATEGORY_THRESHOLD: return { ...state, categories: [ ...state.categories, { categoryId: action.categoryId, value: action.value, } ], }; case REMOVE_CATEGORY_THRESHOLD: const filteredCategories = _.filter(state.categories, (c) => c.id !== action.categoryId); return { ...state, categories: filteredCategories, }; case SET_GLOBAL_THRESHOLD: return { ...state, value: action.value }; case RESET_ADD_THRESHOLD_FORM: return { ...initialState }; default: return state; } };
Increase polling freqency to speed up tests.
# Copyright 2018 Nathan Sommer and Ben Coleman # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import time polling_count = 250 def polling(func): def polling_wrapper(*args, **kwargs): for count in range(polling_count): if func(*args, **kwargs): return True time.sleep(.01) return False return polling_wrapper
# Copyright 2018 Nathan Sommer and Ben Coleman # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import time polling_count = 25 def polling(func): def polling_wrapper(*args, **kwargs): for count in range(polling_count): if func(*args, **kwargs): return True time.sleep(.1) return False return polling_wrapper
Handle number format exception: building port
package fortiss.gui.listeners.textfield; import fortiss.gui.DesignerPanel; import fortiss.gui.listeners.helper.InsertionVerifier; import fortiss.simulation.helper.Logger; public class BPortListener extends TextFieldListener { public BPortListener() { super("Error. Invalid port number. Only numbers between 1024 and 49151, and 0 are valid."); } @Override boolean isValidField(String text) { boolean valid = false; if (!text.isEmpty()) { try { int num = Integer.parseUnsignedInt(text); if (num == 0 || (num > 1024 && num < 49151)) valid = true; } catch (NumberFormatException e) { Logger.getInstance().writeError("Number format exception. Expected an integer and received " + text); } } return valid; } @Override boolean isValidCharacter(char c, String text) { InsertionVerifier v = new InsertionVerifier(); return v.isNumber(c, text); } @Override void update(String text) { try { building.setPort(Integer.parseUnsignedInt(text)); } catch (NumberFormatException e) { Logger.getInstance().writeError("Number format exception. Expected an integer and received " + text); DesignerPanel.pl_ems_detail.update(); } } @Override boolean isValidLength(String text) { return text.length() < 5; } @Override String getAttribute() { return String.valueOf(building.getPort()); } }
package fortiss.gui.listeners.textfield; import fortiss.gui.listeners.helper.InsertionVerifier; public class BPortListener extends TextFieldListener { public BPortListener() { super("Error. Invalid port number. Only numbers between 1024 and 49151, and 0 are valid."); } @Override boolean isValidField(String text) { boolean valid = false; if (!text.isEmpty()) { int num = Integer.parseUnsignedInt(text); if (num == 0 || (num > 1024 && num < 49151)) valid = true; } return valid; } @Override boolean isValidCharacter(char c, String text) { InsertionVerifier v = new InsertionVerifier(); return v.isNumber(c, text); } @Override void update(String text) { building.setPort(Integer.parseUnsignedInt(text)); } @Override boolean isValidLength(String text) { return text.length() < 5; } @Override String getAttribute() { return String.valueOf(building.getPort()); } }
Fix the bad packets! Naughty naughty packets!
package net.md_5.bungee.protocol.packet; import io.netty.buffer.ByteBuf; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; @Getter @ToString @EqualsAndHashCode(callSuper = false) public class PacketCFScoreboardScore extends DefinedPacket { private String itemName; /** * 0 = create / update, 1 = remove. */ private byte action; private String scoreName; private int value; private PacketCFScoreboardScore() { super( 0xCF ); } @Override public void read(ByteBuf buf) { itemName = readString( buf ); action = buf.readByte(); if ( action != 1 ) { scoreName = readString( buf ); value = buf.readInt(); } } @Override public void write(ByteBuf buf) { writeString( itemName, buf ); buf.writeByte( action ); if ( action != 1 ) { writeString( scoreName, buf ); buf.writeInt( value ); } } @Override public void handle(AbstractPacketHandler handler) throws Exception { handler.handle( this ); } }
package net.md_5.bungee.protocol.packet; import io.netty.buffer.ByteBuf; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; @Getter @ToString @EqualsAndHashCode(callSuper = false) public class PacketCFScoreboardScore extends DefinedPacket { private String itemName; /** * 0 = create / update, 1 = remove. */ private byte action; private String scoreName; private int value; private PacketCFScoreboardScore() { super( 0xCF ); } @Override public void read(ByteBuf buf) { itemName = readString( buf ); action = buf.readByte(); if ( action == 0 ) { scoreName = readString( buf ); value = buf.readInt(); } } @Override public void write(ByteBuf buf) { writeString( itemName, buf ); buf.writeByte( action ); if ( action == 0 ) { writeString( scoreName, buf ); buf.writeInt( value ); } } @Override public void handle(AbstractPacketHandler handler) throws Exception { handler.handle( this ); } }
Adjust the module __version__ to match the version advertised in PyPI.
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.5" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.1" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
Reduce concurrency level to 3 for accomodating acient thinkpad
let dotAnsel = `${process.env.HOME}/.ansel`; if (process.env.ANSEL_DEV_MODE) dotAnsel = `${process.env.INIT_CWD}/dot-ansel`; export default { characters: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZéè', acceptedRawFormats: [ 'raf', 'cr2', 'arw', 'dng' ], acceptedImgFormats: [ 'png', 'jpg', 'jpeg', 'tif', 'tiff' ], watchedFormats: /([\$\#\w\d]+)-([\$\#\w\dèé]+)-(\d+)\.(JPEG|JPG|PNG|PPM)/i, dotAnsel, dbFile: `${dotAnsel}/db.sqlite3`, settings: `${dotAnsel}/settings.json`, thumbsPath: `${dotAnsel}/thumbs`, thumbs250Path: `${dotAnsel}/thumbs-250`, tmp: '/tmp/ansel', concurrency: 3 };
let dotAnsel = `${process.env.HOME}/.ansel`; if (process.env.ANSEL_DEV_MODE) dotAnsel = `${process.env.INIT_CWD}/dot-ansel`; export default { characters: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZéè', acceptedRawFormats: [ 'raf', 'cr2', 'arw', 'dng' ], acceptedImgFormats: [ 'png', 'jpg', 'jpeg', 'tif', 'tiff' ], watchedFormats: /([\$\#\w\d]+)-([\$\#\w\dèé]+)-(\d+)\.(JPEG|JPG|PNG|PPM)/i, dotAnsel, dbFile: `${dotAnsel}/db.sqlite3`, settings: `${dotAnsel}/settings.json`, thumbsPath: `${dotAnsel}/thumbs`, thumbs250Path: `${dotAnsel}/thumbs-250`, tmp: '/tmp/ansel', concurrency: 5 };
Use token() instead of getToken() since it is "deprecated"
<?php namespace Contentify\ServiceProviders; use Collective\Html\HtmlServiceProvider as OriginalHtmlServiceProvider; use Contentify\HtmlBuilder; use Contentify\FormBuilder; class HtmlServiceProvider extends OriginalHtmlServiceProvider { /** * Register the HTML builder instance. * * @return void */ protected function registerHtmlBuilder() { $this->app->singleton('html', function($app) { return new HtmlBuilder($app['url'], $app['view']); }); } /** * Register the form builder instance. * * @return void */ protected function registerFormBuilder() { $this->app->singleton('form', function($app) { $form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->token()); return $form->setSessionStore($app['session.store']); }); } }
<?php namespace Contentify\ServiceProviders; use Collective\Html\HtmlServiceProvider as OriginalHtmlServiceProvider; use Contentify\HtmlBuilder; use Contentify\FormBuilder; class HtmlServiceProvider extends OriginalHtmlServiceProvider { /** * Register the HTML builder instance. * * @return void */ protected function registerHtmlBuilder() { $this->app->singleton('html', function($app) { return new HtmlBuilder($app['url'], $app['view']); }); } /** * Register the form builder instance. * * @return void */ protected function registerFormBuilder() { $this->app->singleton('form', function($app) { $form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->getToken()); return $form->setSessionStore($app['session.store']); }); } }
Disable SSR for speed testing
const path = require('path') module.exports = { http: { port: process.env.DEV ? 8080 : 8050, favicon: path.join(__dirname, '../assets/favicon.ico') }, server: { SSR: false, // Server side rendering certificate: path.join(__dirname, '../../fullchain.pem'), certificate_key: path.join(__dirname, '../../privkey.pem'), }, static: [ { url: '/build', path: path.join(__dirname, '../../build') }, { url: '/assets', path: path.join(__dirname, '../assets') }, { url: '/static', path: path.join(__dirname, '../docs') } ] }
const path = require('path') module.exports = { http: { port: process.env.DEV ? 8080 : 8050, favicon: path.join(__dirname, '../assets/favicon.ico') }, server: { SSR: true, // Server side rendering certificate: path.join(__dirname, '../../fullchain.pem'), certificate_key: path.join(__dirname, '../../privkey.pem'), }, static: [ { url: '/build', path: path.join(__dirname, '../../build') }, { url: '/assets', path: path.join(__dirname, '../assets') }, { url: '/static', path: path.join(__dirname, '../docs') } ] }
client: Improve background contrast for current song titles.
import React from 'react'; import { Card, CardHeader, CardMedia, CardTitle } from 'material-ui/Card'; const overlayContentStyle = { background: 'rgba(0, 0, 0, 0.75)', }; const ServerThumbnail = ({ server, media }) => ( <Card className="thumb"> <a href={server.url}> <CardHeader title={server.name} subtitle={server.description} /> {media && ( <CardMedia overlay={( <CardTitle title={media.title} subtitle={media.artist} /> )} overlayContentStyle={overlayContentStyle} > <img src={media.media.thumbnail} /> </CardMedia> )} </a> <style jsx>{` .thumb { width: 360px; margin: 0 20px 20px 20px; } `}</style> </Card> ); export default ServerThumbnail;
import React from 'react'; import { Card, CardHeader, CardMedia, CardTitle } from 'material-ui/Card'; const ServerThumbnail = ({ server, media }) => ( <Card className="thumb"> <a href={server.url}> <CardHeader title={server.name} subtitle={server.description} /> {media && ( <CardMedia overlay={( <CardTitle title={media.title} subtitle={media.artist} /> )} > <img src={media.media.thumbnail} /> </CardMedia> )} </a> <style jsx>{` .thumb { width: 360px; margin: 0 20px 20px 20px; } `}</style> </Card> ); export default ServerThumbnail;
Fix place of "tags" option in the default options
$(document).ready(function () { $.fn.select24entity = function (action) { // Create the parameters array with basic values var select24entityParam = { ajax: { data: function (params) { return { q: params.term }; }, processResults: function (data) { return { results: data }; }, cache: true }, tags: false }; // Extend the parameters array with the one in arguments $.extend(select24entityParam, action); // Activate the select2 field this.select2(select24entityParam); // If we have tag support activated, add a listener to add "new_" in front of new entries. if (select24entityParam.tags === true) { this.on('select2:selecting', function (e) { if (e.params.args.data.id === e.params.args.data.text) { e.params.args.data.id = 'new_' + e.params.args.data.id; } }); } // Return current field return this; }; });
$(document).ready(function () { $.fn.select24entity = function (action) { // Create the parameters array with basic values var select24entityParam = { ajax: { data: function (params) { return { q: params.term }; }, processResults: function (data) { return { results: data }; }, cache: true, tags: false } }; // Extend the parameters array with the one in arguments $.extend(select24entityParam, action); // Activate the select2 field this.select2(select24entityParam); // If we have tag support activated, add a listener to add "new_" in front of new entries. if (select24entityParam.tags === true) { this.on('select2:selecting', function (e) { if (e.params.args.data.id === e.params.args.data.text) { e.params.args.data.id = 'new_' + e.params.args.data.id; } }); } // Return current field return this; }; });
Fix for assertIs method not being present in Python 2.6.
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
Refactor code using ES6 syntax
import gulp from 'gulp'; import babel from 'gulp-babel'; import nodemon from 'gulp-nodemon'; import mocha from 'gulp-mocha'; import istanbul from 'gulp-babel-istanbul'; import injectModules from 'gulp-inject-modules'; gulp.task('start', () => { nodemon({ script: 'index.js', env: { NODE_ENV: 'development' } }); }); gulp.task('coverage', (cb) => { gulp.src('src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', () => { gulp.src('test/**/*.js') .pipe(babel()) .pipe(injectModules()) .pipe(mocha()) .pipe(istanbul.writeReports()) .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } })) .on('end', cb); }); });
import gulp from 'gulp'; import babel from 'gulp-babel'; import nodemon from 'gulp-nodemon'; import mocha from 'gulp-mocha'; import istanbul from 'gulp-babel-istanbul'; import injectModules from 'gulp-inject-modules'; gulp.task('start', () => { nodemon({ script: 'index.js', env: { NODE_ENV: 'development' } }); }); gulp.task('coverage', function (cb) { gulp.src('src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', () => { gulp.src('test/**/*.js') .pipe(babel()) .pipe(injectModules()) .pipe(mocha()) .pipe(istanbul.writeReports()) .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } })) .on('end'); }); });
Fix up deprecated lazy import
# Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # 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. """ The deprecated lazy command objects """ import warnings from libqtile.command_client import InteractiveCommandClient from libqtile.lazy import LazyCommandInterface class _LazyTree(InteractiveCommandClient): def __getattr__(self, name: str) -> InteractiveCommandClient: """Get the child element of the currently selected object""" warnings.warn("libqtile.command.lazy is deprecated, use libqtile.lazy.lazy", DeprecationWarning) return super().__getattr__(name) lazy = _LazyTree(LazyCommandInterface())
# Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # 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. """ The deprecated lazy command objects """ import warnings from libqtile.command_client import InteractiveCommandClient from libqtile.lazy import LazyCommandObject class _LazyTree(InteractiveCommandClient): def __getattr__(self, name: str) -> InteractiveCommandClient: """Get the child element of the currently selected object""" warnings.warn("libqtile.command.lazy is deprecated, use libqtile.lazy.lazy", DeprecationWarning) return super().__getattr__(name) lazy = _LazyTree(LazyCommandObject())
Hide test classes for AnonFunc from spec
from tryp import __ from tryp.test import Spec # type: ignore class _Inner: def __init__(self, z) -> None: self.z = z @property def wrap(self): return _Inner(self.z * 2) def add(self, a, b): return self.z + a + b class _Outer: def inner(self, z): return _Inner(z) class AnonSpec(Spec): def nested(self): z = 5 a = 3 b = 4 o = _Outer() f = __.inner(z).wrap.add(a, b) f(o).should.equal(2 * z + a + b) __all__ = ('AnonSpec',)
from tryp import __ from tryp.test import Spec # type: ignore class Inner: def __init__(self, z) -> None: self.z = z @property def wrap(self): return Inner(self.z * 2) def add(self, a, b): return self.z + a + b class Outer: def inner(self, z): return Inner(z) class AnonSpec(Spec): def nested(self): z = 5 a = 3 b = 4 o = Outer() f = __.inner(z).wrap.add(a, b) f(o).should.equal(2 * z + a + b) __all__ = ('AnonSpec',)
Refactor to use new model
const AssignedSchedule = require('../../structs/db/AssignedSchedule.js') const ArticleModel = require('../../models/Article.js') const log = require('../../util/logger.js') exports.normal = async (bot, message) => { try { const args = message.content.split(' ') const feedID = args[1] if (!feedID) { return await message.channel.send('No feed ID argument') } const assigned = await AssignedSchedule.getByFeedAndShard(feedID, -1) if (!assigned) { return await message.channel.send('No assigned schedule') } const link = assigned.link const shardID = assigned.shard const scheduleName = assigned.schedule await message.channel.send(ArticleModel.getCollectionID(link, shardID, scheduleName)) } catch (err) { log.owner.warning('collectionid', err) if (err.code !== 50013) message.channel.send(err.message).catch(err => log.owner.warning('collectionid 1a', message.guild, err)) } } exports.sharded = exports.normal
const dbOpsSchedules = require('../../util/db/schedules.js') const ArticleModel = require('../../models/Article.js') const log = require('../../util/logger.js') exports.normal = async (bot, message) => { try { const args = message.content.split(' ') const feedID = args[1] if (!feedID) { return await message.channel.send('No feed ID argument') } const assigned = await dbOpsSchedules.assignedSchedules.get(feedID) if (!assigned) { return await message.channel.send('No assigned schedule') } const link = assigned.link const shardID = assigned.shard const scheduleName = assigned.schedule await message.channel.send(ArticleModel.getCollectionID(link, shardID, scheduleName)) } catch (err) { log.owner.warning('collectionid', err) if (err.code !== 50013) message.channel.send(err.message).catch(err => log.owner.warning('collectionid 1a', message.guild, err)) } } exports.sharded = exports.normal
Set record date on entity when persisting transaction
<?php namespace PerFi\PerFiBundle\Repository; use Doctrine\ORM\EntityRepository; use PerFi\Domain\Transaction\Transaction; use PerFi\Domain\Transaction\TransactionRepository as TransactionRepositoryInterface; use PerFi\PerFiBundle\Entity\Transaction as DtoTransaction; /** * TransactionRepository */ class TransactionRepository extends EntityRepository implements TransactionRepositoryInterface { /** * {@inheritdoc} */ public function add(Transaction $transaction) { $entity = new DtoTransaction(); $entity->setTransactionId((string) $transaction->id()); $entity->setType((string) $transaction->type()); $entity->setSourceAccount((string) $transaction->sourceAccount()->id()); $entity->setDestinationAccount((string) $transaction->destinationAccount()->id()); $entity->setDate($transaction->date()); $entity->setRecordDate($transaction->recordDate()); $entity->setDescription($transaction->description()); $amount = $transaction->amount(); $entity->setAmount($amount->getAmount()); $entity->setCurrency((string) $amount->getCurrency()); $em = $this->getEntityManager(); $em->persist($entity); $em->flush(); } /** * {@inheritdoc} */ public function getAll() : array { return []; } }
<?php namespace PerFi\PerFiBundle\Repository; use Doctrine\ORM\EntityRepository; use PerFi\Domain\Transaction\Transaction; use PerFi\Domain\Transaction\TransactionRepository as TransactionRepositoryInterface; use PerFi\PerFiBundle\Entity\Transaction as DtoTransaction; /** * TransactionRepository */ class TransactionRepository extends EntityRepository implements TransactionRepositoryInterface { /** * {@inheritdoc} */ public function add(Transaction $transaction) { $entity = new DtoTransaction(); $entity->setTransactionId((string) $transaction->id()); $entity->setType((string) $transaction->type()); $entity->setSourceAccount((string) $transaction->sourceAccount()->id()); $entity->setDestinationAccount((string) $transaction->destinationAccount()->id()); $entity->setDate($transaction->date()); $entity->setDescription($transaction->description()); $amount = $transaction->amount(); $entity->setAmount($amount->getAmount()); $entity->setCurrency((string) $amount->getCurrency()); $em = $this->getEntityManager(); $em->persist($entity); $em->flush(); } /** * {@inheritdoc} */ public function getAll() : array { return []; } }
Add link to module pattern doc
// fetch api // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch // https://blog.hospodarets.com/fetch_in_action // async/await // https://ponyfoo.com/articles/understanding-javascript-async-await // module pattern // http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html const venigi = (() => { let get = async function (source) { return await fetch(source) .then(response => response.text()) .catch(err => console.error(err.message)); } let getJson = async function (source) { return await fetch(source) .then(response => response.json()) .catch(err => console.error(err.message)); } return { get: get, getJson: getJson }; })();
// fetch api // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch // https://blog.hospodarets.com/fetch_in_action // async/await // https://ponyfoo.com/articles/understanding-javascript-async-await const venigi = (() => { let get = async function (source) { return await fetch(source) .then(response => response.text()) .catch(err => console.error(err.message)); } let getJson = async function (source) { return await fetch(source) .then(response => response.json()) .catch(err => console.error(err.message)); } return { get: get, getJson: getJson }; })();
Set select place marker latlng based on main map center latlng
var Place = {}; $(document).on('pageshow', '#select-place', function() { $('#select-place-map').css('height', 450); var pos = Map.map.getCenter(); Place.map = Map.createMap('select-place-map', pos.lat(), pos.lng(), 8); // kutc Place.currentLocation = Map.createMarker(Place.map, 'Current Location', pos.lat(), pos.lng(), true); Place.setPostLocation(); google.maps.event.addListener(Place.currentLocation, 'dragend', function() { Place.setPostLocation(); }); }); Place.getMarkerLocation = function() { var pos = Place.currentLocation.getPosition(); var lat = pos.lat(); var lng = pos.lng(); return {"latitude": lat, "longitude": lng}; }; Place.setPostLocation = function() { var location = Place.getMarkerLocation(); $('#post-lat').val(location.latitude); $('#post-lng').val(location.longitude); };
var Place = {}; $(document).on('pageshow', '#select-place', function() { $('#select-place-map').css('height', 500); utils.getCurrentLocation().done(function(location) { Place.map = Map.createMap('select-place-map', location.latitude, location.longitude, 12); Place.currentLocation = Map.createMarker(Place.map, 'Current Location', location.latitude, location.longitude, true); Place.setPostLocation(); google.maps.event.addListener(Place.currentLocation, 'dragend', function() { Place.setPostLocation(); }); }); }); Place.getMarkerLocation = function() { var pos = Place.currentLocation.getPosition(); var lat = pos.lat(); var lng = pos.lng(); return {"latitude": lat, "longitude": lng}; }; Place.setPostLocation = function() { var location = Place.getMarkerLocation(); $('#post-lat').val(location.latitude); $('#post-lng').val(location.longitude); };
Update to work with directory outside of cwd
var gulp = require('gulp'); var gReact = require('gulp-react'); var del = require('del'); var shell = require('gulp-shell'); gulp.task('clean', function(cb) { del(['lib/', 'Flux.js'], cb); }); gulp.task('default', ['clean'], function() { return gulp.src('src/*.js') .pipe(gReact({harmony: true})) .pipe(gulp.dest('lib')); }); gulp.task('build-examples-website', ['clean'], shell.task([[ 'pushd ../react-art-gh-pages', 'git checkout -- .', 'git clean -dfx', 'git pull', 'rm -rf *', 'popd', 'pushd examples/vector-widget', 'npm install', 'npm run build', 'popd', 'cp -r examples/vector-widget/{index.html,bundle.js} ../react-art-gh-pages', 'pushd ../react-art-gh-pages', 'git add -A .', 'git commit -m "Update website"', 'popd', 'echo "react-art-gh-pages ready to push"' ].join(';')]));
var gulp = require('gulp'); var gReact = require('gulp-react'); var del = require('del'); var shell = require('gulp-shell'); gulp.task('clean', function(cb) { del(['lib/', 'Flux.js'], cb); }); gulp.task('default', ['clean'], function() { return gulp.src('src/*.js') .pipe(gReact({harmony: true})) .pipe(gulp.dest('lib')); }); gulp.task('build-examples-website', ['clean'], shell.task([ 'git checkout gh-pages', 'git merge master', 'cd examples/vector-widget; ../../node_modules/.bin/webpack app.js bundle.js', 'cp -r examples/* .', 'git add --all .', 'git commit -m "Update website"', 'git push origin gh-pages', 'git checkout master' ]));
Update latest green build migration
"""add latest green build table Revision ID: 19b8969073ab Revises: 4d235d421320 Create Date: 2014-07-10 10:53:34.415990 """ # revision identifiers, used by Alembic. revision = '19b8969073ab' down_revision = '4d235d421320' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'latest_green_build', sa.Column('id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('branch', sa.String(length=128), nullable=False), sa.Column('build_id', sa.GUID(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.ForeignKeyConstraint(['build_id'], ['build.id'], ), sa.UniqueConstraint('project_id', 'branch', name='unq_project_branch') ) def downgrade(): op.drop_table('latest_green_build')
"""add latest green build table Revision ID: 19b8969073ab Revises: 2b7153fe25af Create Date: 2014-07-10 10:53:34.415990 """ # revision identifiers, used by Alembic. revision = '19b8969073ab' down_revision = '2b7153fe25af' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'latest_green_build', sa.Column('id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('branch', sa.String(length=128), nullable=False), sa.Column('build_id', sa.GUID(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.ForeignKeyConstraint(['build_id'], ['build.id'], ), sa.UniqueConstraint('project_id', 'branch', name='unq_project_branch') ) def downgrade(): op.drop_table('latest_green_build')
Use CSS styling to proportionally resize the iFrame Use the notebook aspect ratio to determine padding for the iFrame container. This keeps the proportions of the JupyterLab Notebook, avoids the delay caused by calculating the height, and seems to work smoothly across browsers. Signed-off-by: Brianna Major <6a62c0472e857db5994824f147beeb095c78d3a5@kitware.com>
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Iframe from 'react-iframe' import { Typography, withStyles } from '@material-ui/core'; import PageHead from './page-head'; import PageBody from './page-body'; const styles = () => ({ iframe: { border: 0, left: 0, position: 'absolute', top: 0, width:'100%', height:'100%' }, container: { overflow: 'hidden', position: 'relative', paddingTop: '72%' } }); class Notebook extends Component { render = () => { const { fileId, classes } = this.props; const baseUrl = `${window.location.origin}/api/v1`; return ( <div> <PageHead> <Typography color="inherit" gutterBottom variant="display1"> Notebook </Typography> </PageHead> <PageBody> <div className={classes.container}> <Iframe id='iframe' url={`${baseUrl}/notebooks/${fileId}/html`} className={classes.iframe}/> </div> </PageBody> </div> ); } } Notebook.propTypes = { fileId: PropTypes.string } Notebook.defaultProps = { fileId: null, } export default withStyles(styles)(Notebook)
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Iframe from 'react-iframe' import Typography from '@material-ui/core/Typography'; import PageHead from './page-head'; import PageBody from './page-body'; export default class Notebook extends Component { render = () => { const {fileId} = this.props; const baseUrl = `${window.location.origin}/api/v1`; return ( <div> <PageHead> <Typography color="inherit" gutterBottom variant="display1"> Notebook </Typography> </PageHead> <PageBody> <Iframe id='iframe' url={`${baseUrl}/notebooks/${fileId}/html`} width='100%' onLoad={function(){ var frame = document.getElementById('iframe'); if (frame) { frame.height = frame.contentWindow.document.body.scrollHeight + 'px'; } }}/> </PageBody> </div> ); } } Notebook.propTypes = { fileId: PropTypes.string } Notebook.defaultProps = { fileId: null, }
Update argument to createContentItem in Content
// ---------------------------------------------------------------- // Content Class class Content { static get TYPE_NAME_KEY() { return 0; } static get CONTENT() { return 'content'; } static get ITEM() { return 'content-item'; } static get ITEM_HEADER() { return 'content-item-header'; } static get ITEM_NAME() { return 'content-item-name'; } static get ITEM_KEYS() { return 'content-item-keys'; } static get ITEM_KEY() { return 'content-item-key'; } static createContentItem( _type = Content.TYPE_NAME_KEY, _header = null, _name = null, ..._key = [] ) { let result = ''; return result; } }
// ---------------------------------------------------------------- // Content Class class Content { static get TYPE_NAME_KEY() { return 0; } static get CONTENT() { return 'content'; } static get ITEM() { return 'content-item'; } static get ITEM_HEADER() { return 'content-item-header'; } static get ITEM_NAME() { return 'content-item-name'; } static get ITEM_KEYS() { return 'content-item-keys'; } static get ITEM_KEY() { return 'content-item-key'; } static createContentItem( _type = Content.TYPE_NAME_KEY, _name = null, ..._key = [] ) { let result = ''; return result; } }
Rename database in log file.
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/school_census/create_files.py en/pt output_path\n" exit() logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG) for year in range(2007, 2016): logging.info("python scripts/data_download/school_census/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n") ret = commands.getoutput("python scripts/data_download/school_census/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year)) logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")
import os import commands import time import logging import sys if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']): print "ERROR! Use:\n python scripts/data_download/school_census/create_files.py en/pt output_path\n" exit() logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG) for year in range(2007, 2016): logging.info("python scripts/data_download/higher_education/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n") ret = commands.getoutput("python scripts/data_download/school_census/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year)) logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")
Fix not going to dominion status page after logging via 'remember me'
<?php namespace OpenDominion\Http\Controllers; use Auth; use OpenDominion\Services\Dominion\SelectorService; class HomeController extends AbstractController { public function getIndex() { // Only redirect to status/dashboard if we have no referer if (Auth::check() && (request()->server('HTTP_REFERER') !== '') && (url()->previous() === url()->current())) { $dominionSelectorService = app(SelectorService::class); if ($dominionSelectorService->tryAutoSelectDominionForAuthUser()) { return redirect()->route('dominion.status'); } return redirect()->route('dashboard'); } return view('pages.home'); } }
<?php namespace OpenDominion\Http\Controllers; use Auth; use OpenDominion\Services\Dominion\SelectorService; class HomeController extends AbstractController { public function getIndex() { // Only redirect to status/dashboard if we have no referer if (Auth::check() && (request()->server('HTTP_REFERER') !== '') && (url()->previous() === url()->current())) { $dominionSelectorService = app(SelectorService::class); if ($dominionSelectorService->hasUserSelectedDominion()) { return redirect()->route('dominion.status'); } return redirect()->route('dashboard'); } return view('pages.home'); } }
Discard supplier after it's used
package editor.util; import java.util.function.Supplier; /** * This class "lazily" supplies a value by not evaluating it until the first time * it is requested. Then that function's result is cached so it doesn't have to * be reevaluated again. * * @param <T> Type of object that is being lazily evaluated * @author Alec Roelke */ public class Lazy<T> implements Supplier<T> { /** * Cached value. */ private T value; /** * Supplier for the cached value. */ private Supplier<T> supplier; /** * Create a new Lazy supplier. * * @param val Function supplying the value to lazily evaluate. */ public Lazy(Supplier<T> val) { value = null; supplier = val; } /** * If the value has not been computed, compute it and then return it. Otherwise, * just return it. * * @return The value computed by the function */ @Override public T get() { if (value == null) { value = supplier.get(); supplier = null; } return value; } }
package editor.util; import java.util.function.Supplier; /** * This class "lazily" supplies a value by not evaluating it until the first time * it is requested. Then that function's result is cached so it doesn't have to * be reevaluated again. * * @param <T> Type of object that is being lazily evaluated * @author Alec Roelke */ public class Lazy<T> implements Supplier<T> { /** * Cached value. */ private T value; /** * Supplier for the cached value. */ private Supplier<T> supplier; /** * Create a new Lazy supplier. * * @param val Function supplying the value to lazily evaluate. */ public Lazy(Supplier<T> val) { value = null; supplier = val; } /** * If the value has not been computed, compute it and then return it. Otherwise, * just return it. * * @return The value computed by the function */ @Override public T get() { if (value == null) value = supplier.get(); return value; } }
Support for Internet Explorer 8
/** * @author mrdoob / http://mrdoob.com * @author Jesús Leganés Combarro "Piranna" <piranna@gmail.com> */ function EventTarget() { var listeners = {}; this.addEventListener = function(type, listener) { if(!listener) return var listeners_type = listeners[type] if(listeners_type === undefined) listeners[type] = listeners_type = []; for(var i=0,l; l=listeners_type[i]; i++) if(l === listener) return; listeners_type.push(listener); }; this.dispatchEvent = function(event) { var type = event.type var listenerArray = (listeners[type] || []); var dummyListener = this['on' + type]; if(typeof dummyListener == 'function') listenerArray = listenerArray.concat(dummyListener); for(var i=0,listener; listener=listenerArray[i]; i++) listener.call(this, event); }; this.removeEventListener = function(type, listener) { if(!listener) return var listeners_type = listeners[type] if(listeners_type === undefined) return for(var i=0,l; l=listeners_type[i]; i++) if(l === listener) { listeners_type.splice(i, 1); break; } if(!listeners_type.length) delete listeners[type] }; }; if(typeof module !== 'undefined' && module.exports) module.exports = EventTarget;
/** * @author mrdoob / http://mrdoob.com * @author Jesús Leganés Combarro "Piranna" <piranna@gmail.com> */ function EventTarget() { var listeners = {}; this.addEventListener = function(type, listener) { if(!listener) return var listeners_type = listeners[type] if(listeners_type === undefined) listeners[type] = listeners_type = []; if(listeners_type.indexOf(listener) === -1) listeners_type.push(listener); }; this.dispatchEvent = function(event) { var type = event.type var listenerArray = (listeners[type] || []); var dummyListener = this['on' + type]; if(typeof dummyListener == 'function') listenerArray = listenerArray.concat(dummyListener); for(var i=0,listener; listener=listenerArray[i]; i++) listener.call(this, event); }; this.removeEventListener = function(type, listener) { if(!listener) return var listeners_type = listeners[type] if(listeners_type === undefined) return var index = listeners_type.indexOf(listener); if(index !== -1) listeners_type.splice(index, 1); if(!listeners_type.length) delete listeners[type] }; }; if(typeof module !== 'undefined' && module.exports) module.exports = EventTarget;
Remove [thz.la] from file names.
import os import re distDir = 'H:\\temp' p = re.compile(r'(\D+\d+)\w*(.\w+)') filenames = os.listdir(distDir) upperfilenames = [] print(filenames) for filenamepref in filenames: if filenamepref.find('_') > 0: filenameprefit = filenamepref[filenamepref.index('_'):] else: filenameprefit = filenamepref filenamepost = filenameprefit.replace('-', '').replace('_', '')\ .replace(' ', '').replace('.1080p', '').replace('.720p', '')\ .replace('[thz.la]', '').replace('[Thz.la]', '') distname = p.search(filenamepost).group(1).upper() + p.search(filenamepost).group(2).lower() print(distname) os.rename(distDir + os.sep + filenamepref, distDir + os.sep + distname)
import requests import bs4 import os import urllib.request import shutil import re distDir = 'F:\\utorrent\\WEST' p = re.compile(r'(\D+\d+)\w*(.\w+)') filenames = os.listdir(distDir) upperfilenames = [] print(filenames) for filenamepref in filenames: if (filenamepref.find('_') > 0): filenameprefit = filenamepref[filenamepref.index('_'):] else: filenameprefit = filenamepref filenamepost = filenameprefit.replace('-', '').replace('_', '')\ .replace(' ', '').replace('.1080p', '').replace('.720p', '') distname = p.search(filenamepost).group(1).upper() + p.search(filenamepost).group(2).lower() print(distname) os.rename(distDir + os.sep + filenamepref, distDir + os.sep + distname)
Test Map<String,List> as read only attribute
package uk.co.jemos.podam.test.dto.pdm45; import java.util.List; import java.util.HashMap; import java.util.Map; /** * Pojo with map of generic attributes. * * @author daivanov * */ public class GenericMapPojo<F, S> { private Map<String, GenericPojo<F, S>> genericPojos; private Map<String, List> genericRawLists = new HashMap<String, List>(); /** * Map getter * @return the genericPojo */ public Map<String, GenericPojo<F, S>> getGenericPojos() { return genericPojos; } /** * Map setter * @param genericPojos the genericPojo to set */ public void setGenericPojos(Map<String, GenericPojo<F, S>> genericPojos) { this.genericPojos = genericPojos; } /** * Map getter * @return the genericRawLists */ public Map<String, List> getGenericRawLists() { return genericRawLists; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "GenericAttributePojo [genericPojo=" + genericPojos + "]"; } }
package uk.co.jemos.podam.test.dto.pdm45; import java.util.List; import java.util.Map; /** * Pojo with map of generic attributes. * * @author daivanov * */ public class GenericMapPojo<F, S> { private Map<String, GenericPojo<F, S>> genericPojos; private Map<String, List> genericRawLists; /** * Map getter * @return the genericPojo */ public Map<String, GenericPojo<F, S>> getGenericPojos() { return genericPojos; } /** * Map setter * @param genericPojos the genericPojo to set */ public void setGenericPojos(Map<String, GenericPojo<F, S>> genericPojos) { this.genericPojos = genericPojos; } /** * Map getter * @return the genericRawLists */ public Map<String, List> getGenericRawLists() { return genericRawLists; } /** * Map setter * @param genericRawLists the genericRawLists to set */ public void setGenericRawLists(Map<String, List> genericRawLists) { this.genericRawLists = genericRawLists; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "GenericAttributePojo [genericPojo=" + genericPojos + "]"; } }
Use keypath.str property to prevent coercion erros
import { isArray } from 'utils/is'; import { getKeypath, normalise } from 'shared/keypaths'; import runloop from 'global/runloop'; import getNewIndices from 'shared/getNewIndices'; var arrayProto = Array.prototype; export default function ( methodName ) { return function ( keypath, ...args ) { var array, newIndices = [], len, promise, result; keypath = getKeypath( normalise( keypath ) ); array = this.viewmodel.get( keypath ); len = array.length; if ( !isArray( array ) ) { throw new Error( 'Called ractive.' + methodName + '(\'' + keypath.str + '\'), but \'' + keypath.str + '\' does not refer to an array' ); } newIndices = getNewIndices( array, methodName, args ); result = arrayProto[ methodName ].apply( array, args ); promise = runloop.start( this, true ).then( () => result ); if ( !!newIndices ) { this.viewmodel.smartUpdate( keypath, array, newIndices ); } else { this.viewmodel.mark( keypath ); } runloop.end(); return promise; }; }
import { isArray } from 'utils/is'; import { getKeypath, normalise } from 'shared/keypaths'; import runloop from 'global/runloop'; import getNewIndices from 'shared/getNewIndices'; var arrayProto = Array.prototype; export default function ( methodName ) { return function ( keypath, ...args ) { var array, newIndices = [], len, promise, result; keypath = getKeypath( normalise( keypath ) ); array = this.viewmodel.get( keypath ); len = array.length; if ( !isArray( array ) ) { throw new Error( 'Called ractive.' + methodName + '(\'' + keypath + '\'), but \'' + keypath + '\' does not refer to an array' ); } newIndices = getNewIndices( array, methodName, args ); result = arrayProto[ methodName ].apply( array, args ); promise = runloop.start( this, true ).then( () => result ); if ( !!newIndices ) { this.viewmodel.smartUpdate( keypath, array, newIndices ); } else { this.viewmodel.mark( keypath ); } runloop.end(); return promise; }; }
Remove single use locval variable
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.Map; import org.apache.commons.lang3.builder.ToStringStyle; import org.junit.jupiter.api.AfterEach; public class AbstractLangTest { /** * All tests should leave the {@link ToStringStyle} registry empty. */ @AfterEach public void after() { validateNullToStringStyleRegistry(); } void validateNullToStringStyleRegistry() { assertNull(ToStringStyle.getRegistry(), "Expected null, actual: " + ToStringStyle.getRegistry()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.Map; import org.apache.commons.lang3.builder.ToStringStyle; import org.junit.jupiter.api.AfterEach; public class AbstractLangTest { /** * All tests should leave the {@link ToStringStyle} registry empty. */ @AfterEach public void after() { validateNullToStringStyleRegistry(); } void validateNullToStringStyleRegistry() { final Map<Object, Object> registry = ToStringStyle.getRegistry(); assertNull(registry, "Expected null, actual: " + registry); } }
Attach to player, not other things
"use strict"; var onEntityDelete = require("splat-ecs/lib/systems/box-collider").onEntityDelete; function getCamera(entities) { return entities[1]; } module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars ecs.addEach(function(entity, elapsed) { // eslint-disable-line no-unused-vars if (entity.collisions.length === 0) { return; } var player = data.entities.entities[0]; entity.collisions.forEach(function(id) { var other = data.entities.entities[id]; if (other.sticky) { return; } data.canvas.width += 50; data.canvas.height += 50; other.match = { id: player.id, offsetX: other.position.x - player.position.x, offsetY: other.position.y - player.position.y }; other.sticky = true; other.velocity = { x: 0, y: 0 }; onEntityDelete(other, data); }); var camera = getCamera(data.entities.entities); camera.size.width = data.canvas.width; camera.size.height = data.canvas.height; }, ["sticky"]); };
"use strict"; var onEntityDelete = require("splat-ecs/lib/systems/box-collider").onEntityDelete; function getCamera(entities) { return entities[1]; } module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars ecs.addEach(function(entity, elapsed) { // eslint-disable-line no-unused-vars if (entity.collisions.length === 0) { return; } entity.collisions.forEach(function(id) { var other = data.entities.entities[id]; if (other.sticky) { return; } data.canvas.width += 50; data.canvas.height += 50; other.match = { id: entity.id, offsetX: other.position.x - entity.position.x, offsetY: other.position.y - entity.position.y }; other.sticky = true; other.velocity = { x: 0, y: 0 }; onEntityDelete(other, data); }); var camera = getCamera(data.entities.entities); camera.size.width = data.canvas.width; camera.size.height = data.canvas.height; }, ["sticky"]); };
Update category and website on module description
# -*- coding: utf-8 -*- { 'name': 'Document Attachment', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Hidden/Dependency', 'description': """Enchancements to the ir.attachment module to manage kinds of attachments that can be linked with OpenERP objects. The implenter has to: - Pass 'res_model' and 'res_id' in the context. - Define menus and actions should it want to allow changing document types. Document attachments are displayed in a many2many field; it can optionally be changed to work like a one2many field by using the "domain="[('res_id', '=', id)]" attribute. """, 'website': 'http://odoo.consulting/', 'depends': [ 'base', 'document', ], 'data': [ 'security/ir.model.access.csv', 'document_attachment.xml', ], 'test': [ ], 'installable': True, }
# -*- coding: utf-8 -*- { 'name': 'Document Attachment', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Dependency', 'description': """Enchancements to the ir.attachment module to manage kinds of attachments that can be linked with OpenERP objects. The implenter has to: - Pass 'res_model' and 'res_id' in the context. - Define menus and actions should it want to allow changing document types. Document attachments are displayed in a many2many field; it can optionally be changed to work like a one2many field by using the "domain="[('res_id', '=', id)]" attribute. """, 'website': 'www.odoo.consulting/', 'depends': [ 'base', 'document', ], 'data': [ 'security/ir.model.access.csv', 'document_attachment.xml', ], 'test': [ ], 'installable': True, }
OpenFile: Use *.bob over *.opi when called from alarm UI, cmd line
/******************************************************************************* * Copyright (c) 2015-2016 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.csstudio.display.builder.rcp; import org.csstudio.display.builder.model.macros.MacroXMLUtil; import org.csstudio.display.builder.model.macros.Macros; import org.csstudio.openfile.IOpenDisplayAction; /** Handler for opening files from command line * * <p>See * Opening Files from Command-Line - org.csstudio.openfile * in CS-Studio docbook. * * @author Kay Kasemir */ @SuppressWarnings("nls") public class OpenDisplayFile implements IOpenDisplayAction { @Override public void openDisplay(final String path, final String data) throws Exception { final Macros macros = MacroXMLUtil.readMacros(data); // 'resolve', i.e. use *.bob over *.opi if found final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros, true); new OpenDisplayAction(info).run(); } }
/******************************************************************************* * Copyright (c) 2015-2016 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.csstudio.display.builder.rcp; import org.csstudio.display.builder.model.macros.MacroXMLUtil; import org.csstudio.display.builder.model.macros.Macros; import org.csstudio.openfile.IOpenDisplayAction; /** Handler for opening files from command line * * <p>See * Opening Files from Command-Line - org.csstudio.openfile * in CS-Studio docbook. * * @author Kay Kasemir */ @SuppressWarnings("nls") public class OpenDisplayFile implements IOpenDisplayAction { @Override public void openDisplay(final String path, final String data) throws Exception { final Macros macros = MacroXMLUtil.readMacros(data); final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros); new OpenDisplayAction(info).run(); } }
Add $gArchive to queries so we can start using page table archive column as a way to do one-off runs. git-svn-id: d5a8a4092b1c3eddbe100e0c5fc6446cfb12afd1@894 fc7d47d3-c008-acd5-f51f-d19787b8a02f
<?php require_once("utils.inc"); define("MIN_RESULTS", 12); // TODO - move it to conf file $term = getParam("term"); if ( ! $term ) { return; // no need to run anything - May be, return 'warn' in dev mode } $sites = array(); $query = "select urlShort, max(pageid) as pageid from $gPagesTable where archive='$gArchive' and urlShort like '%$term%' group by urlShort order by urlShort asc limit 101;"; $result = doQuery($query); $numUrls = mysql_num_rows($result); if ($numUrls > MIN_RESULTS) { array_push($sites, array("label" => ( $numUrls > 100 ? "100+ URLs" : "$numUrls URLs" ) . ", refine further", "value" => "0")); } else { // less then min results - so we'll give the list of urls while ( $row = mysql_fetch_assoc($result) ) { $url = $row['urlShort']; $pageid = $row['pageid']; array_push($sites, array("label" => $url, "value" => $url, "data-pageid" => $pageid)); } } mysql_free_result($result); //echo JSON to our jQueryUI auto-complete box $response = json_encode($sites); echo $response; ?>
<?php require_once("utils.inc"); define("MIN_RESULTS", 12); // TODO - move it to conf file $term = getParam("term"); if ( ! $term ) { return; // no need to run anything - May be, return 'warn' in dev mode } $sites = array(); $query = "select urlShort, max(pageid) as pageid from $gPagesTable where urlShort like '%$term%' group by urlShort order by urlShort asc limit 101;"; $result = doQuery($query); $numUrls = mysql_num_rows($result); if ($numUrls > MIN_RESULTS) { array_push($sites, array("label" => ( $numUrls > 100 ? "100+ URLs" : "$numUrls URLs" ) . ", refine further", "value" => "0")); } else { // less then min results - so we'll give the list of urls while ( $row = mysql_fetch_assoc($result) ) { $url = $row['urlShort']; $pageid = $row['pageid']; array_push($sites, array("label" => $url, "value" => $url, "data-pageid" => $pageid)); } } mysql_free_result($result); //echo JSON to our jQueryUI auto-complete box $response = json_encode($sites); echo $response; ?>
Allow shortening of "tvsearch" to "tv", "SAB_RATE" env, decimal rate arg
package main import ( "flag" "log" "os" "strconv" "git.astuart.co/andrew/limio" ) var t = flag.String("t", "movie", "the type of search to perform") var rl = flag.String("r", "", "the rate limit") var nc = flag.Bool("nocache", false, "skip cache") var clr = flag.Bool("clear", false, "clear cache") var downRate int func init() { flag.Parse() if *t == "tv" { *t = "tvsearch" } if *rl == "" { *rl = os.Getenv("SAB_RATE") } orig := *rl if len(*rl) > 0 { rl := []byte(*rl) unit := rl[len(rl)-1] rl = rl[:len(rl)-1] qty, err := strconv.ParseFloat(string(rl), 64) if err != nil { log.Printf("Bad quantity: %s\n", orig) } switch unit { case 'm': downRate = int(qty * float64(limio.MB)) case 'k': downRate = int(qty * float64(limio.KB)) } } }
package main import ( "flag" "log" "strconv" "git.astuart.co/andrew/limio" ) var t = flag.String("t", "search", "the type of search to perform") var rl = flag.String("r", "", "the rate limit") var nc = flag.Bool("nocache", false, "skip cache") var clr = flag.Bool("clear", false, "clear cache") var downRate int func init() { flag.Parse() orig := *rl if len(*rl) > 0 { rl := []byte(*rl) unit := rl[len(rl)-1] rl = rl[:len(rl)-1] qty, err := strconv.Atoi(string(rl)) if err != nil { log.Printf("Bad quantity: %s\n", orig) } switch unit { case 'm': downRate = qty * limio.MB case 'k': downRate = qty * limio.KB } } }
Use jQuery ajax request instead of fetch `fetch` doesn't work with URLs without a protocol.
import Ember from 'ember'; import ENV from '../config/environment' export default Ember.Component.extend({ classNames: ['noise-query-and-results'], results: null, // Store the query that was set by the tutorial. If that query changes, // by going to another tutorial step, then empty the results. tutorialQuery: null, actions: { doQuery() { const query = this.$('textarea').val(); Ember.$.post(ENV.noiseUrl, query, data => { this.set('results', data); }); } }, didUpdateAttrs() { // Empty the results only if the query changed to due to the tutorial, // don't empty them when the user does some input. if (this.get('tutorialQuery') != this.get('attrs').query.value) { this.set('results', null); this.set('tutorialQuery', this.get('attrs').query.value); } }, });
import Ember from 'ember'; import fetch from "ember-network/fetch"; import ENV from '../config/environment' export default Ember.Component.extend({ classNames: ['noise-query-and-results'], results: null, // Store the query that was set by the tutorial. If that query changes, // by going to another tutorial step, then empty the results. tutorialQuery: null, actions: { doQuery() { const query = this.$('textarea').val(); fetch(ENV.noiseUrl, { method: "POST", body: query }).then(data => { return data.json(); }).then(json => { this.set('results', json); }); } }, didUpdateAttrs() { // Empty the results only if the query changed to due to the tutorial, // don't empty them when the user does some input. if (this.get('tutorialQuery') != this.get('attrs').query.value) { this.set('results', null); this.set('tutorialQuery', this.get('attrs').query.value); } }, });
Simplify the definision of install_requires
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, Inc.", author_email="support@treasure-data.com", url="http://treasuredata.com/", install_requires=open("requirements.txt").read().splitlines(), packages=find_packages(), license="Apache Software License", platforms="Posix; MacOS X; Windows", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Internet", ], )
#!/usr/bin/env python from setuptools import setup, find_packages install_requires = [] with open("requirements.txt") as fp: for s in fp: install_requires.append(s.strip()) setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, Inc.", author_email="support@treasure-data.com", url="http://treasuredata.com/", install_requires=install_requires, packages=find_packages(), license="Apache Software License", platforms="Posix; MacOS X; Windows", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Internet", ], )
Clean up old test, pass all tests
# -*- coding: utf-8 -*- """ Postpasses over the LLVM IR. The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc """ from __future__ import print_function, division, absolute_import from numba.support.math_support import linking, libs default_postpasses = {} def register_default(name): def dec(f): default_postpasses[name] = f return f return dec # ______________________________________________________________________ # Postpasses @register_default('math') def postpass_link_math(env, ee, lmod, lfunc): "numba.math.* -> mathcode.*" replacements = {} for lf in lmod.functions: if lf.name.startswith('numba.math.'): _, _, name = lf.name.rpartition('.') replacements[lf.name] = name del lf # this is dead after linking below linking.link_llvm_math_intrinsics(ee, lmod, libs.math_library, linking.LLVMLinker(), replacements) return lfunc
# -*- coding: utf-8 -*- """ Postpasses over the LLVM IR. The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc """ from __future__ import print_function, division, absolute_import from numba.support.math_support import math_support, libs default_postpasses = {} def register_default(name): def dec(f): default_postpasses[name] = f return f return dec # ______________________________________________________________________ # Postpasses @register_default('math') def postpass_link_math(env, ee, lmod, lfunc): "numba.math.* -> mathcode.*" replacements = {} for lf in lmod.functions: if lf.name.startswith('numba.math.'): _, _, name = lf.name.rpartition('.') replacements[lf.name] = name del lf # this is dead after linking below math_support.link_llvm_math_intrinsics(ee, lmod, libs.math_library, math_support.LLVMLinker(), replacements) return lfunc
Call any previous beforeRender() once we're done with ours
import { options } from 'preact'; let currentIndex; let component; let oldBeforeRender = options.beforeRender; options.beforeRender = vnode => { component = vnode._component; currentIndex = 0; if (oldBeforeRender) oldBeforeRender(vnode) } const createHook = (create) => (...args) => { if (component == null) return; const list = component.__hooks || (component.__hooks = []); let index = currentIndex++; let hook = list[index]; if (!hook) { hook = list[index] = { index, value: undefined }; hook.run = create(hook, component, ...args); } return (hook.value = hook.run()); }; export const useState = createHook((hook, inst, initialValue) => { const stateId = 'hookstate$' + hook.index; let value = typeof initialValue === 'function' ? initialValue() : initialValue; const setter = {}; setter[stateId] = inst.state[stateId] = value; function set(v) { value = setter[stateId] = typeof v === 'function' ? v(value) : v; inst.setState(setter); } return () => [value, set]; });
import { options } from 'preact'; let currentIndex; let component; options.beforeRender = function (vnode) { component = vnode._component; currentIndex = 0; } const createHook = (create) => (...args) => { if (component == null) return; const list = component.__hooks || (component.__hooks = []); let index = currentIndex++; let hook = list[index]; if (!hook) { hook = list[index] = { index, value: undefined }; hook.run = create(hook, component, ...args); } return (hook.value = hook.run()); }; export const useState = createHook((hook, inst, initialValue) => { const stateId = 'hookstate$' + hook.index; let value = typeof initialValue === 'function' ? initialValue() : initialValue; const setter = {}; setter[stateId] = inst.state[stateId] = value; function set(v) { value = setter[stateId] = typeof v === 'function' ? v(value) : v; inst.setState(setter); } return () => [value, set]; });
Fix warning on docs deploy.
import React, {Component, PropTypes} from "react"; import {Route} from "react-router"; import {PageContainer as PhenomicPageContainer} from 'phenomic'; import LayoutContainer from "../LayoutContainer"; import OptimisationContainer from "../layouts/Optimisations/show"; import * as layouts from '../layouts'; class PageContainer extends Component { static propTypes = { params: PropTypes.object.isRequired, }; render () { const {props} = this; return ( <PhenomicPageContainer {...props} layouts={layouts} /> ); } componentWillReceiveProps (props) { if (props.params.splat !== this.props.params.splat && !window.location.hash) { window.scrollTo(0, 0); } } } export default ( <Route component={LayoutContainer}> <Route path="/optimisations/:optimisation" component={OptimisationContainer} /> <Route path="*" component={PageContainer} /> </Route> );
import React, {Component, PropTypes} from "react"; import {Route} from "react-router"; import PhenomicPageContainer from "phenomic/lib/PageContainer"; import LayoutContainer from "../LayoutContainer"; import OptimisationContainer from "../layouts/Optimisations/show"; import * as layouts from '../layouts'; class PageContainer extends Component { static propTypes = { params: PropTypes.object.isRequired, }; render () { const {props} = this; return ( <PhenomicPageContainer {...props} layouts={layouts} /> ); } componentWillReceiveProps (props) { if (props.params.splat !== this.props.params.splat && !window.location.hash) { window.scrollTo(0, 0); } } } export default ( <Route component={LayoutContainer}> <Route path="/optimisations/:optimisation" component={OptimisationContainer} /> <Route path="*" component={PageContainer} /> </Route> );
Add FileListing to objects we export
import os from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401 from .core import FileListing # noqa: F401 from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401 from .mappers import get_active_lines # noqa: F401 from .util import defaults, parse_table # noqa: F401 __here__ = os.path.dirname(os.path.abspath(__file__)) package_info = {k: None for k in ["RELEASE", "COMMIT", "VERSION", "NAME"]} for name in package_info: with open(os.path.join(__here__, name)) as f: package_info[name] = f.read().strip() def get_nvr(): return "{0}-{1}-{2}".format(package_info["NAME"], package_info["VERSION"], package_info["RELEASE"]) RULES_STATUS = {} """ Mapping of dictionaries containing nvr and commitid for each rule repo included in this instance {"rule_repo_1": {"version": nvr(), "commit": sha1}} """ def add_status(name, nvr, commit): """ Rule repositories should call this method in their package __init__ to register their version information. """ RULES_STATUS[name] = {"version": nvr, "commit": commit}
import os from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401 from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401 from .mappers import get_active_lines # noqa: F401 from .util import defaults, parse_table # noqa: F401 __here__ = os.path.dirname(os.path.abspath(__file__)) package_info = {k: None for k in ["RELEASE", "COMMIT", "VERSION", "NAME"]} for name in package_info: with open(os.path.join(__here__, name)) as f: package_info[name] = f.read().strip() def get_nvr(): return "{0}-{1}-{2}".format(package_info["NAME"], package_info["VERSION"], package_info["RELEASE"]) RULES_STATUS = {} """ Mapping of dictionaries containing nvr and commitid for each rule repo included in this instance {"rule_repo_1": {"version": nvr(), "commit": sha1}} """ def add_status(name, nvr, commit): """ Rule repositories should call this method in their package __init__ to register their version information. """ RULES_STATUS[name] = {"version": nvr, "commit": commit}
Fix store detail return data
<?php namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\Controller\Annotations\Get; use FOS\RestBundle\Controller\Annotations\View; use Symfony\Component\Security\Core\User\UserInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use AppBundle\Entity\User; use AppBundle\Entity\Store; use Nelmio\ApiDocBundle\Annotation\ApiDoc; class StoresController extends FOSRestController { /** * List all stores of the logged in user. * * @ApiDoc() * @View(statusCode=200, serializerGroups={"userId", "storeDetail", "conversationList"}) * @Get("/api/v1/stores") */ public function listAction(UserInterface $user = null) { $repository = $this->getDoctrine()->getRepository('AppBundle:Store'); $stores = $repository->findAllForUserOrderedByName($user->getId()); return ['stores' => $stores]; } /** * Get detailed information on a specific store. * * @ApiDoc() * @View(statusCode=200, serializerGroups={"profile", "userProfileStore", "storeDetail", "conversationList"}) * @Get("/api/v1/stores/{id}") * @Security("is_granted('view', store)") */ public function getAction(Store $store) { return ['store' => $store]; } }
<?php namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\Controller\Annotations\Get; use FOS\RestBundle\Controller\Annotations\View; use Symfony\Component\Security\Core\User\UserInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use AppBundle\Entity\User; use AppBundle\Entity\Store; use Nelmio\ApiDocBundle\Annotation\ApiDoc; class StoresController extends FOSRestController { /** * List all stores of the logged in user. * * @ApiDoc() * @View(statusCode=200, serializerGroups={"userId", "storeDetail", "conversationList"}) * @Get("/api/v1/stores") */ public function listAction(UserInterface $user = null) { $repository = $this->getDoctrine()->getRepository('AppBundle:Store'); $stores = $repository->findAllForUserOrderedByName($user->getId()); return ['stores' => $stores]; } /** * Get detailed information on a specific store. * * @ApiDoc() * @View(statusCode=200, serializerGroups={"profile", "userProfileStore", "storeDetail", "conversationList"}) * @Get("/api/v1/stores/{id}") * @Security("is_granted('view', store)") */ public function getAction(Store $store) { return ['stores' => $store]; } }
Comment out missing call to notify plugin
var gulp = require('gulp'); var sass = require('gulp-sass'); var sasslint = require('gulp-sass-lint'); var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); var header = require('gulp-header'); var pkg = require('./package.json'); var banner = '/*! <%= pkg.name %>: v.<%= pkg.version %>, last updated on: <%= new Date() %> */\n'; /////////////////////////////////// // Build Tasks /////////////////////////////////// /////////////////////////////////// // Development Tasks /////////////////////////////////// gulp.task('styles:dev', function() { return gulp.src('./scss/**/*.s+(a|c)ss') .pipe(sasslint({configFile: '.ubs-sass-lint.yml'})) .pipe(sasslint.format()) .pipe(sasslint.failOnError(false)) .pipe(sourcemaps.init()) .pipe(sass({outputStyle: 'expanded'})) //.pipe(rename({extname: '.dev.css'})) .pipe(header(banner, {pkg : pkg})) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('./css')) //.pipe(notify(notifyMsg)); }); gulp.task('default', ['styles:dev']);
var gulp = require('gulp'); var sass = require('gulp-sass'); var sasslint = require('gulp-sass-lint'); var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); var header = require('gulp-header'); var pkg = require('./package.json'); var banner = '/*! <%= pkg.name %>: v.<%= pkg.version %>, last updated on: <%= new Date() %> */\n'; /////////////////////////////////// // Build Tasks /////////////////////////////////// /////////////////////////////////// // Development Tasks /////////////////////////////////// gulp.task('styles:dev', function() { return gulp.src('./scss/**/*.s+(a|c)ss') .pipe(sasslint({configFile: '.ubs-sass-lint.yml'})) .pipe(sasslint.format()) .pipe(sasslint.failOnError(false)) .pipe(sourcemaps.init()) .pipe(sass({outputStyle: 'expanded'})) //.pipe(rename({extname: '.dev.css'})) .pipe(header(banner, {pkg : pkg})) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('./css')) .pipe(notify(notifyMsg)); }); gulp.task('default', ['styles:dev']);
Change the tag to fit the size requirements of the log class
package edu.berkeley.eecs.cfc_tracker.test.location; import android.content.Intent; import android.util.Log; /** * Created by shankari on 1/18/15. */ public class MockLocationBroadcastChecker extends BroadcastChecker { private static final String TAG = "MockLocationBrdcstChker"; private int code1; private int code2; public MockLocationBroadcastChecker(String broadcastAction, int code1, int code2) { super(broadcastAction); this.code1 = code1; this.code2 = code2; Log.d(TAG, "Creation done with "+broadcastAction+", "+code1+", "+code2); } public boolean isMatchingIntent(Intent intent) { if (super.isMatchingIntent(intent)) { int iCode1 = intent.getIntExtra(LocationUtils.KEY_EXTRA_CODE1, 0); int iCode2 = intent.getIntExtra(LocationUtils.KEY_EXTRA_CODE2, 0); Log.d(TAG, "intent string matches, checking extra codes from intent "+ iCode1+", "+iCode2+" against stored "+code1+", "+code2); if (iCode1 == code1 && iCode2 == code2) { return true; } } return false; } }
package edu.berkeley.eecs.cfc_tracker.test.location; import android.content.Intent; import android.util.Log; /** * Created by shankari on 1/18/15. */ public class MockLocationBroadcastChecker extends BroadcastChecker { private static final String TAG = "MockLocationBroadcastChecker"; private int code1; private int code2; public MockLocationBroadcastChecker(String broadcastAction, int code1, int code2) { super(broadcastAction); this.code1 = code1; this.code2 = code2; Log.d(TAG, "Creation done with "+broadcastAction+", "+code1+", "+code2); } public boolean isMatchingIntent(Intent intent) { if (super.isMatchingIntent(intent)) { int iCode1 = intent.getIntExtra(LocationUtils.KEY_EXTRA_CODE1, 0); int iCode2 = intent.getIntExtra(LocationUtils.KEY_EXTRA_CODE2, 0); Log.d(TAG, "intent string matches, checking extra codes from intent "+ iCode1+", "+iCode2+" against stored "+code1+", "+code2); if (iCode1 == code1 && iCode2 == code2) { return true; } } return false; } }
Add link to go back to index
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost } from '../actions'; class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } render() { const { post } = this.props; if (!post) { return <div>Loading...</div>; } return ( <div> <Link to="/">Back To Index</Link> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost })(PostsShow);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchPost } from '../actions'; class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } render() { const { post } = this.props; if (!post) { return <div>Loading...</div>; } return ( <div> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost })(PostsShow);
Add middleware to convert true/false query parameters to respective boolean values
var Express = require('express'); var FS = require('fs'); var HTTP = require('http'); require('../lib/config'); var app = Express(); var server = HTTP.createServer(app); // Convert true, false, and null to primatives app.use(function(req, res, next) { Object.keys(req.query).forEach(function(key) { switch(req.query[key]) { case 'true': req.query[key] = true; break; case 'false': req.query[key] = false; break; case 'null': req.query[key] = null; break; } }); next(); }); app.use(require('body-parser').json()); require('../lib/control/cookbook').attach(app); require('../lib/control/directory').attach(app); require('../lib/control/status').attach(app); try { // Try to clean up existing file handle if (FS.existsSync(Config.get('service:listen'))) { console.log('Trying to remove existing socket file ' + Config.get('service:listen')); FS.unlinkSync(Config.get('service:listen')); } } catch(e) { console.log('Error cleaning up socket file'); } server.listen(Config.get('service:listen'), function() { console.log('Listening for requests on ' + Config.get('service:listen')); });
var Express = require('express'); var FS = require('fs'); var HTTP = require('http'); require('../lib/config'); var app = Express(); var server = HTTP.createServer(app); app.use(require('body-parser').json()); require('../lib/control/cookbook').attach(app); require('../lib/control/directory').attach(app); require('../lib/control/status').attach(app); try { // Try to clean up existing file handle if (FS.existsSync(Config.get('service:listen'))) { console.log('Trying to remove existing socket file ' + Config.get('service:listen')); FS.unlinkSync(Config.get('service:listen')); } } catch(e) { console.log('Error cleaning up socket file'); } server.listen(Config.get('service:listen'), function() { console.log('Listening for requests on ' + Config.get('service:listen')); });
Allow json to be false
var Writable = require('stream').Writable; var loggly = require('loggly'); var util = require('util'); var extend = util._extend; module.exports = LogglyStream; util.inherits(LogglyStream, Writable); function LogglyStream (options) { if (!(this instanceof LogglyStream)) { return new LogglyStream(options) } Writable.call(this, extend({ decodeStrings: false, objectMode: true}, options)); // // Remark: we are assuming object streams here so JSON is true // unless json is explictly set to false // if (options.json !== false) { options = extend(options, { json: true }); } this.loggly = loggly.createClient(options); }; LogglyStream.prototype._write = function (data, encoding, callback) { // // Remark we are going to do fire and forget style cause otherwise it will // cause backpressue and fuck that shit. Also allow tags to be on the data // object for easy addition // this.loggly.log(data, data.tags); callback(); };
var Writable = require('stream').Writable; var loggly = require('loggly'); var util = require('util'); var extend = util._extend; module.exports = LogglyStream; util.inherits(LogglyStream, Writable); function LogglyStream (options) { if (!(this instanceof LogglyStream)) { return new LogglyStream(options) } Writable.call(this, extend({ decodeStrings: false, objectMode: true}, options)); // // Remark: we are assuming object streams here so JSON is true // options = extend(options, { json: true }); this.loggly = loggly.createClient(options); }; LogglyStream.prototype._write = function (data, encoding, callback) { // // Remark we are going to do fire and forget style cause otherwise it will // cause backpressue and fuck that shit. Also allow tags to be on the data // object for easy addition // this.loggly.log(data, data.tags); callback(); };
Update strict to error if present since it is redundant in modules, and not really necessary in demo pages.
module.exports = { "extends": "./index.js", "parser": "babel-eslint", "env": { "browser": true }, "plugins": [ "lit", "html" ], "globals": { "D2L": false }, "rules": { "strict": [2, "never"], "lit/no-duplicate-template-bindings": 2, "lit/no-legacy-template-syntax": 2, "lit/no-template-bind": 2, "lit/no-template-map": 0, "lit/no-useless-template-literals": 2, "lit/attribute-value-entities": 2, "lit/binding-positions": 2, "lit/no-property-change-update": 2, "lit/no-invalid-html": 2, "lit/no-value-attribute": 2 } };
module.exports = { "extends": "./index.js", "parser": "babel-eslint", "env": { "browser": true }, "plugins": [ "lit", "html" ], "globals": { "D2L": false }, "rules": { "strict": 0, "lit/no-duplicate-template-bindings": 2, "lit/no-legacy-template-syntax": 2, "lit/no-template-bind": 2, "lit/no-template-map": 0, "lit/no-useless-template-literals": 2, "lit/attribute-value-entities": 2, "lit/binding-positions": 2, "lit/no-property-change-update": 2, "lit/no-invalid-html": 2, "lit/no-value-attribute": 2 } };
Add twitter and Facebook links
controllers.controller('HomeCtrl', function($scope, Settings, AdUtil) { function showHomeAd() { if(AdMob){//Because android need this on start up apparently var platform = Settings.getPlatformSettings(); console.log('<GFF> HomeCtrl showHomeAd Banner AdUnit: ' + platform.developerBanner ); AdUtil.showBannerAd( platform.developerBanner ); } } $scope.$on('$ionicView.enter', showHomeAd ); ionic.Platform.ready( showHomeAd );//Because view events do not appear to fire when the view first loads $scope.onEmailTap = function(){ window.open('mailto:support@giveforfreeonline.org', '_system', 'location=yes'); return false; } $scope.onFacebookTap = function(){ window.open('https://www.facebook.com/Give-For-Free-643061692510804/', '_system', 'location=yes'); return false; } $scope.onTwitterTap = function(){ window.open('https://twitter.com/_giveforfree_', '_system', 'location=yes'); return false; } });
controllers.controller('HomeCtrl', function($scope, Settings, AdUtil) { function showHomeAd() { if(AdMob){//Because android need this on start up apparently var platform = Settings.getPlatformSettings(); console.log('<GFF> HomeCtrl showHomeAd Banner AdUnit: ' + platform.developerBanner ); AdUtil.showBannerAd( platform.developerBanner ); } } $scope.$on('$ionicView.enter', showHomeAd ); ionic.Platform.ready( showHomeAd );//Because view events do not appear to fire when the view first loads $scope.onEmailTap = function(){ window.open('mailto:support@giveforfreeonline.org', '_system', 'location=yes'); return false; } $scope.onFacebookTap = function(){ window.open('http://www.facebook.com', '_system', 'location=yes'); return false; } $scope.onTwitterTap = function(){ window.open('http://www.twitter.com', '_system', 'location=yes'); return false; } });
Change synchronous readdir to a promise
'use strict'; var _ = require('lodash'); var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var glob = require('glob'); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testLanguage(language) { describe(language, function() { var filePath = utility.buildPath('markup', language, '*.expect.txt'), filenames = glob.sync(filePath); _.each(filenames, function(filename) { var testName = path.basename(filename, '.expect.txt'), sourceName = filename.replace(/\.expect/, ''); it(`should markup ${testName}`, function(done) { var sourceFile = fs.readFileAsync(sourceName, 'utf-8'), expectedFile = fs.readFileAsync(filename, 'utf-8'); bluebird.join(sourceFile, expectedFile, function(source, expected) { var actual = hljs.highlight(language, source).value; actual.trim().should.equal(expected.trim()); done(); }); }); }); }); } describe('hljs.highlight()', function() { var markupPath = utility.buildPath('markup'); return fs.readdirAsync(markupPath).each(testLanguage); });
'use strict'; var _ = require('lodash'); var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var glob = require('glob'); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testLanguage(language) { describe(language, function() { var filePath = utility.buildPath('markup', language, '*.expect.txt'), filenames = glob.sync(filePath); _.each(filenames, function(filename) { var testName = path.basename(filename, '.expect.txt'), sourceName = filename.replace(/\.expect/, ''); it(`should markup ${testName}`, function(done) { var sourceFile = fs.readFileAsync(sourceName, 'utf-8'), expectedFile = fs.readFileAsync(filename, 'utf-8'); bluebird.join(sourceFile, expectedFile, function(source, expected) { var actual = hljs.highlight(language, source).value; actual.trim().should.equal(expected.trim()); done(); }); }); }); }); } describe('hljs.highlight()', function() { var languages = fs.readdirSync(utility.buildPath('markup')); _.each(languages, testLanguage, this); });
Fix noVNC not doing initial screen update by simulating a keypress after 2 seconds
<?php $id = rand(0,100000); echo(" <html> <body> <style> #noVNC_screen_".$id." { width: 100%; height: 100%; } html, body { margin: 0; } </style> <script src=\"util.js\"></script> <div id=\"noVNC_screen_".$id."\"> <canvas id=\"noVNC_canvas_".$id."\"></canvas> </div> <script> INCLUDE_URI = ''; Util.load_scripts(['webutil.js', 'base64.js', 'websock.js', 'des.js', 'input.js', 'display.js', 'jsunzip.js', 'rfb.js']); var rfb_".$id."; window.onscriptsload = function () { rfb_".$id." = new RFB({'target': \$D('noVNC_canvas_".$id."'), 'view_only': false }); rfb_".$id.".connect('".$_GET["host"]."', '".$_GET["port"]."', '".$_GET["password"]."', ''); setTimeout('rfb_".$id.".sendKey();', 2000); }; </script> </body> </html> "); ?>
<?php $id = rand(0,100000); echo(" <html> <body> <style> #noVNC_screen_".$id." { width: 100%; height: 100%; } html, body { margin: 0; } </style> <script src=\"util.js\"></script> <div id=\"noVNC_screen_".$id."\"> <canvas id=\"noVNC_canvas_".$id."\"></canvas> </div> <script> INCLUDE_URI = ''; Util.load_scripts(['webutil.js', 'base64.js', 'websock.js', 'des.js', 'input.js', 'display.js', 'jsunzip.js', 'rfb.js']); var rfb_".$id."; window.onscriptsload = function () { rfb_".$id." = new RFB({'target': \$D('noVNC_canvas_".$id."'), 'view_only': false }); rfb_".$id.".connect('".$_GET["host"]."', '".$_GET["port"]."', '".$_GET["password"]."', ''); }; </script> </body> </html> "); ?>
Add optional username & password parameters to login helper.
/** * Helper methods and variables for capser test suite. */ // Define the url for all tests. var url = casper.cli.get('url'); // Set default viewport for all tests. casper.options.viewportSize = { width: 1280, height: 1024 }; // Use to log in before performing a test. casper.login = function(username, password) { // If no arguments are given, log in using default test account username = typeof username == "string" ? username : "QA_TEST_ACCOUNT@example.com"; password = typeof password == "string" ? password : "QA_TEST_ACCOUNT"; this.echo("Logging in as: " + username); // Go home and login. casper.thenOpen(url + "/user", function() { this.fill('form[action="/user/login"]', { name: username, pass: password }, true); }); } // Use to log out after completing a test. casper.logout = function() { // Go home and click the "Log Out" button casper.thenOpen(url + "/user/logout", function() { this.echo("Logging out of test user."); }); } // We want to clear session after every test. casper.test.tearDown(function() { phantom.clearCookies(); })
/** * Helper methods and variables for capser test suite. */ // Define the url for all tests. var url = casper.cli.get('url'); // Set default viewport for all tests. casper.options.viewportSize = { width: 1280, height: 1024 }; // Use to log in before performing a test. casper.login = function() { this.echo("Logging in as test user."); // Go home and login. casper.thenOpen(url + "/user", function() { this.fill('form[action="/user/login"]', { name: 'QA_TEST_ACCOUNT@example.com', pass: 'QA_TEST_ACCOUNT' }, true); }); } // Use to log out after completing a test. casper.logout = function() { // Go home and click the "Log Out" button casper.thenOpen(url + "/user/logout", function() { this.echo("Logging out of test user."); }); } // We want to clear session after every test. casper.test.tearDown(function() { phantom.clearCookies(); })
Change the version to be the release version
from setuptools import setup, find_packages setup( name = 'django-globals', version = '0.2.1', description = 'Very simple application, that allow to define a thread specific global variables.', keywords = 'django apps', license = 'New BSD License', author = 'Alexander Artemenko', author_email = 'svetlyak.40wt@gmail.com', url = 'http://github.com/svetlyak40wt/django-globals/', install_requires = [], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Plugins', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], package_dir = {'': 'src'}, packages = find_packages('src', exclude = ['example']), include_package_data = True, )
from setuptools import setup, find_packages setup( name = 'django-globals', version = '0.2.1-rc1', description = 'Very simple application, that allow to define a thread specific global variables.', keywords = 'django apps', license = 'New BSD License', author = 'Alexander Artemenko', author_email = 'svetlyak.40wt@gmail.com', url = 'http://github.com/svetlyak40wt/django-globals/', install_requires = [], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Plugins', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], package_dir = {'': 'src'}, packages = find_packages('src', exclude = ['example']), include_package_data = True, )
Fix typo in statsd stat
// statsd/index.js // Setup some statsd stuff for qb // vendor var StatsD = require('node-statsd').StatsD exports.enable = function (qb, statsdconf) { var statsd = new StatsD(statsdconf.host, statsdconf.port) , prefix = statsdconf.prefix setInterval(function () { statsd.increment(prefix + '.heartbeat') }, statsdconf.heartbeat) // Setup some qb listeners to track progress qb.post('push', function (type, task, next) { statsd.increment([prefix, type, 'push'].join('.')) next() }) qb.post('process', function (type, task, next) { statsd.increment([prefix, type, 'process'].join('.')) next() }) qb.on('finish', function (type, task, next) { statsd.increment([prefix, type, 'success'].join('.')) next() }) qb.on('fail', function (type, task, next) { statsd.increment([prefix, type, 'failure'].join('.')) next() }) qb._statsd = statsd return statsd }
// statsd/index.js // Setup some statsd stuff for qb // vendor var StatsD = require('node-statsd').StatsD exports.enable = function (qb, statsdconf) { var statsd = new StatsD(statsdconf.host, statsdconf.port) , prefix = statsdconf.prefix setInterval(function () { statsd.increment(prefix + '.heartbeat') }, statsdconf.heartbeat) // Setup some qb listeners to track progress qb.post('push', function (type, task, next) { statsd.increment([prefix, type, 'push'].join('.')) next() }) qb.post('process', function (type, task, next) { statsd.increment([prefix, type, 'push'].join('.')) next() }) qb.on('finish', function (type, task, next) { statsd.increment([prefix, type, 'success'].join('.')) next() }) qb.on('fail', function (type, task, next) { statsd.increment([prefix, type, 'failure'].join('.')) next() }) qb._statsd = statsd return statsd }
Remove the .dev from version.
from setuptools import setup, find_packages with open('README.md') as fhandle: long_description = fhandle.read() setup( name='buckets', version='1.0.0', description='managing data by relevancy.', long_description=long_description, url="https://github.com/bdastur/spam", author="Behzad Dastur", author_email="bdastur@gmail.com", license='Apache Software License', classifier=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: Apache Software License', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS', ], keywords='buckets utility ', py_modules=['buckets'] )
from setuptools import setup, find_packages with open('README.md') as fhandle: long_description = fhandle.read() setup( name='buckets', version='1.0.0.dev', description='managing data by relevancy.', long_description=long_description, url="https://github.com/bdastur/spam", author="Behzad Dastur", author_email="bdastur@gmail.com", license='Apache Software License', classifier=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: Apache Software License', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS', ], keywords='buckets utility ', py_modules=['buckets'] )
Switch off a browsersync label
/** * Start browserSync server */ 'use strict'; const gulp = require('gulp'), fs = require('fs'); module.exports = function(options) { return () => { // If index.html exist - open it, else show folder let listDirectory = fs.existsSync(options.mainHtml) ? false : true; options.browserSync.init({ notify: false, server: { baseDir: "./", directory: listDirectory }, snippetOptions: { // Provide a custom Regex for inserting the snippet rule: { match: /$/i, fn: (snippet, match) => snippet + match } }, port: 8080 }); }; };
/** * Start browserSync server */ 'use strict'; const gulp = require('gulp'), fs = require('fs'); module.exports = function(options) { return () => { // If index.html exist - open it, else show folder let listDirectory = fs.existsSync(options.mainHtml) ? false : true; options.browserSync.init({ server: { baseDir: "./", directory: listDirectory }, snippetOptions: { // Provide a custom Regex for inserting the snippet rule: { match: /$/i, fn: (snippet, match) => snippet + match } }, port: 8080 }); }; };
Add option to silence warnings from environment plugin If a process.env variable is is added to the EnvironmentPlugin but not defined, it is reported in the terminal as: `WARNING in NODE_ENV environment variable is undefined.` This pull request adds an option as the second argument to EnvironmentPlugin to silence the warnings. Example: ```js plugins: [ new webpack.EnvironmentPlugin([ 'NODE_ENV', ], true), ], ```
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Simen Brekken @simenbrekken */ var DefinePlugin = require("./DefinePlugin"); function EnvironmentPlugin(keys, silent) { this.keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments); this.silent = silent } module.exports = EnvironmentPlugin; EnvironmentPlugin.prototype.apply = function(compiler) { compiler.apply(new DefinePlugin(this.keys.reduce(function(definitions, key) { var value = process.env[key]; if(value === undefined && !this.silent) { compiler.plugin("this-compilation", function(compilation) { var error = new Error(key + " environment variable is undefined."); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } definitions["process.env." + key] = value ? JSON.stringify(value) : "undefined"; return definitions; }.bind(this), {}))); };
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Simen Brekken @simenbrekken */ var DefinePlugin = require("./DefinePlugin"); function EnvironmentPlugin(keys) { this.keys = Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments); } module.exports = EnvironmentPlugin; EnvironmentPlugin.prototype.apply = function(compiler) { compiler.apply(new DefinePlugin(this.keys.reduce(function(definitions, key) { var value = process.env[key]; if(value === undefined) { compiler.plugin("this-compilation", function(compilation) { var error = new Error(key + " environment variable is undefined."); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } definitions["process.env." + key] = value ? JSON.stringify(value) : "undefined"; return definitions; }, {}))); };
Add a comment for log.
package study.hard.javalib.file; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FileTest { FileHandler fileHandler; File tempFile; @Before public void setUp() { fileHandler = new FileHandler(); } @Test public void testCreateTempFile() throws IOException { tempFile = fileHandler.getTempFile("TEST_TEMP_FILE.txt"); System.out.println("Absolute path of temporary file: " + tempFile.getAbsolutePath()); } @Test public void testGetTempDirectoryPath() { File tempDirectory = new File(System.getProperty("java.io.tmpdir")); System.out.println("Absolute path of temporary directory: " + tempDirectory); } @After public void clean() { if (tempFile != null) { tempFile.delete(); } } }
package study.hard.javalib.file; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FileTest { FileHandler fileHandler; File tempFile; @Before public void setUp() { fileHandler = new FileHandler(); } @Test public void testCreateTempFile() throws IOException { tempFile = fileHandler.getTempFile("TEST_TEMP_FILE.txt"); System.out.println("Absolute path of temporary file: " + tempFile.getAbsolutePath()); } @Test public void testGetTempDirectoryPath() { File tempDirectory = new File(System.getProperty("java.io.tmpdir")); System.out.println(tempDirectory); } @After public void clean() { if (tempFile != null) { tempFile.delete(); } } }
Remove reference to "Viewer" in modal
PDRClient.directive('permissionsInfo', function() { return { restrict: 'E', transclude: true, scope: { content: '@', placement: '@' }, controller: ['$scope', '$rootScope', '$timeout', function($scope, $rootScope, $timeout) { $timeout(function(){ $("[data-toggle=requestPopover]").popover({ html : true, placement: $scope.placement, trigger: 'hover', content: "<i class='fa fa-bullhorn'></i><span>Facilitator</span><p>Facilitators share responsibility with the district facilitator to contact participants and view their individual responses, facilitate the consensus meeting, and view the final consensus report.</p><i class='fa fa-pencil-square-o'></i><span>Participant</span><p>Participants responds to the individual readiness assessment survey and take part of the consensus meeting. They can view the final consensus report</p>" }); }); }], templateUrl: 'client/views/directives/help_info_popover.html' } });
PDRClient.directive('permissionsInfo', function() { return { restrict: 'E', transclude: true, scope: { content: '@', placement: '@' }, controller: ['$scope', '$rootScope', '$timeout', function($scope, $rootScope, $timeout) { $timeout(function(){ $("[data-toggle=requestPopover]").popover({ html : true, placement: $scope.placement, trigger: 'hover', content: "<i class='fa fa-bullhorn'></i><span>Facilitator</span><p>Facilitators share responsibility with the district facilitator to contact participants and view their individual responses, facilitate the consensus meeting, and view the final consensus report.</p><i class='fa fa-pencil-square-o'></i><span>Participant</span><p>Participants responds to the individual readiness assessment survey and take part of the consensus meeting. They can view the final consensus report</p><i class='fa fa-eye'></i><span>Viewer</span><p>Viewers have read-only access to the final consensus report. They cannot view individual participant responses or data.</p>" }); }); }], templateUrl: 'client/views/directives/help_info_popover.html' } });
Replace `tmpdir` with `tmp_path` in `samp` tests
from astropy.samp import conf from astropy.samp.hub import SAMPHubServer from astropy.samp.hub_proxy import SAMPHubProxy def setup_module(module): conf.use_internet = False class TestHubProxy: def setup_method(self, method): self.hub = SAMPHubServer(web_profile=False, mode='multiple', pool_size=1) self.hub.start() self.proxy = SAMPHubProxy() self.proxy.connect(hub=self.hub, pool_size=1) def teardown_method(self, method): if self.proxy.is_connected: self.proxy.disconnect() self.hub.stop() def test_is_connected(self): assert self.proxy.is_connected def test_disconnect(self): self.proxy.disconnect() def test_ping(self): self.proxy.ping() def test_registration(self): result = self.proxy.register(self.proxy.lockfile["samp.secret"]) self.proxy.unregister(result['samp.private-key']) def test_custom_lockfile(tmp_path): lockfile = str(tmp_path / '.samptest') hub = SAMPHubServer(web_profile=False, lockfile=lockfile, pool_size=1) hub.start() proxy = SAMPHubProxy() proxy.connect(hub=hub, pool_size=1) hub.stop()
from astropy.samp import conf from astropy.samp.hub import SAMPHubServer from astropy.samp.hub_proxy import SAMPHubProxy def setup_module(module): conf.use_internet = False class TestHubProxy: def setup_method(self, method): self.hub = SAMPHubServer(web_profile=False, mode='multiple', pool_size=1) self.hub.start() self.proxy = SAMPHubProxy() self.proxy.connect(hub=self.hub, pool_size=1) def teardown_method(self, method): if self.proxy.is_connected: self.proxy.disconnect() self.hub.stop() def test_is_connected(self): assert self.proxy.is_connected def test_disconnect(self): self.proxy.disconnect() def test_ping(self): self.proxy.ping() def test_registration(self): result = self.proxy.register(self.proxy.lockfile["samp.secret"]) self.proxy.unregister(result['samp.private-key']) def test_custom_lockfile(tmpdir): lockfile = tmpdir.join('.samptest').realpath().strpath hub = SAMPHubServer(web_profile=False, lockfile=lockfile, pool_size=1) hub.start() proxy = SAMPHubProxy() proxy.connect(hub=hub, pool_size=1) hub.stop()
Modify .scss files to compile
var gulp = require('gulp'); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var uglify = require('gulp-uglify'); var pump = require('pump'); var cleanCSS = require('gulp-clean-css'); var imagemin = require('gulp-imagemin'); gulp.task('sass', function() { return gulp.src('src/sass/main.scss') .pipe(sass()) .pipe(autoprefixer({ browsers: ['last 3 versions'] })) .pipe(cleanCSS()) .pipe(gulp.dest('build/css')); }); gulp.task('uglify-js', function() { pump([ gulp.src('src/js/*.js'), uglify(), gulp.dest('build/js') ]); }); gulp.task('html', function() { return gulp.src('src/index.html').pipe(gulp.dest('build')); }); gulp.task('default', function() { gulp.watch('src/sass/*.scss', ['sass']); gulp.watch('src/js/*.js', ['uglify-js']); gulp.watch('src/index.html', ['html']); gulp.src('src/img/*') .pipe(imagemin()) .pipe(gulp.dest('build/img')); });
var gulp = require('gulp'); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var uglify = require('gulp-uglify'); var pump = require('pump'); var cleanCSS = require('gulp-clean-css'); var imagemin = require('gulp-imagemin'); gulp.task('sass', function() { return gulp.src('src/sass/*.scss') .pipe(sass()) .pipe(autoprefixer({ browsers: ['last 3 versions'] })) .pipe(cleanCSS()) .pipe(gulp.dest('build/css')); }); gulp.task('uglify-js', function() { pump([ gulp.src('src/js/*.js'), uglify(), gulp.dest('build/js') ]); }); gulp.task('html', function() { return gulp.src('src/index.html').pipe(gulp.dest('build')); }); gulp.task('default', function() { gulp.watch('src/sass/*.scss', ['sass']); gulp.watch('src/js/*.js', ['uglify-js']); gulp.watch('src/index.html', ['html']); gulp.src('src/img/*') .pipe(imagemin()) .pipe(gulp.dest('build/img')); });
Fix migration on conpherence images
<?php // Rebuild all Conpherence Room images to profile standards // $table = new ConpherenceThread(); $conn = $table->establishConnection('w'); $table_name = 'conpherence_thread'; foreach (new LiskRawMigrationIterator($conn, $table_name) as $row) { $images = phutil_json_decode($row['imagePHIDs']); if (!$images) { continue; } $file_phid = idx($images, 'original'); $file = id(new PhabricatorFileQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($file_phid)) ->executeOne(); $xform = PhabricatorFileTransform::getTransformByKey( PhabricatorFileThumbnailTransform::TRANSFORM_PROFILE); $xformed = $xform->executeTransform($file); $new_phid = $xformed->getPHID(); queryfx( $conn, 'UPDATE %T SET profileImagePHID = %s WHERE id = %d', $table->getTableName(), $new_phid, $row['id']); }
<?php // Rebuild all Conpherence Room images to profile standards // $table = new ConpherenceThread(); $conn = $table->establishConnection('w'); $table_name = 'conpherence_thread'; foreach (new LiskRawMigrationIterator($conn, $table_name) as $row) { $images = phutil_json_decode($row['imagePHIDs']); if (!$images) { return; } $file_phid = idx($images, 'original'); $file = id(new PhabricatorFileQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($file_phid)) ->executeOne(); $xform = PhabricatorFileTransform::getTransformByKey( PhabricatorFileThumbnailTransform::TRANSFORM_PROFILE); $xformed = $xform->executeTransform($file); $new_phid = $xformed->getPHID(); queryfx( $conn, 'UPDATE %T SET profileImagePHID = %s WHERE id = %d', $table->getTableName(), $new_phid, $row['id']); }
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); } }
Add check whether test runs under maven
package to.etc.testutil; import java.io.BufferedReader; import java.io.InputStreamReader; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 15-04-22. */ final public class TestUtil { private static boolean m_mavenTest; private TestUtil() { } public static void nonTestPrintln(String text) { if(!inTest()) System.out.println(text); } static public boolean inTest() { return System.getProperty("surefire.real.class.path") != null || System.getProperty("surefire.test.class.path") != null; } static public String getGitBranch() { try { Process process = Runtime.getRuntime().exec("git rev-parse --abbrev-ref HEAD"); process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); return reader.readLine(); } catch(Exception x) { return null; } } static public void main(String[] args) { System.out.println("branch: " + getGitBranch()); } public static synchronized boolean isMavenTest() { Boolean mavenTest = m_mavenTest; if(null == mavenTest) { mavenTest = m_mavenTest = System.getProperty("surefire.real.class.path") != null || System.getProperty("surefire.test.class.path") != null; } return mavenTest; } }
package to.etc.testutil; import java.io.BufferedReader; import java.io.InputStreamReader; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 15-04-22. */ final public class TestUtil { private TestUtil() { } public static void nonTestPrintln(String text) { if(!inTest()) System.out.println(text); } static public boolean inTest() { return System.getProperty("surefire.real.class.path") != null || System.getProperty("surefire.test.class.path") != null; } static public String getGitBranch() { try { Process process = Runtime.getRuntime().exec("git rev-parse --abbrev-ref HEAD"); process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); return reader.readLine(); } catch(Exception x) { return null; } } static public void main(String[] args) { System.out.println("branch: " + getGitBranch()); } }
Verify in a layout test that replacing a notification closes the old one. We do this by listening to the "close" event on the old notification as well. This test passes with or without the Chrome-sided fix because it's properly implemented in the LayoutTestNotificationManager, but is a good way of verifying the fix manually. BUG=366098 Review URL: https://codereview.chromium.org/750563005 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@186033 bbb929c8-8fbe-4397-9dbb-9b2b20218538
if (self.importScripts) { importScripts('/resources/testharness.js'); importScripts('worker-helpers.js'); } async_test(function(test) { if (Notification.permission != 'granted') { assert_unreached('No permission has been granted for displaying notifications.'); return; } // We require two asynchronous events to happen when a notification gets updated, (1) // the old instance should receive the "close" event, and (2) the new notification // should receive the "show" event, but only after (1) has happened. var closedOriginalNotification = false; var notification = new Notification('My Notification', { tag: 'notification-test' }); notification.addEventListener('show', function() { var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' }); updatedNotification.addEventListener('show', function() { assert_true(closedOriginalNotification); test.done(); }); }); notification.addEventListener('close', function() { closedOriginalNotification = true; }); notification.addEventListener('error', function() { assert_unreached('The error event should not be thrown.'); }); }, 'Replacing a notification will discard the previous notification.'); if (isDedicatedOrSharedWorker()) done();
if (self.importScripts) { importScripts('/resources/testharness.js'); importScripts('worker-helpers.js'); } async_test(function(test) { if (Notification.permission != 'granted') { assert_unreached('No permission has been granted for displaying notifications.'); return; } var notification = new Notification('My Notification', { tag: 'notification-test' }); notification.addEventListener('show', function() { var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' }); updatedNotification.addEventListener('show', function() { test.done(); }); }); // FIXME: Replacing a notification should fire the close event on the // notification that's being replaced. notification.addEventListener('error', function() { assert_unreached('The error event should not be thrown.'); }); }, 'Replacing a notification will discard the previous notification.'); if (isDedicatedOrSharedWorker()) done();
Make duration optional to create a Job
#!/usr/bin/env python3 from dateutil import parser class Job: def __init__(self, category, id, status, start_timestamp, finish_timestamp, duration = None): self.tool_id = category.tool self.type_id = category.context self.id = id self.status_bit = int(status) self.start_timestamp = parser.parse(start_timestamp) self.finish_timestamp = parser.parse(finish_timestamp) self.duration_seconds = (self.finish_timestamp - self.start_timestamp).total_seconds() if duration is None else (int(duration) / float(1000)) @property def timestamp(self): return self.finish_timestamp @property def tool(self): return self.tool_id @property def type(self): return self.type_id @property def status(self): return self.status_bit @property def duration(self): return self.duration_seconds
#!/usr/bin/env python3 from dateutil import parser class Job: def __init__(self, category, id, status, start_timestamp, finish_timestamp, duration): self.tool_id = category.tool self.type_id = category.context self.id = id self.status_bit = int(status) self.start_timestamp = parser.parse(start_timestamp) self.finish_timestamp = parser.parse(finish_timestamp) self.duration_seconds = (int(duration) / float(1000)) if duration else (self.finish_timestamp - self.start_timestamp).total_seconds() @property def timestamp(self): return self.finish_timestamp @property def tool(self): return self.tool_id @property def type(self): return self.type_id @property def status(self): return self.status_bit @property def duration(self): return self.duration_seconds
Fix missing newline at EOF
from abundsolar import elsolarlogepsilon zfactor = 10 ** -1.92 # Smith et al. (2000) ROA 219 in Omega Centauri # [Fe/H] is about ~-1.7 #logxtofe = log epsilon(X) - log epsilon(Fe) targetlogxtofe = {'rb': 1.34 - 6.25, 'y': 1.15 - 6.25, 'zr': 2.01 - 6.25, 'ba': 1.88 - 6.25, 'la': 0.75 - 6.25, 'ce': 0.42 - 6.25, 'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066 }
from abundsolar import elsolarlogepsilon zfactor = 10 ** -1.92 # Smith et al. (2000) ROA 219 in Omega Centauri # [Fe/H] is about ~-1.7 #logxtofe = log epsilon(X) - log epsilon(Fe) targetlogxtofe = {'rb': 1.34 - 6.25, 'y': 1.15 - 6.25, 'zr': 2.01 - 6.25, 'ba': 1.88 - 6.25, 'la': 0.75 - 6.25, 'ce': 0.42 - 6.25, 'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066 }
Fix the data point mapper Javadoc
package org.openmhealth.shim.common; import org.openmhealth.schema.domain.omh.DataPoint; import java.util.ArrayList; import java.util.List; /** * A mapper that takes one or more inputs and creates data points. * * @param <DP> the body type of the data points to create * @param <I> the input type * @author Emerson Farrugia */ public interface DataPointMapper<DP extends DataPoint, I> { List<DP> asDataPoints(I input); /** * By default, handle each input individually. */ default List<DP> asDataPoints(List<I> input) { List<DP> dataPoints = new ArrayList<>(); for (I i : input) { dataPoints.addAll(asDataPoints(i)); } return dataPoints; } }
package org.openmhealth.shim.common; import org.openmhealth.schema.domain.omh.DataPoint; import java.util.ArrayList; import java.util.List; /** * A mapper that takes a generic input and creates data points. * * @param <DP> the body type of the data points to create * @param <I> the input type * @author Emerson Farrugia */ public interface DataPointMapper<DP extends DataPoint, I> { List<DP> asDataPoints(I input); /** * By default, handle each input individually. */ default List<DP> asDataPoints(List<I> input) { List<DP> dataPoints = new ArrayList<>(); for (I i : input) { dataPoints.addAll(asDataPoints(i)); } return dataPoints; } }
Allow some tests to create more then 1 shard. This is needed when we want to test things with a routing param.
<?php namespace Elastica\Test; use Elastica\Client; class Base extends \PHPUnit_Framework_TestCase { protected function _getClient() { return new Client(); } /** * @param string $name Index name * @param bool $delete Delete index if it exists * @param int $shards Number of shards to create * @return \Elastica\Index */ protected function _createIndex($name = 'test', $delete = true, $shards = 1) { $client = $this->_getClient(); $index = $client->getIndex('elastica_' . $name); $index->create(array('index' => array('number_of_shards' => $shards, 'number_of_replicas' => 0)), $delete); return $index; } }
<?php namespace Elastica\Test; use Elastica\Client; class Base extends \PHPUnit_Framework_TestCase { protected function _getClient() { return new Client(); } /** * @param string $name Index name * @param bool $delete Delete index if it exists * @return \Elastica\Index */ protected function _createIndex($name = 'test', $delete = true) { $client = $this->_getClient(); $index = $client->getIndex('elastica_' . $name); $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), $delete); return $index; } }
Update unit test for `Address`.
<?PHP /** * An Address value object. * * This Value Object use commerceguys/addressing library * (https://github.com/commerceguys/addressing). * * Other useful libraries: * - https://github.com/black-project/Address * - https://github.com/adamlc/address-format * * @package Serendipity\Framework * @subpackage ValueObjects * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Tests\Address; use SerendipityHQ\Component\ValueObjects\Address\Address; class AddressTest extends \PHPUnit_Framework_TestCase { public function testAddress() { $options = [ 'locale' => 'en_EN' ]; $resource = new Address($options); } }
<?PHP /** * An Address value object. * * This Value Object use commerceguys/addressing library * (https://github.com/commerceguys/addressing). * * Other useful libraries: * - https://github.com/black-project/Address * - https://github.com/adamlc/address-format * * @package Serendipity\Framework * @subpackage ValueObjects * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Tests\Address; use SerendipityHQ\Component\ValueObjects\Address\Address; class AddressTest extends \PHPUnit_Framework_TestCase { public function testAddress() { $options = [ 'locale' => 'en_EN' ]; $resource = new Address($options); $this->assertEquals($options['locale'], $resource->getLocale()); } }
Make sure we check data.expires is a number
'use strict'; class Keyv { constructor(opts) { this.opts = opts || {}; this.opts.store = this.opts.store || new Map(); } get(key) { const store = this.opts.store; return Promise.resolve(store.get(key)).then(data => { if (data === undefined) { return undefined; } if (!store.ttlSupport && typeof data.expires === 'number' && Date.now() > data.expires) { this.delete(key); return undefined; } return store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { ttl = ttl || this.opts.ttl; const store = this.opts.store; let set; if (store.ttlSupport) { set = store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { const store = this.opts.store; return Promise.resolve(store.delete(key)); } clear() { const store = this.opts.store; return Promise.resolve(store.clear()); } } module.exports = Keyv;
'use strict'; class Keyv { constructor(opts) { this.opts = opts || {}; this.opts.store = this.opts.store || new Map(); } get(key) { const store = this.opts.store; return Promise.resolve(store.get(key)).then(data => { if (data === undefined) { return undefined; } if (!store.ttlSupport && Date.now() > data.expires) { this.delete(key); return undefined; } return store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { ttl = ttl || this.opts.ttl; const store = this.opts.store; let set; if (store.ttlSupport) { set = store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { const store = this.opts.store; return Promise.resolve(store.delete(key)); } clear() { const store = this.opts.store; return Promise.resolve(store.clear()); } } module.exports = Keyv;