text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use Case for persona b (pet seeker)
<!DOCTYPE html> <head> <title>Conceptual-Model</title> </head> <body> <main> <h2>Entities and Attributes</h2> <p><strong>Profile</strong></p> <ul> <li>profileId</li> <li>profileAtHandle</li> <li>profileEmail</li> <li>profilePhone</li> </ul> <p><strong>Pet Profile</strong></p> <ul> <li>petId</li> <li>petProfileId</li> <li>petDescription</li> <li>petType</li> <li>petBreed</li> <li>PetLocation</li> </ul> <p><strong>images</strong></p> <ul> <li>petProfileImage</li> </ul> <p><strong>Relations</strong></p> <ul> <li>One <strong>Profile </strong>favorites products - (m to n)</li> </ul> <br> <img src="https://bootcamp-coders.cnm.edu/~mharrison13/data-design/public_html/images/erd-data-design.svg"> </main> </body>
<!DOCTYPE html> <head> <title>Conceptual-Model</title> </head> <body> <main> <h2>Entities and Attributes</h2> <p><strong>User Profile</strong></p> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <p>Pet Profile</p> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <p><strong>Favorite</strong></p> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <p><strong>Relations</strong></p> <ul> <li>One <strong>Profile </strong>favorites products - (m to n)</li> </ul> <br> <img src="https://bootcamp-coders.cnm.edu/~mharrison13/data-design/public_html/images/erd-data-design.svg"> </main> </body>
Handle invalid / absent credentials
'use strict'; var _ = require('lodash'); var Store = require('../core/Store'); var Dispatcher = require('../core/Dispatcher'); var ActionTypes = require('../constants/ActionTypes'); /** * @typedef Credentials * @type {object} * @property {string} keyId * @property {string} keySecret */ var _credentials; var LOCAL_STORAGE_VAR = 'scalrCredentials'; var fromLocalStorage = function () { if (typeof localStorage === 'undefined') { return null; } try { var storedCredentials = JSON.parse(localStorage[LOCAL_STORAGE_VAR]); if (_.isObject(storedCredentials)) { return storedCredentials; } } catch (e) {} return {}; }; var toLocalStorage = function (credentials) { localStorage[LOCAL_STORAGE_VAR] = JSON.stringify(credentials); }; var CredentialsStore = new Store({ /** * @returns {Credentials} */ get() { return _credentials || _.merge({},require('../constants/Settings').defaults.credentials, fromLocalStorage()); }, set(credentials) { _credentials = credentials; toLocalStorage(credentials); } }); CredentialsStore.dispatcherToken = Dispatcher.register(payload => { var action = payload.action; if (action.actionType == ActionTypes.SET_CREDENTIALS) { CredentialsStore.set(action.credentials); CredentialsStore.emitChange(); } }); module.exports = CredentialsStore;
'use strict'; var Store = require('../core/Store'); var Dispatcher = require('../core/Dispatcher'); var ActionTypes = require('../constants/ActionTypes'); /** * @typedef Credentials * @type {object} * @property {string} keyId * @property {string} keySecret */ var _credentials; var LOCAL_STORAGE_VAR = 'scalrCredentials'; var fromLocalStorage = function () { if (typeof localStorage === 'undefined') { return null; } return JSON.parse(localStorage[LOCAL_STORAGE_VAR]); }; var toLocalStorage = function (credentials) { localStorage[LOCAL_STORAGE_VAR] = JSON.stringify(credentials); }; var CredentialsStore = new Store({ /** * @returns {Credentials} */ get() { // TODO - Error handling! return _credentials || fromLocalStorage() || require('../constants/Settings').defaults.credentials; }, set(credentials) { _credentials = credentials; toLocalStorage(credentials); } }); CredentialsStore.dispatcherToken = Dispatcher.register(payload => { var action = payload.action; if (action.actionType == ActionTypes.SET_CREDENTIALS) { CredentialsStore.set(action.credentials); CredentialsStore.emitChange(); } }); module.exports = CredentialsStore;
Update requests requirement from <2.23,>=2.4.2 to >=2.4.2,<2.24 Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version. - [Release notes](https://github.com/psf/requests/releases) - [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md) - [Commits](https://github.com/psf/requests/compare/v2.4.2...v2.23.0) Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.24', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.23', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Update copyright notice with MIT license
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --*/ package com.nasmlanguage; import com.intellij.lang.Language; import org.jetbrains.annotations.NotNull; public class NASMLanguage extends Language { public static final NASMLanguage INSTANCE = new NASMLanguage(); private NASMLanguage() { super("NASM"); } @NotNull @Override public String getDisplayName() { return "NASM Assembly Language"; } }
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury. All rights reserved. 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/>. --*/ package com.nasmlanguage; import com.intellij.lang.Language; import org.jetbrains.annotations.NotNull; public class NASMLanguage extends Language { public static final NASMLanguage INSTANCE = new NASMLanguage(); private NASMLanguage() { super("NASM"); } @NotNull @Override public String getDisplayName() { return "NASM Assembly Language"; } }
Fix error in on-connect emission of userstats
/* Created by 'myth' on July 3. 2015 CognacTime is licenced under the MIT licence. */ var log = require('./logging') var util = require('../client/util') // Start by defining the container object function iowrapper (io) { this.connections = [] this.io = io io.on('connection', function (socket) { log.info('Client connected: ' + socket.id) io.emit('stats', { users: io.engine.clientsCount }) socket.on('message', function (data) { log.info('Received message: ' + data) }) socket.on('fetch', function (data) { log.info('Received query: ' + util.repr(data)) }) socket.on('disconnect', function () { log.info('Client disconnected: ' + socket.id) }) }) } module.exports = iowrapper
/* Created by 'myth' on July 3. 2015 CognacTime is licenced under the MIT licence. */ var log = require('./logging') var util = require('../client/util') // Start by defining the container object function iowrapper (io) { this.connections = [] this.io = io io.on('connection', function (socket) { log.info('Client connected: ' + socket.id) socket.emit('stats', { users: io.engine.clientsCount }) socket.on('message', function (data) { log.info('Received message: ' + data) }) socket.on('fetch', function (data) { log.info('Received query: ' + util.repr(data)) }) socket.on('disconnect', function () { log.info('Client disconnected: ' + socket.id) }) }) } module.exports = iowrapper
Remove 'Increment in background' action as all the actions should be dispatched in background
import React, { Component, PropTypes } from 'react'; class Counter extends Component { render() { const { increment, incrementIfOdd, incrementAsync, decrement, state } = this.props; return ( <div> Clicked: <span className="counter">{state.counter.count}</span> times <div className="rule"></div> <button className="btn" onClick={increment}>+</button> {' '} <button className="btn" onClick={decrement}>-</button> <div className="rule"></div> <button className="btn" onClick={incrementIfOdd}>Increment if odd</button> <br /> <button className="btn" onClick={() => incrementAsync()}>Increment async</button> </div> ); } } Counter.propTypes = { increment: PropTypes.func.isRequired, incrementIfOdd: PropTypes.func.isRequired, incrementAsync: PropTypes.func.isRequired, decrement: PropTypes.func.isRequired, state: PropTypes.object.isRequired }; export default Counter;
import React, { Component, PropTypes } from 'react'; class Counter extends Component { render() { const { increment, incrementIfOdd, incrementAsync, bg, decrement, state } = this.props; return ( <div> Clicked: <span className="counter">{state.counter.count}</span> times <div className="rule"></div> <button className="btn" onClick={increment}>+</button> {' '} <button className="btn" onClick={decrement}>-</button> <div className="rule"></div> <button className="btn" onClick={incrementIfOdd}>Increment if odd</button> <br /> <button className="btn" onClick={() => incrementAsync()}>Increment async</button> <div className="rule"></div> <button className="btn" onClick={() => bg('increment')}>Increment in background</button> </div> ); } } Counter.propTypes = { increment: PropTypes.func.isRequired, incrementIfOdd: PropTypes.func.isRequired, incrementAsync: PropTypes.func.isRequired, bg: PropTypes.func.isRequired, decrement: PropTypes.func.isRequired, state: PropTypes.object.isRequired }; export default Counter;
Update auth tests to be compatible with Python 3
from __future__ import absolute_import import random import unittest from six.moves import input from .config import * from tweepy import API, OAuthHandler class TweepyAuthTests(unittest.TestCase): def testoauth(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.assertTrue(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assertTrue(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status('test %i' % random.randint(0, 1000)) api.destroy_status(s.id) def testaccesstype(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
from __future__ import absolute_import import random import unittest from .config import * from tweepy import API, OAuthHandler class TweepyAuthTests(unittest.TestCase): def testoauth(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = raw_input('PIN: ').strip() self.assertTrue(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assertTrue(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status('test %i' % random.randint(0, 1000)) api.destroy_status(s.id) def testaccesstype(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = raw_input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
Remove auth_request as no used Function auth_request() isn't be used, it can be removed for the code clean. Change-Id: I979b67e934c72f50dd62c75ac614f99f136cfeae
# Copyright 2014 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class FakeAuthProvider(object): def get_token(self): return "faketoken" def base_url(self, filters, auth_data=None): return "https://example.com"
# Copyright 2014 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class FakeAuthProvider(object): def auth_request(self, method, url, headers=None, body=None, filters=None): return url, headers, body def get_token(self): return "faketoken" def base_url(self, filters, auth_data=None): return "https://example.com"
Use INFO logging level in `bar git install`
package command import ( "github.com/akaspin/bar/client/git" "github.com/akaspin/bar/client/model" "github.com/akaspin/bar/client/transport" "github.com/spf13/cobra" "github.com/tamtam-im/logx" ) type GitInstallCmd struct { *Environment *CommonOptions // Installable logging level Log string } func (c *GitInstallCmd) Init(cc *cobra.Command) { cc.Use = "install" cc.Short = "install bar support into git repo" cc.Flags().StringVarP(&c.Log, "log", "", logx.INFO, "installable logging level") cc.Flags() } func (c *GitInstallCmd) Run(args ...string) (err error) { var mod *model.Model if mod, err = model.New(c.WD, true, c.ChunkSize, c.PoolSize); err != nil { return } defer mod.Close() trans := transport.NewTransport(mod, "", c.Endpoint, c.PoolSize) defer trans.Close() info, err := trans.ServerInfo() if err != nil { return } config := git.NewConfig(info, mod.Git) err = config.Install(c.Log) return }
package command import ( "github.com/akaspin/bar/client/git" "github.com/akaspin/bar/client/model" "github.com/akaspin/bar/client/transport" "github.com/spf13/cobra" "github.com/tamtam-im/logx" ) type GitInstallCmd struct { *Environment *CommonOptions // Installable logging level Log string } func (c *GitInstallCmd) Init(cc *cobra.Command) { cc.Use = "install" cc.Short = "install bar support into git repo" cc.Flags().StringVarP(&c.Log, "log", "", logx.DEBUG, "installable logging level") cc.Flags() } func (c *GitInstallCmd) Run(args ...string) (err error) { var mod *model.Model if mod, err = model.New(c.WD, true, c.ChunkSize, c.PoolSize); err != nil { return } defer mod.Close() trans := transport.NewTransport(mod, "", c.Endpoint, c.PoolSize) defer trans.Close() info, err := trans.ServerInfo() if err != nil { return } config := git.NewConfig(info, mod.Git) err = config.Install(c.Log) return }
Migrate content repo to @isaacphysics
'use strict'; define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() { /* Services */ angular.module('scooter.services', []) .constant('Repo', { owner: "isaacphysics", name: "isaac-content-2" }) .constant('ApiServer', "https://staging-2.isaacphysics.org/api/any/api") .service('LoginChecker', require("app/services/LoginChecker")) .factory('FileLoader', require("app/services/FileLoader")) .factory('FigureUploader', require("app/services/FigureUploader")) .service('SnippetLoader', require("app/services/SnippetLoader")) .factory('TagLoader', require("app/services/TagLoader")) .factory('IdLoader', require("app/services/IdLoader")) });
'use strict'; define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() { /* Services */ angular.module('scooter.services', []) .constant('Repo', { owner: "ucam-cl-dtg", name: "isaac-content-2" }) .constant('ApiServer', "https://staging-2.isaacphysics.org/api/any/api") .service('LoginChecker', require("app/services/LoginChecker")) .factory('FileLoader', require("app/services/FileLoader")) .factory('FigureUploader', require("app/services/FigureUploader")) .service('SnippetLoader', require("app/services/SnippetLoader")) .factory('TagLoader', require("app/services/TagLoader")) .factory('IdLoader', require("app/services/IdLoader")) });
Add new routes for components and serve them up to client side
require('dotenv').config(); const bodyParser = require('body-parser'); const metadata = require('../package.json'); const compression = require('compression'); const express = require('express'); const path = require('path'); const port = process.env.NODE_PORT; const secret = process.env.SESSION_SECRET; // const redisClient = redis.createClient(); const app = express(); app.use(bodyParser.json({limit: '40mb'})); app.use(compression()); // gzip compress all responses const routes = ['/', '/contact', '/portfolio', '/skills', '/', '/hackerwords', '/goolp', '/immerse', ]; for (const route of routes) { app.get(route, (req, res) => { res.sendFile(path.join(__dirname, '/../client/index.html')); }); } app.use(express.static(path.join(__dirname, '../client'))); // wildcard route app.get('*', function(req, res) { res.status(404).send('Not Found'); }); app.listen(port, () => { console.log(`🌎 Listening on port ${port} for app ${metadata.name} 🌏`); });
require('dotenv').config(); const bodyParser = require('body-parser'); const metadata = require('../package.json'); const compression = require('compression'); const express = require('express'); const path = require('path'); const port = process.env.NODE_PORT; const secret = process.env.SESSION_SECRET; // const redisClient = redis.createClient(); const app = express(); app.use(bodyParser.json({limit: '40mb'})); app.use(compression()); // gzip compress all responses const routes = ['/']; for (const route of routes) { app.get(route, (req, res) => { res.sendFile(path.join(__dirname, '/../client/index.html')); }); } app.use(express.static(path.join(__dirname, '../client'))); // wildcard route app.get('*', function(req, res) { res.status(404).send('Not Found'); }); app.listen(port, () => { console.log(`🌎 Listening on port ${port} for app ${metadata.name} 🌏`); });
Allow it to run with runserver if you don't have the VIRTUALENV variable set
""" WSGI config for moocng project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. #from django.core.wsgi import get_wsgi_application #application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) def application(environ, start_response): virtualenv = environ.get('VIRTUALENV', None) if virtualenv is not None: activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py') execfile(activate_this, dict(__file__=activate_this)) from django.core.wsgi import get_wsgi_application django_app = get_wsgi_application() return django_app(environ, start_response)
""" WSGI config for moocng project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. #from django.core.wsgi import get_wsgi_application #application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) def application(environ, start_response): virtualenv = environ.get('VIRTUALENV', '/var/www') activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py') execfile(activate_this, dict(__file__=activate_this)) from django.core.wsgi import get_wsgi_application django_app = get_wsgi_application() return django_app(environ, start_response)
Test for API url's without path parameters. Signed-off-by: joelso <18eaca8d2012d90d448985477d4cb18b3fab3fa4@gmail.com>
package org.trello4j; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.trello4j.model.Action; /** * Created with IntelliJ IDEA. * User: joel * Date: 2012-04-15 * Time: 11:00 AM */ public class TrelloURLTest { /** * Should build url with filter. * * @throws Exception the exception */ @Test public void shouldBuildURLWithFilter() throws Exception { String url = TrelloURL.create("API_KEY", TrelloURL.ACTION_URL, "ID") .token("TOKEN") .filter(Action.TYPE.ADD_ATTACHMENT, Action.TYPE.ADD_CHECKLIST) .build(); String expectedUrl = "https://api.trello.com/1/actions/ID?key=API_KEY&token=TOKEN&filter=" + Action.TYPE.ADD_ATTACHMENT + "," + Action.TYPE.ADD_CHECKLIST; assertEquals(expectedUrl, url); } @Test public void shouldNotReturnNullBaseURL() { String url = TrelloURL .create("API_KEY", TrelloURL.CARD_POST_URL) .token("TOKEN") .build(); String expectedUrl = "https://api.trello.com/1/cards?key=API_KEY&token=TOKEN"; assertEquals(expectedUrl, url); } }
package org.trello4j; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.trello4j.model.Action; /** * Created with IntelliJ IDEA. * User: joel * Date: 2012-04-15 * Time: 11:00 AM */ public class TrelloURLTest { /** * Should build url with filter. * * @throws Exception the exception */ @Test public void shouldBuildURLWithFilter() throws Exception { String url = TrelloURL.create("API_KEY", TrelloURL.ACTION_URL, "ID") .token("TOKEN") .filter(Action.TYPE.ADD_ATTACHMENT, Action.TYPE.ADD_CHECKLIST) .build(); String expectedUrl = "https://api.trello.com/1/actions/ID?key=API_KEY&token=TOKEN&filter=" + Action.TYPE.ADD_ATTACHMENT + "," + Action.TYPE.ADD_CHECKLIST; assertEquals(expectedUrl, url); } }
Clarify how Persist() is supposed to work.
package raft import ( "io" ) // FSM provides an interface that can be implemented by // clients to make use of the replicated log type FSM interface { // Apply log is invoked once a log entry is commited Apply(*Log) interface{} // Snapshot is used to support log compaction. This call should // return an FSMSnapshot which can be used to save a point-in-time // snapshot of the FSM. Apply and Snapshot are not called in multiple // threads, but Apply will be called concurrently with Persist. This means // the FSM should be implemented in a fashion that allows for concurrent // updates while a snapshot is happening. Snapshot() (FSMSnapshot, error) // Restore is used to restore an FSM from a snapshot. It is not called // concurrently with any other command. The FSM must discard all previous // state. Restore(io.ReadCloser) error } // FSMSnapshot is returned by an FSM in response to a Snapshot // It must be safe to invoke FSMSnapshot methods with concurrent // calls to Apply type FSMSnapshot interface { // Persist should dump all necessary state to the WriteCloser 'sink', // and call sink.Close() when finished or call sink.Cancel() on error. Persist(sink SnapshotSink) error // Release is invoked when we are finished with the snapshot Release() }
package raft import ( "io" ) // FSM provides an interface that can be implemented by // clients to make use of the replicated log type FSM interface { // Apply log is invoked once a log entry is commited Apply(*Log) interface{} // Snapshot is used to support log compaction. This call should // return an FSMSnapshot which can be used to save a point-in-time // snapshot of the FSM. Apply and Snapshot are not called in multiple // threads, but Apply will be called concurrently with Persist. This means // the FSM should be implemented in a fashion that allows for concurrent // updates while a snapshot is happening. Snapshot() (FSMSnapshot, error) // Restore is used to restore an FSM from a snapshot. It is not called // concurrently with any other command. The FSM must discard all previous // state. Restore(io.ReadCloser) error } // FSMSnapshot is returned by an FSM in response to a Snapshot // It must be safe to invoke FSMSnapshot methods with concurrent // calls to Apply type FSMSnapshot interface { // Persist should dump all necessary state to the WriteCloser, // and invoke close when finished or call Cancel on error. Persist(sink SnapshotSink) error // Release is invoked when we are finished with the snapshot Release() }
Switch to ReactNative Linking API Based on https://docs.expo.io/versions/latest/guides/linking.html
/** * A Link element for React Native * * Currently links to http:// URLs * */ var React = require('react-native'); var { AppRegistry, Image, ScrollView, StyleSheet, Text, TouchableHighlight, View, Linking, } = React; var Link = React.createClass({ render() { return ( <TouchableHighlight onPress={this._linkPressed} {...this.props} /> ); }, _linkPressed() { if (this.props.url) { Linking.openURL(this.props.url); } else if (this.props.to && this.props.to.uri) { var url = this.props.to.uri; Linking.openURL(url); } else { console.error("Invalid Link destination:", this.props.to); } }, }); module.exports = Link;
/** * A Link element for React Native * * Currently links to http:// URLs * */ var React = require('react-native'); var { AppRegistry, Image, ScrollView, StyleSheet, Text, TouchableHighlight, View, } = React; var URLHandler = require('react-native-url-handler'); var Link = React.createClass({ render() { return ( <TouchableHighlight onPress={this._linkPressed} {...this.props} /> ); }, _linkPressed() { if (this.props.url) { URLHandler.openURL(this.props.url); } else if (this.props.to && this.props.to.uri) { var url = this.props.to.uri; URLHandler.openURL(url); } else { console.error("Invalid Link destination:", this.props.to); } }, }); module.exports = Link;
Fix describe name for getter tests
/** * Module dependencies. */ require('should'); var fixtures = require('../lib'); /** * Tests */ describe('fixturefiles', function() { describe('getter', function() { before(function() { fixtures.reload(); }); it('should return json', function() { fixtures.one.should.eql({ hello: 'world' }); fixtures.three.four.six.should.eql({ six: 6 }); }); it('should return text', function() { fixtures.three.four.five.should.eql('555'); fixtures.eight.should.eql('nine: 10'); }); }); describe('function', function() { before(function() { fixtures.reload({ type: 'function' }); }); it('should return json', function() { fixtures.one().should.eql({ hello: 'world' }); fixtures.one('text').should.eql('{"hello":"world"}'); fixtures.three.four.six().should.eql({ six: 6 }); }); it('should return text', function() { fixtures.three.four.five().should.eql('555'); fixtures.eight().should.eql('nine: 10'); }); it('should return buffer', function() { fixtures.one('buffer').should.be.instanceof(Buffer); fixtures.one('buffer').length.should.equal(18); fixtures.two('buffer').should.be.instanceof(Buffer); }); }); });
/** * Module dependencies. */ require('should'); var fixtures = require('../lib'); /** * Tests */ describe('fixturefiles', function() { describe('function', function() { before(function() { fixtures.reload(); }); it('should return json', function() { fixtures.one.should.eql({ hello: 'world' }); fixtures.three.four.six.should.eql({ six: 6 }); }); it('should return text', function() { fixtures.three.four.five.should.eql('555'); fixtures.eight.should.eql('nine: 10'); }); }); describe('function', function() { before(function() { fixtures.reload({ type: 'function' }); }); it('should return json', function() { fixtures.one().should.eql({ hello: 'world' }); fixtures.one('text').should.eql('{"hello":"world"}'); fixtures.three.four.six().should.eql({ six: 6 }); }); it('should return text', function() { fixtures.three.four.five().should.eql('555'); fixtures.eight().should.eql('nine: 10'); }); it('should return buffer', function() { fixtures.one('buffer').should.be.instanceof(Buffer); fixtures.one('buffer').length.should.equal(18); fixtures.two('buffer').should.be.instanceof(Buffer); }); }); });
Make the widget error message shorter and more understandable.
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual from .widget_link import Link, link, DirectionalLink, dlink # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget # Warn on import from warnings import warn warn("IPython widgets are experimental and may change in the future.", FutureWarning, stacklevel=2)
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual from .widget_link import Link, link, DirectionalLink, dlink # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget # Warn on import from warnings import warn warn("""The widget API is still considered experimental and may change in the future.""", FutureWarning, stacklevel=2)
Change version number to 0.1.3
Package.describe({ name: 'extremeandy:es6-promisify', version: '0.1.3', summary: 'es6-promisify for Meteor', git: 'https://github.com/extremeandy/meteor-es6-promisify', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.0.1'); api.use('ecmascript'); api.use('cosmos:browserify@0.7.0', 'client'); api.addFiles('promise-override.js'); api.addFiles('es6-promisify_server.js', 'server'); //.browserify.js extension is required due to a meteor bug to get it to handle properly. This will be fixed shortly. api.addFiles('es6-promisify_client.browserify.js', 'client'); api.export('Promisify'); }); Npm.depends({ 'es6-promisify': '3.0.0' });
Package.describe({ name: 'extremeandy:es6-promisify', version: '0.1.2', summary: 'es6-promisify for Meteor', git: 'https://github.com/extremeandy/meteor-es6-promisify', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.0.1'); api.use('ecmascript'); api.use('cosmos:browserify@0.7.0', 'client'); api.addFiles('promise-override.js'); api.addFiles('es6-promisify_server.js', 'server'); //.browserify.js extension is required due to a meteor bug to get it to handle properly. This will be fixed shortly. api.addFiles('es6-promisify_client.browserify.js', 'client'); api.export('Promisify'); }); Npm.depends({ 'es6-promisify': '3.0.0' });
Improve search ordering in challenges (+packages)
from django import forms from django.contrib.admin import widgets # Smrtr from network.models import Network from challenge.models import Challenge # External from haystack.forms import SearchForm class ChallengeForm(forms.ModelForm): class Meta: model = Challenge fields = ['name', 'description','image'] def __init__(self, request, *args, **kwargs): super(ChallengeForm, self).__init__(*args, **kwargs) #if request: # If passed only show networks the user is on #self.fields['network'].queryset = Network.objects.filter(usernetwork__user=request.user) class ChallengeSearchForm(SearchForm): def search(self): sqs = super(ChallengeSearchForm, self).search() sqs = sqs.order_by('-total_members','-type','score') return sqs def __init__(self, *args, **kwargs): super(ChallengeSearchForm, self).__init__(*args, **kwargs)
from django import forms from django.contrib.admin import widgets # Smrtr from network.models import Network from challenge.models import Challenge # External from haystack.forms import SearchForm class ChallengeForm(forms.ModelForm): class Meta: model = Challenge fields = ['name', 'description','image'] def __init__(self, request, *args, **kwargs): super(ChallengeForm, self).__init__(*args, **kwargs) #if request: # If passed only show networks the user is on #self.fields['network'].queryset = Network.objects.filter(usernetwork__user=request.user) class ChallengeSearchForm(SearchForm): def __init__(self, *args, **kwargs): super(ChallengeSearchForm, self).__init__(*args, **kwargs)
Make watch example for pods more durable.
import sys import asyncio import powershift.endpoints as endpoints async def run_query(): namespace = sys.argv[1] print('namespace=%r' % namespace) client = endpoints.AsyncClient() pods = await client.api.v1.namespaces(namespace=namespace).pods.get() for pod in pods.items: print(' OBJECT %s pod=%r' % (pod.metadata.resource_version, pod.metadata.name)) resource_version = pods.metadata.resource_version while True: try: async with client.api.v1.namespaces(namespace=namespace).pods.get(watch='', resource_version=resource_version, timeout_seconds=10) as items: async for item in items: action = item['type'] pod = item['object'] print(' %s %s pod=%r' % (action, pod.metadata.resource_version, pod.metadata.name)) resource_version = pod.metadata.resource_version except Exception: pass loop = asyncio.get_event_loop() loop.run_until_complete(run_query())
import asyncio import powershift.endpoints as endpoints import powershift.resources as resources client = endpoints.AsyncClient() async def run_query(): projects = await client.oapi.v1.projects.get() #print(projects) #print(resources.dumps(projects, indent=4, sort_keys=True)) #print() project = projects.items[0] namespace = project.metadata.name print('namespace=%r' % namespace) async with client.api.v1.namespaces(namespace=namespace).pods.get(watch='') as items: async for item in items: action = item['type'] pod = item['object'] print(' %s pod=%r' % (action, pod.metadata.name)) loop = asyncio.get_event_loop() loop.run_until_complete(run_query())
Use template instead of default view generator
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Welcome extends MY_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->template->build('welcome_message'); } } /* End of file welcome.php */ /* Location: ./application/controllers/welcome.php */
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Welcome extends MY_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->load->view('welcome_message'); } } /* End of file welcome.php */ /* Location: ./application/controllers/welcome.php */
Add graph of boolean property
/** * Logs Screen * * Shows all logs * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const Log = require('./logs/log'); const LogsScreen = { init: function() { this.view = document.getElementById('logs-view'); this.logsContainer = this.view.querySelector('.logs'); this.logs = [ new Log('virtual-things-2', 'level'), new Log('virtual-things-2', 'on'), new Log('weather-8b8f279cfcc42b05f2b3cdfd4b0c7f9c5eac5b18', 'temperature'), new Log('philips-hue-001788fffe4f2113-sensors-2', 'temperature'), ]; this.onWindowResize = this.onWindowResize.bind(this); window.addEventListener('resize', this.onWindowResize); this.onWindowResize(); }, show: function() { this.logsContainer.innerHTML = ''; this.logs.forEach((log) => { log.reload(); this.logsContainer.appendChild(log.elt); }); }, onWindowResize: function() { }, }; module.exports = LogsScreen;
/** * Logs Screen * * Shows all logs * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const Log = require('./logs/log'); const LogsScreen = { init: function() { this.view = document.getElementById('logs-view'); this.logsContainer = this.view.querySelector('.logs'); this.logs = [ new Log('virtual-things-2', 'level'), new Log('weather-8b8f279cfcc42b05f2b3cdfd4b0c7f9c5eac5b18', 'temperature'), new Log('philips-hue-001788fffe4f2113-sensors-2', 'temperature'), ]; this.onWindowResize = this.onWindowResize.bind(this); window.addEventListener('resize', this.onWindowResize); this.onWindowResize(); }, show: function() { this.logsContainer.innerHTML = ''; this.logs.forEach((log) => { log.reload(); this.logsContainer.appendChild(log.elt); }); }, onWindowResize: function() { }, }; module.exports = LogsScreen;
Add close() method to HttpOutput
<?php namespace Nerd\Framework\Http\IO; use Nerd\Framework\Http\Response\CookieContract; interface OutputContract { /** * Send cookie to client * * @param CookieContract $cookie * @return mixed */ public function sendCookie(CookieContract $cookie); /** * Send header to client * * @param $header * @return mixed */ public function sendHeader($header); /** * Send data to client. * * @param $data * @return mixed */ public function sendData($data); /** * Return are headers was sent * * @return mixed */ public function isHeadersSent(); /** * Clear output buffer */ public function flush(); /** * Close output */ public function close(); }
<?php namespace Nerd\Framework\Http\IO; use Nerd\Framework\Http\Response\CookieContract; interface OutputContract { /** * Send cookie to client * * @param CookieContract $cookie * @return mixed */ public function sendCookie(CookieContract $cookie); /** * Send header to client * * @param $header * @return mixed */ public function sendHeader($header); /** * Send data to client. * * @param $data * @return mixed */ public function sendData($data); /** * Return are headers was sent * * @return mixed */ public function isHeadersSent(); /** * Clear output buffer */ public function flush(); }
Include pygame and numpy in discription.
# -*- coding: utf-8 -*- """ FLUID DYNAMICS SIMULATOR Requires Python 2.7, pygame, numpy, and OpenCV 2 Tom Blanchet (c) 2013 - 2014 (revised 2017) """ import cv2 from fluidDoubleCone import FluidDoubleCone, RGB from fluidDoubleConeView import FluidDCViewCtrl def slow_example(): inImg = cv2.imread("gameFace.jpg") game_face_dCone = FluidDoubleCone(inImg, RGB) ui = FluidDCViewCtrl(game_face_dCone, 615, 737) def fast_example(): inImg = cv2.imread("fastKid.png") fast_kid_dCone = FluidDoubleCone(inImg, RGB) ui = FluidDCViewCtrl(fast_kid_dCone, 200*2, 200*2) ui.mainloop() if __name__ == "__main__": fast_example()
# -*- coding: utf-8 -*- """ FLUID DYNAMICS SIMULATOR Requires Python 2.7 and OpenCV 2 Tom Blanchet (c) 2013 - 2014 (revised 2017) """ import cv2 from fluidDoubleCone import FluidDoubleCone, RGB from fluidDoubleConeView import FluidDCViewCtrl def slow_example(): inImg = cv2.imread("gameFace.jpg") game_face_dCone = FluidDoubleCone(inImg, RGB) ui = FluidDCViewCtrl(game_face_dCone, 615, 737) def fast_example(): inImg = cv2.imread("fastKid.png") fast_kid_dCone = FluidDoubleCone(inImg, RGB) ui = FluidDCViewCtrl(fast_kid_dCone, 200*2, 200*2) ui.mainloop() if __name__ == "__main__": fast_example()
Add documentation for the CPSR command
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import gdb import pwndbg.arch import pwndbg.color import pwndbg.commands import pwndbg.regs @pwndbg.commands.Command @pwndbg.commands.OnlyWhenRunning def cpsr(): 'Print out the ARM CPSR register' if pwndbg.arch.current != 'arm': print("This is only available on ARM") return cpsr = pwndbg.regs.cpsr N = cpsr & (1<<31) Z = cpsr & (1<<30) C = cpsr & (1<<29) V = cpsr & (1<<28) T = cpsr & (1<<5) bold = pwndbg.color.bold result = [ bold('N') if N else 'n', bold('Z') if Z else 'z', bold('C') if C else 'c', bold('V') if V else 'v', bold('T') if T else 't' ] print('cpsr %#x [ %s ]' % (cpsr, ' '.join(result)))
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import gdb import pwndbg.arch import pwndbg.color import pwndbg.commands import pwndbg.regs @pwndbg.commands.Command @pwndbg.commands.OnlyWhenRunning def cpsr(): if pwndbg.arch.current != 'arm': print("This is only available on ARM") return cpsr = pwndbg.regs.cpsr N = cpsr & (1<<31) Z = cpsr & (1<<30) C = cpsr & (1<<29) V = cpsr & (1<<28) T = cpsr & (1<<5) bold = pwndbg.color.bold result = [ bold('N') if N else 'n', bold('Z') if Z else 'z', bold('C') if C else 'c', bold('V') if V else 'v', bold('T') if T else 't' ] print('cpsr %#x [ %s ]' % (cpsr, ' '.join(result)))
Extend task controller to render search results
define([ 'Backbone', //Collection 'app/collections/tasks', //Template 'text!templates/project-page/taskItemTemplate.html', ], function( Backbone, //Collection Tasks, //Template itemTemplate ){ var TaskController = Backbone.View.extend({ template: _.template(itemTemplate), initialize: function(){ this.collection = new Tasks(this.options.projectId); this.collection.bind('reset', this.render, this); this.collection.bind('search', this.searchResult, this); }, searchResult: function(result){ this.$el.html(''); var template = this.template; var $list = this.$el; var title; _.each(result, function(model){ title = model.get('title'); if(title){ $list.append(template({title: model.get('title')})); } }); }, render: function(){ this.$el.html(''); var template = this.template; var $list = this.$el; _.each(this.collection.models, function(model){ $list.append(template({title: model.get('title')})); }); } }); return TaskController; });
define([ 'Backbone', //Collection 'app/collections/tasks', //Template 'text!templates/project-page/taskItemTemplate.html', ], function( Backbone, //Collection Tasks, //Template itemTemplate ){ var TaskController = Backbone.View.extend({ template: _.template(itemTemplate), initialize: function(){ this.collection = new Tasks(this.options.projectId); this.collection.bind('reset', this.render, this); }, render: function(){ this.$el.html(''); var template = this.template; var $list = this.$el; _.each(this.collection.models, function(model){ $list.append(template({title: model.get('title')})); }); } }); return TaskController; });
Use multi arg option too
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} +' % dirname)
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} \\;' % dirname)
Fix calculation of model size
import subprocess import re import os from lib.utils import loadYaml config = loadYaml('../config.yml') dimensionsRegex = r'{type} = +(\-?\d+\.\d+)' types = { 'x': ['Min X', 'Max X'], 'y': ['Min Y', 'Max Y'], 'z': ['Min Z', 'Max Z'], } def analyzeSTL(path, fileName): command = subprocess.Popen('{ADMeshExecutable} {stlFilePath}'.format( ADMeshExecutable=config['ADMesh-executable'], stlFilePath = os.path.join(path, config['stl-upload-directory'], fileName) ), stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = command.communicate() output = output.decode(config['terminal-encoding']) dimensions = {} for type in types: try: firstVal = re.findall(dimensionsRegex.format(type=types[type][0]), output)[0] secondVal = re.findall(dimensionsRegex.format(type=types[type][1]), output)[0] dimensions[type] = abs(float(firstVal) - float(secondVal)) except IndexError as e: print('unable to decode', output) raise e return dimensions
import subprocess import re import os from lib.utils import loadYaml config = loadYaml('../config.yml') dimensionsRegex = r'{type} = +(\-?\d+\.\d+)' types = { 'x': ['Min X', 'Max X'], 'y': ['Min Y', 'Max Y'], 'z': ['Min Z', 'Max Z'], } def analyzeSTL(path, fileName): command = subprocess.Popen('{ADMeshExecutable} {stlFilePath}'.format( ADMeshExecutable=config['ADMesh-executable'], stlFilePath = os.path.join(path, config['stl-upload-directory'], fileName) ), stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = command.communicate() output = output.decode(config['terminal-encoding']) dimensions = {} for type in types: try: firstVal = re.findall(dimensionsRegex.format(type=types[type][0]), output)[0] secondVal = re.findall(dimensionsRegex.format(type=types[type][1]), output)[0] dimensions[type] = abs(float(firstVal)) + abs(float(secondVal)) except IndexError as e: print('unable to decode', output) raise e return dimensions
Add externally maintained source type
package org.ihtsdo.buildcloud.service.fileprocessing; public enum InputSources { TERM_SERVER("terminology-server"), REFSET_TOOL("reference-set-tool"), MAPPING_TOOLS("mapping-tools"), MANUAL("manual"), EXTERNALY_MAINTAINED("externally-maintained"); private String sourceName; InputSources(String sourceName) { this.sourceName = sourceName; } public String getSourceName() { return sourceName; } public static InputSources getSource(String sourceName) { for (InputSources sourceType : InputSources.values()) { if(sourceType.getSourceName().equalsIgnoreCase(sourceName)) { return sourceType; } } return null; } }
package org.ihtsdo.buildcloud.service.fileprocessing; public enum InputSources { TERM_SERVER("terminology-server"), REFSET_TOOL("reference-set-tool"), MAPPING_TOOLS("mapping-tools"), MANUAL("manual"); private String sourceName; InputSources(String sourceName) { this.sourceName = sourceName; } public String getSourceName() { return sourceName; } public static InputSources getSource(String sourceName) { for (InputSources sourceType : InputSources.values()) { if(sourceType.getSourceName().equalsIgnoreCase(sourceName)) { return sourceType; } } return null; } }
Make private checkbox not required
from django import forms class LeagueForm(forms.Form): league_name = forms.CharField(label = "Group name", max_length = 30) max_size = forms.IntegerField(label = "Maximum participants", min_value = 0, max_value = 9999) points_for_exact_guess = forms.IntegerField(label = "Points for exact guess", min_value = 0, max_value = 100) points_for_goal_difference = forms.IntegerField(label = "Points for correct outcome with goal difference", min_value = 0, max_value = 100) points_for_outcome = forms.IntegerField(label = "Points for outcome", min_value = 0, max_value = 100) points_for_number_of_goals = forms.IntegerField(label = "Points for number of goals", min_value = 0, max_value = 100) points_for_exact_home_goals = forms.IntegerField(label = "Points for exact home goals", min_value = 0, max_value = 100) points_for_exact_away_goals = forms.IntegerField(label = "Points for exact away goals", min_value = 0, max_value = 100) is_private = forms.BooleanField(label = "Private", required=False, initial = False)
from django import forms class LeagueForm(forms.Form): league_name = forms.CharField(label = "Group name", max_length = 30) max_size = forms.IntegerField(label = "Maximum participants", min_value = 0, max_value = 9999) points_for_exact_guess = forms.IntegerField(label = "Points for exact guess", min_value = 0, max_value = 100) points_for_goal_difference = forms.IntegerField(label = "Points for correct outcome with goal difference", min_value = 0, max_value = 100) points_for_outcome = forms.IntegerField(label = "Points for outcome", min_value = 0, max_value = 100) points_for_number_of_goals = forms.IntegerField(label = "Points for number of goals", min_value = 0, max_value = 100) points_for_exact_home_goals = forms.IntegerField(label = "Points for exact home goals", min_value = 0, max_value = 100) points_for_exact_away_goals = forms.IntegerField(label = "Points for exact away goals", min_value = 0, max_value = 100) is_private = forms.BooleanField(label = "Private")
Handle correct timezone when retrieving the daily schedule with a specific time.
package foodtruck.server.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.google.inject.Inject; import org.joda.time.DateTime; import foodtruck.model.DailySchedule; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.util.Clock; /** * @author aviolette * @since 1/27/13 */ @Path("/daily_schedule") @Produces(MediaType.APPLICATION_JSON) public class DailyScheduleResource { private final FoodTruckStopService truckService; private final Clock clock; private final AuthorizationChecker checker; @Inject public DailyScheduleResource(FoodTruckStopService foodTruckService, Clock clock, AuthorizationChecker checker) { this.truckService = foodTruckService; this.clock = clock; this.checker = checker; } @GET @Produces("application/json") public DailySchedule findForDay(@QueryParam("appKey") final String appKey, @QueryParam("from") final long from) { checker.requireAppKey(appKey); if (from > 0) { return truckService.findStopsForDayAfter(new DateTime(from, clock.zone())); } return truckService.findStopsForDay(clock.currentDay()); } }
package foodtruck.server.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.google.inject.Inject; import org.joda.time.DateTime; import foodtruck.model.DailySchedule; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.util.Clock; /** * @author aviolette * @since 1/27/13 */ @Path("/daily_schedule") @Produces(MediaType.APPLICATION_JSON) public class DailyScheduleResource { private final FoodTruckStopService truckService; private final Clock clock; private final AuthorizationChecker checker; @Inject public DailyScheduleResource(FoodTruckStopService foodTruckService, Clock clock, AuthorizationChecker checker) { this.truckService = foodTruckService; this.clock = clock; this.checker = checker; } @GET @Produces("application/json") public DailySchedule findForDay(@QueryParam("appKey") final String appKey, @QueryParam("from") final long from) { checker.requireAppKey(appKey); if (from > 0) { return truckService.findStopsForDayAfter(new DateTime(from)); } return truckService.findStopsForDay(clock.currentDay()); } }
Add ProcessHelp call to Helptext test. License: MIT Signed-off-by: Jakub Sztandera <77246600354bed77252577b0222eb63e0827639a@protonmail.ch>
package commands import ( cmds "github.com/ipfs/go-ipfs/commands" "strings" "testing" ) func checkHelptextRecursive(t *testing.T, name []string, c *cmds.Command) { if c.Helptext.Tagline == "" { t.Errorf("%s has no tagline!", strings.Join(name, " ")) } if c.Helptext.LongDescription == "" { t.Errorf("%s has no long description!", strings.Join(name, " ")) } if c.Helptext.ShortDescription == "" { t.Errorf("%s has no short description!", strings.Join(name, " ")) } if c.Helptext.Synopsis == "" { t.Errorf("%s has no synopsis!", strings.Join(name, " ")) } for subname, sub := range c.Subcommands { checkHelptextRecursive(t, append(name, subname), sub) } } func TestHelptexts(t *testing.T) { Root.ProcessHelp() checkHelptextRecursive(t, []string{"ipfs"}, Root) }
package commands import ( cmds "github.com/ipfs/go-ipfs/commands" "strings" "testing" ) func checkHelptextRecursive(t *testing.T, name []string, c *cmds.Command) { if c.Helptext.Tagline == "" { t.Errorf("%s has no tagline!", strings.Join(name, " ")) } if c.Helptext.LongDescription == "" { t.Errorf("%s has no long description!", strings.Join(name, " ")) } if c.Helptext.ShortDescription == "" { t.Errorf("%s has no short description!", strings.Join(name, " ")) } if c.Helptext.Synopsis == "" { t.Errorf("%s has no synopsis!", strings.Join(name, " ")) } for subname, sub := range c.Subcommands { checkHelptextRecursive(t, append(name, subname), sub) } } func TestHelptexts(t *testing.T) { checkHelptextRecursive(t, []string{"ipfs"}, Root) }
Fix markup for button as search box add-on
<?php ?> <!-- <div class="search form-wrapper form-group"> <form method="get" id="searchform" class="form-inline form-search" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <label for="s" class="assistive-text"><?php _e( 'Search', 'twentyeleven' ); ?></label> <input type="text" class="form-control" name="s" id="s" placeholder="<?php esc_attr_e( 'Search...', 'ttp' ); ?>" /> </form> </div> --> <form method="get" id="searchform" role="form" class="navbar-form navbar-right" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div class="form-group"> <div class="input-group"> <input type="text" class="form-control" name="s" id="s" placeholder="<?php esc_attr_e( 'Search...', 'ttp' ); ?>" /> <span class="input-group-btn"> <button type="submit" class="btn btn-default"><i class="fa fa-search fa-fw"></i></button> </span> </div> </div> </form>
<?php ?> <!-- <div class="search form-wrapper form-group"> <form method="get" id="searchform" class="form-inline form-search" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <label for="s" class="assistive-text"><?php _e( 'Search', 'twentyeleven' ); ?></label> <input type="text" class="form-control" name="s" id="s" placeholder="<?php esc_attr_e( 'Search...', 'ttp' ); ?>" /> </form> </div> --> <form method="get" id="searchform" role="form" class="navbar-form navbar-right" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div class="form-group"> <div class="input-group"> <input type="text" class="form-control" name="s" id="s" placeholder="<?php esc_attr_e( 'Search...', 'ttp' ); ?>" /> <span class="input-group-addon"> <i class="fa fa-search fa-fw" aria-hidden="true"></i> </span> </div> </div> </form>
Update meta version so that documentation looks good in pypi
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform with open("README.md", "r") as fh: long_description = fh.read() setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Kal Walkden", author_email="kal@walkden.us", description="A simple Django form template tag to work with Materializecss", long_description=long_description, long_description_content_type="text/markdown", include_package_data=True, url='https://github.com/kalwalkden/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 4 - Beta", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", ], license="MIT", zip_safe=False )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Kal Walkden", author_email="kal@walkden.us", description="A simple Django form template tag to work with Materializecss", long_description=open('README.md').read(), long_description_content_type="text/markdown", include_package_data=True, url='https://github.com/kalwalkden/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 4 - Beta", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", "Topic :: Documentation :: Sphinx", ], license="MIT", zip_safe=False )
Fix Eval to use current buffer path for GoFmt Signed-off-by: Koichi Shiraishi <13fbd79c3d390e5d6585a21e11ff5ec1970cff0c@zchee.io>
package autocmd import ( "nvim-go/commands" "nvim-go/config" "github.com/garyburd/neovim-go/vim" "github.com/garyburd/neovim-go/vim/plugin" ) func init() { plugin.HandleAutocmd("BufWritePre", &plugin.AutocmdOptions{Pattern: "*.go", Group: "nvim-go", Eval: "[getcwd(), expand('%:p:h'), expand('%:p')]"}, autocmdBufWritePre) } type bufwritepreEval struct { Cwd string `msgpack:",array"` Dir string File string } func autocmdBufWritePre(v *vim.Vim, eval bufwritepreEval) error { if config.IferrAutosave { var env = commands.CmdIferrEval{ Cwd: eval.Cwd, File: eval.File, } go commands.Iferr(v, env) } if config.MetalinterAutosave { go commands.Metalinter(v, eval.Cwd) } if config.FmtAsync { go commands.Fmt(v, eval.Dir) } else { return commands.Fmt(v, eval.Dir) } return nil }
package autocmd import ( "nvim-go/commands" "nvim-go/config" "github.com/garyburd/neovim-go/vim" "github.com/garyburd/neovim-go/vim/plugin" ) func init() { plugin.HandleAutocmd("BufWritePre", &plugin.AutocmdOptions{Pattern: "*.go", Group: "nvim-go", Eval: "[getcwd(), expand('%:p')]"}, autocmdBufWritePre) } type bufwritepreEval struct { Cwd string `msgpack:",array"` File string } func autocmdBufWritePre(v *vim.Vim, eval bufwritepreEval) error { if config.IferrAutosave { var env = commands.CmdIferrEval{ Cwd: eval.Cwd, File: eval.File, } go commands.Iferr(v, env) } if config.MetalinterAutosave { go commands.Metalinter(v, eval.Cwd) } if config.FmtAsync { go commands.Fmt(v, eval.Cwd) } else { return commands.Fmt(v, eval.Cwd) } return nil }
Use commands defined in app package
package main import ( "os" a "github.com/appPlant/alpinepass/app" "github.com/urfave/cli" ) func runApp() { app := cli.NewApp() app.Name = "alpinepass" app.Version = "0.0.0" app.Author = "appPlant GmbH" app.Usage = "Manage system environment information." app.Flags = []cli.Flag{ cli.StringSliceFlag{ Name: "filter, f", Usage: "Filter configurations by name, type and more.", }, cli.StringFlag{ Name: "input, i", Usage: "Specify the input file path.", }, cli.StringFlag{ Name: "output, o", Usage: "Specify the output format.", }, cli.BoolFlag{ Name: "passwords, p", Usage: "Include passwords in the output.", }, cli.BoolFlag{ Name: "show, s", Usage: "Show the output in the console. An output file will not be written.", }, } app.Action = func(context *cli.Context) error { if context.GlobalBool("show") { return a.RunShowCommand(context) } return a.RunOutCommand(context) } app.Run(os.Args) }
package main import ( "os" "github.com/urfave/cli" ) func runApp() { app := cli.NewApp() app.Name = "alpinepass" app.Version = "0.0.0" app.Author = "appPlant GmbH" app.Usage = "Manage system environment information." app.Flags = []cli.Flag{ cli.StringSliceFlag{ Name: "filter, f", Usage: "Filter configurations by name, type and more.", }, cli.StringFlag{ Name: "input, i", Usage: "Specify the input file path.", }, cli.StringFlag{ Name: "output, o", Usage: "Specify the output format.", }, cli.BoolFlag{ Name: "passwords, p", Usage: "Include passwords in the output.", }, cli.BoolFlag{ Name: "show, s", Usage: "Show the output in the console. An output file will not be written.", }, } app.Action = func(context *cli.Context) error { if context.GlobalBool("show") { return runShowCommand(context) } else { return runOutCommand(context) } } app.Run(os.Args) }
Allow Blob to be accessed with __getitem__
import json import hashlib from typing import Any, Dict from wdim import orm from wdim.orm import fields from wdim.orm import exceptions class Blob(orm.Storable): HASH_METHOD = 'sha256' _id = fields.StringField(unique=True) data = fields.DictField() @classmethod async def create(cls, data: Dict[str, Any]) -> 'Blob': sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest() try: # Classmethod supers need arguments for some reason return await super(Blob, cls).create(_id=sha, data=data) except exceptions.UniqueViolation: return await cls.load(sha) @property def hash(self) -> str: return self._id def __getitem__(self, key): return self.data[key]
import json import hashlib from wdim import orm from wdim.orm import fields from wdim.orm import exceptions class Blob(orm.Storable): HASH_METHOD = 'sha256' _id = fields.StringField(unique=True) data = fields.DictField() @classmethod async def create(cls, data): sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest() try: # Classmethod supers need arguments for some reason return await super(Blob, cls).create(_id=sha, data=data) except exceptions.UniqueViolation: return await cls.load(sha) @property def hash(self): return self._id
Add new methods to base social class
var _ = require('lodash'); /** * Create base social instance * @param {Object} [_config] * @constructor */ function BaseSocial(_config) { this._config = {}; _.forOwn(_config, function (value, key) { this.set(key, value); }.bind(this)); } /** * Get configuration value * @param {String} [path] * @returns {*} */ BaseSocial.prototype.get = function (path) { return typeof path === 'undefined' ? this._config : _.get(this._config, path); }; /** * Set configuration value * @param {String} path * @param {*} value * @returns {BaseSocial} */ BaseSocial.prototype.set = function (path, value) { _.set(this._config, path, value); return this; }; /** * Get provider for sending notifications * @returns {*} */ BaseSocial.prototype.getProvider = function () { return this._provider; }; /** * Set new provider to this pusher * @param {*} provider * @returns {BaseSocial} */ BaseSocial.prototype.setProvider = function (provider) { this._provider = provider; return this; }; BaseSocial.prototype.getProfile = _; BaseSocial.prototype.getFriends = _; BaseSocial.prototype.getPhotos = _; BaseSocial.prototype.getPosts = _; module.exports = BaseSocial;
var _ = require('lodash'); /** * Create base social instance * @param {Object} [_config] * @constructor */ function BaseSocial(_config) { this._config = {}; _.forOwn(_config, function (value, key) { this.set(key, value); }.bind(this)); } /** * Get configuration value * @param {String} [path] * @returns {*} */ BaseSocial.prototype.get = function (path) { return typeof path === 'undefined' ? this._config : _.get(this._config, path); }; /** * Set configuration value * @param {String} path * @param {*} value * @returns {BaseSocial} */ BaseSocial.prototype.set = function (path, value) { _.set(this._config, path, value); return this; }; /** * Get provider for sending notifications * @returns {*} */ BaseSocial.prototype.getProvider = function () { return this._provider; }; /** * Set new provider to this pusher * @param {*} provider * @returns {BaseSocial} */ BaseSocial.prototype.setProvider = function (provider) { this._provider = provider; return this; }; BaseSocial.prototype.getFriends = _; BaseSocial.prototype.getPhotos = _; module.exports = BaseSocial;
Save the build log every time the log is updated.
<?php /** * PHPCI - Continuous Integration for PHP * * @copyright Copyright 2014, Block 8 Limited. * @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md * @link https://www.phptesting.org/ */ namespace PHPCI\Logging; use b8\Store\Factory; use Monolog\Handler\AbstractProcessingHandler; use PHPCI\Model\Build; class BuildDBLogHandler extends AbstractProcessingHandler { /** * @var Build */ protected $build; protected $logValue; public function __construct( Build $build, $level = LogLevel::INFO, $bubble = true ) { parent::__construct($level, $bubble); $this->build = $build; // We want to add to any existing saved log information. $this->logValue = $build->getLog(); } protected function write(array $record) { $message = (string)$record['message']; $message = str_replace($this->build->currentBuildPath, '/', $message); $this->logValue .= $message . PHP_EOL; $this->build->setLog($this->logValue); Factory::getStore('Build')->save($this->build); } }
<?php /** * PHPCI - Continuous Integration for PHP * * @copyright Copyright 2014, Block 8 Limited. * @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md * @link https://www.phptesting.org/ */ namespace PHPCI\Logging; use b8\Store; use Monolog\Handler\AbstractProcessingHandler; use PHPCI\Model\Build; class BuildDBLogHandler extends AbstractProcessingHandler { /** * @var Build */ protected $build; protected $logValue; public function __construct( Build $build, $level = LogLevel::INFO, $bubble = true ) { parent::__construct($level, $bubble); $this->build = $build; // We want to add to any existing saved log information. $this->logValue = $build->getLog(); } protected function write(array $record) { $message = (string)$record['message']; $message = str_replace($this->build->currentBuildPath, '/', $message); $this->logValue .= $message . PHP_EOL; $this->build->setLog($this->logValue); } }
Change import path to absolute commonjs path See https://github.com/imcvampire/vue-axios/issues/109#issuecomment-920708021
import Vuex from 'vuex' import axios from 'axios' import VueAxios from 'vue-axios/dist/vue-axios.common.min' import HalJsonVuex from 'hal-json-vuex' import lang from './lang' class StorePlugin { install (Vue, options) { Vue.use(Vuex) store = new Vuex.Store({ modules: { lang }, strict: process.env.NODE_ENV !== 'production' }) axios.defaults.withCredentials = true axios.defaults.baseURL = window.environment.API_ROOT_URL axios.defaults.headers.common.Accept = 'application/hal+json' axios.interceptors.request.use(function (config) { if (config.method === 'patch') { config.headers['Content-Type'] = 'application/merge-patch+json' } return config }) Vue.use(VueAxios, axios) let halJsonVuex = HalJsonVuex if (typeof halJsonVuex !== 'function') { halJsonVuex = HalJsonVuex.default } apiStore = halJsonVuex(store, axios, { forceRequestedSelfLink: true }) Vue.use(apiStore) } } export let apiStore export let store export default new StorePlugin()
import Vuex from 'vuex' import axios from 'axios' import VueAxios from 'vue-axios' import HalJsonVuex from 'hal-json-vuex' import lang from './lang' class StorePlugin { install (Vue, options) { Vue.use(Vuex) store = new Vuex.Store({ modules: { lang }, strict: process.env.NODE_ENV !== 'production' }) axios.defaults.withCredentials = true axios.defaults.baseURL = window.environment.API_ROOT_URL axios.defaults.headers.common.Accept = 'application/hal+json' axios.interceptors.request.use(function (config) { if (config.method === 'patch') { config.headers['Content-Type'] = 'application/merge-patch+json' } return config }) Vue.use(VueAxios, axios) let halJsonVuex = HalJsonVuex if (typeof halJsonVuex !== 'function') { halJsonVuex = HalJsonVuex.default } apiStore = halJsonVuex(store, axios, { forceRequestedSelfLink: true }) Vue.use(apiStore) } } export let apiStore export let store export default new StorePlugin()
Revert a small syntax change introduced by a circular series of changes. Former-commit-id: 09597b7cf33f4c1692f48d08a535bdbc45042cde
from nose.tools import eq_, assert_almost_equal from wordfreq import tokenize, word_frequency def test_tokens(): eq_(tokenize('おはようございます', 'ja'), ['おはよう', 'ござい', 'ます']) def test_combination(): ohayou_freq = word_frequency('おはよう', 'ja') gozai_freq = word_frequency('ござい', 'ja') masu_freq = word_frequency('ます', 'ja') assert_almost_equal( word_frequency('おはようおはよう', 'ja'), ohayou_freq / 2 ) assert_almost_equal( 1.0 / word_frequency('おはようございます', 'ja'), 1.0 / ohayou_freq + 1.0 / gozai_freq + 1.0 / masu_freq )
from nose.tools import eq_, assert_almost_equal from wordfreq import tokenize, word_frequency def test_tokens(): eq_(tokenize('おはようございます', 'ja'), ['おはよう', 'ござい', 'ます']) def test_combination(): ohayou_freq = word_frequency('おはよう', 'ja') gozai_freq = word_frequency('ござい', 'ja') masu_freq = word_frequency('ます', 'ja') assert_almost_equal( word_frequency('おはようおはよう', 'ja'), ohayou_freq / 2 ) assert_almost_equal( 1.0 / word_frequency('おはようございます', 'ja'), (1.0 / ohayou_freq + 1.0 / gozai_freq + 1.0 / masu_freq) )
Remove check for https on production environment. The developer should be careful enough to secure their application.
var localProtocol = require('../services/protocols/local'); /** * basicAuth * * If HTTP Basic Auth credentials are present in the headers, then authenticate the * user for a single request. */ module.exports = function (req, res, next) { var auth = req.headers.authorization; if (!auth || auth.search('Basic ') !== 0) { return next(); } var authString = new Buffer(auth.split(' ')[1], 'base64').toString(); var username = authString.split(':')[0]; var password = authString.split(':')[1]; sails.log.silly('authenticating', username, 'using basic auth:', req.url); localProtocol.login(req, username, password, function (error, user, passport) { if (error) { return next(error); } if (!user) { req.session.authenticated = false; return res.status(403).json({ error: 'Could not authenticate user '+ username }); } req.user = user; req.session.authenticated = true; req.session.passport = passport; next(); }); };
var localProtocol = require('../services/protocols/local'); /** * basicAuth * * If HTTP Basic Auth credentials are present in the headers, then authenticate the * user for a single request. */ module.exports = function (req, res, next) { var auth = req.headers.authorization; if (!auth || auth.search('Basic ') !== 0) { return next(); } if (process.env.NODE_ENV === 'production' && !req.secure) { return res.status(403).json({ error: 'https required for basic auth. refusing login request' }); } var authString = new Buffer(auth.split(' ')[1], 'base64').toString(); var username = authString.split(':')[0]; var password = authString.split(':')[1]; sails.log.silly('authenticating', username, 'using basic auth:', req.url); localProtocol.login(req, username, password, function (error, user, passport) { if (error) { return next(error); } if (!user) { req.session.authenticated = false; return res.status(403).json({ error: 'Could not authenticate user '+ username }); } req.user = user; req.session.authenticated = true; req.session.passport = passport; next(); }); };
FIX wrong db schema declaration
import { Mongo } from 'meteor/mongo'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; class ModuleFulfilmentCollection extends Mongo.Collection { insert(fulfilmentData, callBack){ const fulfilmentDoc = fulfilmentData; let result; //validate document return super.insert( fulfilmentDoc, callBack); }; update(selector, modifier){ const result = super.update(selector, modifier); return result; }; remove(selector){ const result = super.remove(selector); return result; }; } export const ModuleFulfilments = new ModuleFulfilmentCollection("modfulfilment"); /* * moduleMapping type, * @key academicYear * @value moduleMapping object */ const fulfilmentSchema = { moduleCode: { type: String }, moduleMapping: { type: Object, blackbox: true } } ModuleFulfilments.attachSchema(fulfilmentSchema);
import { Mongo } from 'meteor/mongo'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; class ModuleFulfilmentCollection extends Mongo.Collection { insert(fulfilmentData, callBack){ const fulfilmentDoc = fulfilmentData; let result; //validate document return super.insert( fulfilmentDoc, callBack); }; update(selector, modifier){ const result = super.update(selector, modifier); return result; }; remove(selector){ const result = super.remove(selector); return result; }; } export const ModuleFulfilments = new ModuleFulfilmentCollection("modfulfilment"); /* * moduleMapping type, * @key academicYear * @value moduleMapping object */ const fulfilmentSchema = { moduleCode: { type: String }, moduleMapping: { type: object, blackbox: true } } ModuleFulfilments.attachSchema(fulfilmentSchema);
Remove let in datasource tools tests
var datasourceTools = require("../source/tools/datasource.js"); module.exports = { setUp: function(cb) { (cb)(); }, extractDSStrProps: { testExtractsProperties: function(test) { var props = "ds=text,something=1,another-one=something.else,empty=", extracted = datasourceTools.extractDSStrProps(props); test.strictEqual(extracted.ds, "text", "Should extract datasource type correctly"); test.strictEqual(extracted.something, "1", "Should extract basic properties"); test.strictEqual(extracted["another-one"], "something.else", "Should extract properties with other characters"); test.strictEqual(extracted.empty, "", "Should extract empty properties"); test.done(); } } };
var datasourceTools = require("../source/tools/datasource.js"); module.exports = { setUp: function(cb) { (cb)(); }, extractDSStrProps: { testExtractsProperties: function(test) { let props = "ds=text,something=1,another-one=something.else,empty=", extracted = datasourceTools.extractDSStrProps(props); test.strictEqual(extracted.ds, "text", "Should extract datasource type correctly"); test.strictEqual(extracted.something, "1", "Should extract basic properties"); test.strictEqual(extracted["another-one"], "something.else", "Should extract properties with other characters"); test.strictEqual(extracted.empty, "", "Should extract empty properties"); test.done(); } } };
Add global `jquery` dependency for build UMD module
import buble from 'rollup-plugin-buble'; import uglify from 'rollup-plugin-uglify'; const config = { entry: 'src/index.js', plugins: [buble()], sourceMap: true, }; if (process.env.TARGET === 'commonjs') { config.dest = 'lib/index.js'; config.format = 'cjs'; } if (process.env.TARGET === 'es') { config.dest = 'es/index.js'; config.format = 'es'; } if (process.env.TARGET === 'umd') { config.moduleName = 'lightyPluginLegacy'; config.dest = process.env.NODE_ENV === 'production' ? 'dist/lighty-plugin-legacy.min.js' : 'dist/lighty-plugin-legacy.js'; config.format = 'umd'; config.globals = { jquery: 'jQuery', }; if (process.env.NODE_ENV === 'production') { config.plugins.push(uglify()); } } export default config;
import buble from 'rollup-plugin-buble'; import uglify from 'rollup-plugin-uglify'; const config = { entry: 'src/index.js', plugins: [buble()], sourceMap: true, }; if (process.env.TARGET === 'commonjs') { config.dest = 'lib/index.js'; config.format = 'cjs'; } if (process.env.TARGET === 'es') { config.dest = 'es/index.js'; config.format = 'es'; } if (process.env.TARGET === 'umd') { config.moduleName = 'lightyPluginLegacy'; config.dest = process.env.NODE_ENV === 'production' ? 'dist/lighty-plugin-legacy.min.js' : 'dist/lighty-plugin-legacy.js'; config.format = 'umd'; if (process.env.NODE_ENV === 'production') { config.plugins.push(uglify()); } } export default config;
Fix bug causing app to crash on clicking notification
package com.oxapps.tradenotifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; public class NotificationDeleteReceiver extends BroadcastReceiver { private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/"; @Override public void onReceive(Context context, Intent intent) { long newRequestTime = System.currentTimeMillis() / 1000; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime); editor.apply(); if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(TRADE_OFFERS_URL)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.getApplicationContext().startActivity(browserIntent); } } }
package com.oxapps.tradenotifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; public class NotificationDeleteReceiver extends BroadcastReceiver { private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/"; @Override public void onReceive(Context context, Intent intent) { long newRequestTime = System.currentTimeMillis() / 1000; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime); editor.apply(); if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(TRADE_OFFERS_URL)); context.getApplicationContext().startActivity(browserIntent); } } }
Add recover in prgs test for envs.Prgsenv()
package prgs import ( "testing" . "github.com/VonC/godbg" "github.com/VonC/senvgo/envs" "github.com/VonC/senvgo/paths" . "github.com/smartystreets/goconvey/convey" ) type testGetter struct{} func (tg testGetter) Get() []Prg { return []Prg{&prg{}} } func TestMain(t *testing.T) { envs.Prgsenvname = "PRGSTEST" Convey("Prerequisite: Prgsenv is set", t, func() { SetBuffers(nil) defer func() { if r := recover(); r != nil { Perrdbgf("e") p := paths.NewPath(".") So(len(p.String()), ShouldEqual, 1000) } }() p := envs.Prgsenv() So(len(p.String()), ShouldEqual, 1000) }) Convey("prgs can get prgs", t, func() { SetBuffers(nil) dg.Get() getter = testGetter{} So(len(Getter().Get()), ShouldEqual, 1) }) Convey("Prg implements a Prger", t, func() { Convey("Prg has a name", func() { p := &prg{name: "prg1"} So(p.Name(), ShouldEqual, "prg1") var prg Prg = p So(prg.Name(), ShouldEqual, "prg1") }) }) }
package prgs import ( "testing" . "github.com/VonC/godbg" . "github.com/smartystreets/goconvey/convey" ) type testGetter struct{} func (tg testGetter) Get() []Prg { return []Prg{&prg{}} } func TestMain(t *testing.T) { Convey("prgs can get prgs", t, func() { SetBuffers(nil) dg.Get() getter = testGetter{} So(len(Getter().Get()), ShouldEqual, 1) }) Convey("Prg implements a Prger", t, func() { Convey("Prg has a name", func() { p := &prg{name: "prg1"} So(p.Name(), ShouldEqual, "prg1") var prg Prg = p So(prg.Name(), ShouldEqual, "prg1") }) }) }
Declare with const in unit test
import { test, moduleForComponent } from 'ember-qunit'; import Ember from 'ember'; moduleForComponent('jobs-list', 'JobsListComponent', { needs: ['helper:format-duration', 'component:jobs-item'] }); test('it renders a list of jobs', function (assert) { const jobs = [ Ember.Object.create({ id: 1, state: 'passed' }), Ember.Object.create({ id: 1, state: 'failed' }) ]; const component = this.subject({ jobs: jobs, required: true }); this.render(); assert.equal(component.$('.section-title').text().trim(), 'Build Jobs'); assert.equal(component.$('.jobs-item').length, 2, 'there should be 2 job items'); assert.ok(component.$('.jobs-item:nth(0)').hasClass('passed'), 'passed class should be applied to a job'); assert.ok(component.$('.jobs-item:nth(1)').hasClass('failed'), 'failed class should be applied to a job'); }); test('it renders "Allowed Failures" version without a `required` property', function (assert) { const jobs = [ Ember.Object.create({ id: 1 }) ]; const component = this.subject({ jobs: jobs }); this.render(); assert.ok(component.$('.section-title').text().match(/Allowed Failures/)); });
import { test, moduleForComponent } from 'ember-qunit'; import Ember from 'ember'; moduleForComponent('jobs-list', 'JobsListComponent', { needs: ['helper:format-duration', 'component:jobs-item'] }); test('it renders a list of jobs', function (assert) { var component, jobs; jobs = [ Ember.Object.create({ id: 1, state: 'passed' }), Ember.Object.create({ id: 1, state: 'failed' }) ]; component = this.subject({ jobs: jobs, required: true }); this.render(); assert.equal(component.$('.section-title').text().trim(), 'Build Jobs'); assert.equal(component.$('.jobs-item').length, 2, 'there should be 2 job items'); assert.ok(component.$('.jobs-item:nth(0)').hasClass('passed'), 'passed class should be applied to a job'); assert.ok(component.$('.jobs-item:nth(1)').hasClass('failed'), 'failed class should be applied to a job'); }); test('it renders "Allowed Failures" version without a `required` property', function (assert) { const jobs = [ Ember.Object.create({ id: 1 }) ]; const component = this.subject({ jobs: jobs }); this.render(); assert.ok(component.$('.section-title').text().match(/Allowed Failures/)); });
Select only public_id on guest middleware
<?php namespace App\Http\Middleware; use Closure; class GuestAuth extends Authenticate { /** * Check if the user is logged in OR has the public_id of the project stored in a cookie * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if($this->auth->guest()){ $route = $request->route()->parameters(); $project = \DB::table('projects')->select('public_id')->where('slug', $route['project'])->first(); if(count($project) == 0) return redirect('/'); if($request->cookie('public_id') == null || strtoupper($request->cookie('public_id')) != $project->public_id){ if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect('/'); } } } return $next($request); } }
<?php namespace App\Http\Middleware; use Closure; class GuestAuth extends Authenticate { /** * Check if the user is logged in OR has the public_id of the project stored in a cookie * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if($this->auth->guest()){ $route = $request->route()->parameters(); $project = \DB::table('projects')->where('slug', $route['project'])->first(); if(count($project) == 0) return redirect('/'); if($request->cookie('public_id') == null || strtoupper($request->cookie('public_id')) != $project->public_id){ if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect('/'); } } } return $next($request); } }
Make multiple update operate on ids
module.exports = function(sugar, models, assert) { return function updateMultipleAuthors(cb) { var firstAuthor = {name: 'foo'}; var secondAuthor = {name: 'bar'}; var authors = [firstAuthor, secondAuthor]; sugar.create(models.Author, authors, function(err, d) { if(err) return cb(err); var name = 'joe'; sugar.update(models.Author, [d && d[0]._id, d && d[1]._id], {name: name}, function(err, d) { if(err) return cb(err); assert.equal(d && d[0], name); assert.equal(d && d[1], name); cb(); }); }); }; };
module.exports = function(sugar, models, assert) { return function updateMultipleAuthors(cb) { var firstAuthor = {name: 'foo'}; var secondAuthor = {name: 'bar'}; var authors = [firstAuthor, secondAuthor]; sugar.create(models.Author, authors, function(err, d) { if(err) return cb(err); var name = 'joe'; sugar.update(models.Author, authors, {name: name}, function(err, d) { if(err) return cb(err); assert.equal(d && d[0], name); assert.equal(d && d[1], name); cb(); }); }); }; };
Fix 3rd pillar validation constraint
package ee.tuleva.onboarding.mandate; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import lombok.*; import javax.persistence.*; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.math.BigDecimal; @Data @Getter @Entity @Table(name = "fund_transfer_exchange") @Builder @NoArgsConstructor @AllArgsConstructor @ToString(exclude = {"mandate"}) public class FundTransferExchange { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonView(MandateView.Default.class) private Long id; @JsonIgnore @ManyToOne @JoinColumn(name = "mandate_id", nullable = false) private Mandate mandate; @NotBlank @JsonView(MandateView.Default.class) private String sourceFundIsin; @NotNull @Min(0) @JsonView(MandateView.Default.class) private BigDecimal amount; @NotNull @JsonView(MandateView.Default.class) private String targetFundIsin; }
package ee.tuleva.onboarding.mandate; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import lombok.*; import javax.persistence.*; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.math.BigDecimal; @Data @Getter @Entity @Table(name = "fund_transfer_exchange") @Builder @NoArgsConstructor @AllArgsConstructor @ToString(exclude = {"mandate"}) public class FundTransferExchange { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonView(MandateView.Default.class) private Long id; @JsonIgnore @ManyToOne @JoinColumn(name = "mandate_id", nullable = false) private Mandate mandate; @NotBlank @JsonView(MandateView.Default.class) private String sourceFundIsin; @NotNull @Min(0) @Max(1) @JsonView(MandateView.Default.class) private BigDecimal amount; @NotNull @JsonView(MandateView.Default.class) private String targetFundIsin; }
Add shift field to exported csv
<!DOCTYPE html> <html> <table> <tr> <th>Course ID</th> <th>Course</th> <th>Student ID</th> <th>Student Name</th> <th>Student E-mail</th> <th>Enrollment Date</th> <th>Shift</th> </tr> @foreach($enrollments as $enrollment) <tr> <td>{{ $enrollment->course->id }}</td> <td>{{ $enrollment->course->name }}</td> <td>{{ $enrollment->student->student_number }}</td> <td>{{ $enrollment->student->user->name }}</td> <td>{{ $enrollment->student->user->email }}</td> <td>{{ $enrollment->student->created_at }}</td> <td>{{-- Shift field --}}</td> </tr> @endforeach </table> </html>
<!DOCTYPE html> <html> <table> <tr> <th>Course ID</th> <th>Course</th> <th>Student ID</th> <th>Student Name</th> <th>Student E-mail</th> <th>Enrollment Date</th> </tr> @foreach($enrollments as $enrollment) <tr> <td>{{ $enrollment->course->id }}</td> <td>{{ $enrollment->course->name }}</td> <td>{{ $enrollment->student->student_number }}</td> <td>{{ $enrollment->student->user->name }}</td> <td>{{ $enrollment->student->user->email }}</td> <td>{{ $enrollment->student->created_at }}</td> </tr> @endforeach </table> </html>
Test stderr and stdout print methods.
package no.cantara.performance.messagesampler; public class LatencyMessageSamplerTest { public static void main(String[] args) throws InterruptedException { final Object waitBus = new Object(); TimeWindowSampleCallback callback = latency -> latency.printToStandardError(); LatencyMessageSampler sampler = new LatencyMessageSampler(callback, 100); for (int i=0; i<40; i++) { long sentTime = System.currentTimeMillis(); synchronized (waitBus) { waitBus.wait(10, 0); } sampler.addMessage(sentTime, System.currentTimeMillis()); } sampler.getPrintableStatistics().printToStandardOutput(); } }
package no.cantara.performance.messagesampler; public class LatencyMessageSamplerTest { public static void main(String[] args) throws InterruptedException { final Object waitBus = new Object(); TimeWindowSampleCallback callback = latency -> System.out.println(latency.getJson()); LatencyMessageSampler sampler = new LatencyMessageSampler(callback, 100); for (int i=0; i<40; i++) { long sentTime = System.currentTimeMillis(); synchronized (waitBus) { waitBus.wait(10, 0); } sampler.addMessage(sentTime, System.currentTimeMillis()); } System.out.println(sampler.getPrintableStatistics().getJson()); } }
py3: Remove Python 2 compatibility code
import gmusicapi from mopidy import commands from oauth2client.client import OAuth2WebServerFlow class GMusicCommand(commands.Command): def __init__(self): super().__init__() self.add_child("login", LoginCommand()) class LoginCommand(commands.Command): def run(self, args, config): oauth_info = gmusicapi.Mobileclient._session_class.oauth flow = OAuth2WebServerFlow(**oauth_info._asdict()) print() print( "Go to the following URL to get an initial auth code, " "then provide it below:" ) print(flow.step1_get_authorize_url()) print() initial_code = input("code: ") credentials = flow.step2_exchange(initial_code) refresh_token = credentials.refresh_token print("\nPlease update your config to include the following:") print() print("[gmusic]") print("refresh_token =", refresh_token) print()
import gmusicapi from mopidy import commands from oauth2client.client import OAuth2WebServerFlow class GMusicCommand(commands.Command): def __init__(self): super().__init__() self.add_child("login", LoginCommand()) class LoginCommand(commands.Command): def run(self, args, config): oauth_info = gmusicapi.Mobileclient._session_class.oauth flow = OAuth2WebServerFlow(**oauth_info._asdict()) print() print( "Go to the following URL to get an initial auth code, then " + "provide it below: " + flow.step1_get_authorize_url() ) print() try: initial_code = raw_input("code: ") except NameError: # Python 3 initial_code = input("code: ") credentials = flow.step2_exchange(initial_code) refresh_token = credentials.refresh_token print("\nPlease update your config to include the following:") print() print("[gmusic]") print("refresh_token =", refresh_token) print()
Fix onError handler is called even on successful load This causes "re-fetching" problem, because onError handler clears webpack ``installedChunks`` state, which in this cases cleared "loaded bundle", instead of "stuck callbacks". See #1
patch(); function patch() { var ensure = __webpack_require__.e; var head = document.querySelector('head'); __webpack_require__.e = function(chunkId, callback) { var loaded = false; var handler = function(error) { if (loaded) return; loaded = true; callback(error); }; ensure(chunkId, function() { handler(); }); onError(function() { if (loaded) return; loaded = true; if (__webpack_require__.s) { __webpack_require__.s[chunkId] = void 0; } handler(true); }); }; function onError(callback) { var script = head.lastChild; if (script.tagName !== 'SCRIPT') { // throw new Error('Script is not a script'); console.warn('Script is not a script', script); return; } script.onload = script.onerror = function() { script.onload = script.onerror = null; callback(); }; }; };
patch(); function patch() { var ensure = __webpack_require__.e; var head = document.querySelector('head'); __webpack_require__.e = function(chunkId, callback) { var loaded = false; var handler = function(error) { if (loaded) return; loaded = true; callback(error); }; ensure(chunkId, function() { handler(); }); onError(function() { if (__webpack_require__.s) { __webpack_require__.s[chunkId] = void 0; } handler(true); }); }; function onError(callback) { var script = head.lastChild; if (script.tagName !== 'SCRIPT') { // throw new Error('Script is not a script'); console.warn('Script is not a script', script); return; } script.onload = script.onerror = function() { script.onload = script.onerror = null; callback(); }; }; };
Set autoUpdate to true if challenge is null Signed-off-by: Rafael Luis Ibasco <80d89b34d8cf04643e39f61fb924744a8cfa1566@gmail.com>
/* * Copyright (c) 2022 Asynchronous Game Query Library * * 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.ibasco.agql.protocols.valve.source.query.message; /** * A special {@link SourceQueryRequest} which supports challenge based protocols * * @author Rafael Luis Ibasco */ abstract public class SourceQueryAuthRequest extends SourceQueryRequest { private Integer challenge; private boolean autoUpdate; protected SourceQueryAuthRequest() { this(null); } protected SourceQueryAuthRequest(Integer challenge) { this.challenge = challenge; this.autoUpdate = challenge == null; } public Integer getChallenge() { return challenge; } public void setChallenge(Integer challenge) { this.challenge = challenge; } public boolean isAutoUpdate() { return autoUpdate; } public void setAutoUpdate(boolean autoUpdate) { this.autoUpdate = autoUpdate; } }
/* * Copyright 2022-2022 Asynchronous Game Query Library * * 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.ibasco.agql.protocols.valve.source.query.message; /** * A special {@link SourceQueryRequest} which supports challenge based protocols * * @author Rafael Luis Ibasco */ abstract public class SourceQueryAuthRequest extends SourceQueryRequest { private Integer challenge; private boolean autoUpdate = true; protected SourceQueryAuthRequest() { this(null); } protected SourceQueryAuthRequest(Integer challenge) { this.challenge = challenge; } public Integer getChallenge() { return challenge; } public void setChallenge(Integer challenge) { this.challenge = challenge; } public boolean isAutoUpdate() { return autoUpdate; } public void setAutoUpdate(boolean autoUpdate) { this.autoUpdate = autoUpdate; } }
Rename olfactory stimulus file and internal array. --HG-- branch : LPU
""" Create odorant stimuli in hd5 format """ """ Create the gexf configuration based on E. Hallem's cell paper on 2006 """ import numpy as np import h5py osn_num = 1375; f = h5py.File("olfactory_stimulus.h5","w") dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data point t = np.arange(0,dt*Nt,dt) I = -1.*0.0195 # amplitude of the onset odorant concentration u_on = I*np.ones( Ot, dtype=np.float64) u_off = np.zeros( Ot, dtype=np.float64) u_reset = np.zeros( Rt, dtype=np.float64) u = np.concatenate((u_off,u_reset,u_on,u_reset,u_off,u_reset,u_on)) u_all = np.transpose( np.kron( np.ones((osn_num,1)), u)) # create the dataset dset = f.create_dataset("real",(Nt, osn_num), dtype=np.float64,\ data = u_all) f.close()
""" Create odorant stimuli in hd5 format """ """ Create the gexf configuration based on E. Hallem's cell paper on 2006 """ import numpy as np import h5py osn_num = 1375; f = h5py.File("al.hdf5","w") dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data point t = np.arange(0,dt*Nt,dt) I = -1.*0.0195 # amplitude of the onset odorant concentration u_on = I*np.ones( Ot, dtype=np.float64) u_off = np.zeros( Ot, dtype=np.float64) u_reset = np.zeros( Rt, dtype=np.float64) u = np.concatenate((u_off,u_reset,u_on,u_reset,u_off,u_reset,u_on)) u_all = np.transpose( np.kron( np.ones((osn_num,1)), u)) # create the dataset dset = f.create_dataset("acetone_on_off.hdf5",(Nt, osn_num), dtype=np.float64,\ data = u_all) f.close()
Add correct path to tests
from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys requirements = [line.strip() for line in open('requirements.txt').readlines()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(['linear_solver/tests/tests.py']) sys.exit(errcode) setup(name='linear_solver', version='0.0', description='', url='http://github.com/tcmoore3/linear_solver', author='Timothy C. Moore', author_email='timothy.c.moore@vanderbilt.edu', license='MIT', packages=find_packages(), package_data={'linear_solver.testing': ['reference/*']}, install_requires=requirements, zip_safe=False, test_suite='linear_solver', cmdclass={'test': PyTest}, extras_require={'utils': ['pytest']}, )
from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys requirements = [line.strip() for line in open('requirements.txt').readlines()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(['linear_solver']) sys.exit(errcode) setup(name='linear_solver', version='0.0', description='', url='http://github.com/tcmoore3/linear_solver', author='Timothy C. Moore', author_email='timothy.c.moore@vanderbilt.edu', license='MIT', packages=find_packages(), package_data={'linear_solver.testing': ['reference/*']}, install_requires=requirements, zip_safe=False, test_suite='linear_solver', cmdclass={'test': PyTest}, extras_require={'utils': ['pytest']}, )
Add the simplest of simple `alert` error handling
"use strict"; var saveRow = require('../templates/save_row.html')(); module.exports = { events: { 'click .save-item': '_handleSave' }, render: function () { this.$el.append(saveRow) }, toggleLoaders: function (state) { this.$('.save-item').prop('disabled', state); this.$('.loader').toggle(state); }, _handleSave: function () { if (this.saveItem) { this.saveItem(); } else { this.defaultSave(); } }, handleError: function (errorObj) { alert(window.JSON.stringify(errorObj)); }, defaultSave: function () { var that = this; this.toggleLoaders(true); this.model.save() .always(this.toggleLoaders.bind(this, false)) .done(function () { window.location.href = that.model.url().replace('\/api\/', '/'); }) .fail(function (jqXHR, textStatus, error) { that.handleError(jqXHR.responseJSON); }); } }
"use strict"; var saveRow = require('../templates/save_row.html')(); module.exports = { events: { 'click .save-item': '_handleSave' }, render: function () { this.$el.append(saveRow) }, toggleLoaders: function (state) { this.$('.save-item').prop('disabled', state); this.$('.loader').toggle(state); }, _handleSave: function () { if (this.saveItem) { this.saveItem(); } else { this.defaultSave(); } }, defaultSave: function () { var that = this; this.toggleLoaders(true); this.model.save() .always(this.toggleLoaders.bind(this, false)) .done(function () { window.location.href = that.model.url().replace('\/api\/', '/'); }); } }
Use README.rst for long description
from setuptools import setup import os #Function to read README def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='clipboard_memo', version='0.1', description='A command-line clipboard manager', long_description=read('README.rst'), url='http://github.com/arafsheikh/clipboard-memo', author='Sheikh Araf', author_email='arafsheikh@rocketmail.com', license='MIT', keywords='clipboard memo manager command-line CLI', include_package_data=True, entry_points=''' [console_scripts] cmemo=clipboard_memo:main cmemo_direct=clipboard_memo:direct_save ''', py_modules=['clipboard_memo'], install_requires=[ 'pyperclip', ], )
from setuptools import setup import os #Function to read README def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='clipboard_memo', version='0.1', description='A command-line clipboard manager', long_description=read('README.md'), url='http://github.com/arafsheikh/clipboard-memo', author='Sheikh Araf', author_email='arafsheikh@rocketmail.com', license='MIT', keywords='clipboard memo manager command-line CLI', include_package_data=True, entry_points=''' [console_scripts] cmemo=clipboard_memo:main cmemo_direct=clipboard_memo:direct_save ''', py_modules=['clipboard_memo'], install_requires=[ 'pyperclip', ], )
Set language part global accesible
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Redirect; use Log; class LanguageController extends Controller { /** * Switch Language * * @param string $lang Locale full name * @return Redirect Redirect back to requesting URL */ public function switchLang($lang) { Log::info("Language switch Request to $lang"); if (array_key_exists($lang, Config::get('languages'))) { Log::info('Language Switched'); Session::set('applocale', $lang); $locale = \Locale::parseLocale($lang); Session::set('language', $locale['language']); } return Redirect::back(); } }
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Redirect; use Log; class LanguageController extends Controller { /** * Switch Language * * @param string $lang Locale full name * @return Redirect Redirect back to requesting URL */ public function switchLang($lang) { Log::info("Language switch Request to $lang"); if (array_key_exists($lang, Config::get('languages'))) { Log::info('Language Switched'); Session::set('applocale', $lang); } return Redirect::back(); } }
Switch magenta for lighter color
const BasicColorTheme = require('./templates/BasicColorTheme') const ColorSchemeTransformations = require('./ColorSchemeTransformations') const BasicTiming = require('./timings/BasicTiming') module.exports = { name: 'Gradient - Light', theme: BasicColorTheme( ColorSchemeTransformations.fromColorLight, BasicTiming, [{ 'background': 'linear-gradient(to bottom right, orange, red)' }, { 'background': 'linear-gradient(to bottom right, yellow, orange)' }, { 'background': 'linear-gradient(to bottom right, lime, yellow)' }, { 'background': 'linear-gradient(to bottom right, cyan, lime)' }], { weekend: { 'background': 'linear-gradient(to bottom right, #e5bcff, cyan)' }, holiday: { 'background': 'linear-gradient(to bottom right, cyan, #e5bcff)' } } ) }
const BasicColorTheme = require('./templates/BasicColorTheme') const ColorSchemeTransformations = require('./ColorSchemeTransformations') const BasicTiming = require('./timings/BasicTiming') module.exports = { name: 'Gradient - Light', theme: BasicColorTheme( ColorSchemeTransformations.fromColorLight, BasicTiming, [{ 'background': 'linear-gradient(to bottom right, orange, red)' }, { 'background': 'linear-gradient(to bottom right, yellow, orange)' }, { 'background': 'linear-gradient(to bottom right, lime, yellow)' }, { 'background': 'linear-gradient(to bottom right, cyan, lime)' }], { weekend: { 'background': 'linear-gradient(to bottom right, magenta, cyan)' }, holiday: { 'background': 'linear-gradient(to bottom right, cyan, magenta)' } } ) }
Set JavaScript file destination directory, after TypeScript compile
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tslint = require('gulp-tslint'); var jade = require('gulp-jade'); gulp.task('jade', function() { gulp.src('./src/views/*.jade') .pipe(jade()) .pipe(gulp.dest('./dist/')) }); gulp.task('typescript', function() { gulp.src('src/scripts/**/*.ts') .pipe(tslint()) .pipe(tslint.report('verbose')) .pipe(ts({ declarationFiles: true, target: 'es5' }) .pipe(gulp.dest('./dist/scripts/'))); }); gulp.task('default', function () { });
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tslint = require('gulp-tslint'); var jade = require('gulp-jade'); gulp.task('jade', function() { gulp.src('./src/views/*.jade') .pipe(jade()) .pipe(gulp.dest('./dist/')) }); gulp.task('typescript', function() { gulp.src('src/scripts/**/*.ts') .pipe(tslint()) .pipe(tslint.report('verbose')) .pipe(ts({ declarationFiles: true, target: 'es5' })); }); gulp.task('default', function () { });
Fix an issue with AuthProviderConfig handles Summary: Fixes T11156. These were never correct, but also never actually used until I made timelines load object handles unconditionally in D16111. Test Plan: Viewed an auth provider with transactions, no more fatal. Reviewers: chad Reviewed By: chad Maniphest Tasks: T11156 Differential Revision: https://secure.phabricator.com/D16128
<?php final class PhabricatorAuthAuthProviderPHIDType extends PhabricatorPHIDType { const TYPECONST = 'AUTH'; public function getTypeName() { return pht('Auth Provider'); } public function newObject() { return new PhabricatorAuthProviderConfig(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthProviderConfigQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $provider = $objects[$phid]->getProvider(); if ($provider) { $handle->setName($provider->getProviderName()); } } } }
<?php final class PhabricatorAuthAuthProviderPHIDType extends PhabricatorPHIDType { const TYPECONST = 'AUTH'; public function getTypeName() { return pht('Auth Provider'); } public function newObject() { return new PhabricatorAuthProviderConfig(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthProviderConfigQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $provider = $objects[$phid]; $handle->setName($provider->getProviderName()); } } }
Change data with empty json string
<?php /** * WebHook event manager * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) 2014, Mohammad Abdoli Rad * @author Mohammad Abdoli Rad <m.abdolirad@gmail.com> * @since Version 0.1.0 * @license http://opensource.org/licenses/MIT MIT license */ namespace WebHookEventManager; use WebHookEventManager\Service\GitHub\Request; /** * Class WebHook * * @package WebHookEventManager */ class WebHook { protected $service = null; protected $webHookService = null; /** * Get GitHub service * * @return Service\GitHub\WebHook */ public function getGitHubService() { $request = new Request(); if ($request->isValidOrigin()) { $data = $request->getContent(); } else { $data = '{}'; } $payload = new \WebHookEventManager\Service\GitHub\WebHook($data); return $payload; } }
<?php /** * WebHook event manager * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) 2014, Mohammad Abdoli Rad * @author Mohammad Abdoli Rad <m.abdolirad@gmail.com> * @since Version 0.1.0 * @license http://opensource.org/licenses/MIT MIT license */ namespace WebHookEventManager; use WebHookEventManager\Service\GitHub\Request; /** * Class WebHook * * @package WebHookEventManager */ class WebHook { protected $service = null; protected $webHookService = null; /** * Get GitHub service * * @return Service\GitHub\WebHook */ public function getGitHubService() { $request = new Request(); if ($request->isValidOrigin()) { $data = $request->getContent(); } else { $data = null; } $payload = new \WebHookEventManager\Service\GitHub\WebHook($data); return $payload; } }
Fix Dooh userType migration, ensure the userTypeId is correctly set
<?php /** * Copyright (C) 2019 Xibo Signage Ltd * * Xibo - Digital Signage - http://www.xibo.org.uk * * This file is part of Xibo. * * Xibo is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Xibo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Xibo. If not, see <http://www.gnu.org/licenses/>. */ use Phinx\Migration\AbstractMigration; class AddDoohUserTypeMigration extends AbstractMigration { /** @inheritdoc */ public function change() { $userTypeTable = $this->table('usertype'); if (!$this->fetchRow('SELECT * FROM usertype WHERE `userType` = \'DOOH\'')) { $userTypeTable->insert([ 'userTypeId' => 4, 'userType' => 'DOOH' ])->save(); } } }
<?php /** * Copyright (C) 2019 Xibo Signage Ltd * * Xibo - Digital Signage - http://www.xibo.org.uk * * This file is part of Xibo. * * Xibo is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Xibo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Xibo. If not, see <http://www.gnu.org/licenses/>. */ use Phinx\Migration\AbstractMigration; class AddDoohUserTypeMigration extends AbstractMigration { /** @inheritdoc */ public function change() { $userTypeTable = $this->table('usertype'); if (!$this->fetchRow('SELECT * FROM usertype WHERE `userType` = \'DOOH\'')) { $userTypeTable->insert([ 'userType' => 'DOOH' ])->save(); } } }
Refactor RelativeResize param extraction in filter loader Replace foreach() with something more clear, but functionally equivalent.
<?php namespace Liip\ImagineBundle\Imagine\Filter\Loader; use Liip\ImagineBundle\Imagine\Filter\RelativeResize; use Imagine\Exception\InvalidArgumentException, Imagine\Image\ImageInterface; /** * Loader for this bundle's relative resize filter. * * @author Jeremy Mikola <jmikola@gmail.com> */ class RelativeResizeFilterLoader implements LoaderInterface { /** * @see Liip\ImagineBundle\Imagine\Filter\Loader\LoaderInterface::load() */ public function load(ImageInterface $image, array $options = array()) { if (list($method, $parameter) = each($options)) { $filter = new RelativeResize($method, $parameter); return $filter->apply($image); } throw new InvalidArgumentException('Expected method/parameter pair, none given'); } }
<?php namespace Liip\ImagineBundle\Imagine\Filter\Loader; use Liip\ImagineBundle\Imagine\Filter\RelativeResize; use Imagine\Exception\InvalidArgumentException, Imagine\Image\ImageInterface; /** * Loader for this bundle's relative resize filter. * * @author Jeremy Mikola <jmikola@gmail.com> */ class RelativeResizeFilterLoader implements LoaderInterface { /** * @see Liip\ImagineBundle\Imagine\Filter\Loader\LoaderInterface::load() */ public function load(ImageInterface $image, array $options = array()) { foreach ($options as $method => $parameter) { $filter = new RelativeResize($method, $parameter); return $filter->apply($image); } throw new InvalidArgumentException('Expected method/parameter pair, none given'); } }
Remove unused queue type 'none'
package org.icij.extract; import java.util.Locale; /** * An enumerated list of implemented queue types. * * @author Matthew Caruana Galizia <mcaruana@icij.org> * @since 1.0.0-beta */ public enum DocumentQueueType { ARRAY, REDIS; /** * Return the name of the queue type. * * @return The name of the queue type. */ public String toString() { return name().toLowerCase(Locale.ROOT); } /** * Parse the given string representation of the type into an instance. * * @param queueType the type of queue as a string value * @return The type of queue as a {@link DocumentQueueType} instance. */ public static DocumentQueueType parse(final String queueType) { try { return valueOf(queueType.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("\"%s\" is not a valid queue type.", queueType)); } } }
package org.icij.extract; import java.util.Locale; /** * An enumerated list of implemented queue types. * * @author Matthew Caruana Galizia <mcaruana@icij.org> * @since 1.0.0-beta */ public enum DocumentQueueType { NONE, ARRAY, REDIS; /** * Return the name of the queue type. * * @return The name of the queue type. */ public String toString() { return name().toLowerCase(Locale.ROOT); } /** * Parse the given string representation of the type into an instance. * * @param queueType the type of queue as a string value * @return The type of queue as a {@link DocumentQueueType} instance. */ public static DocumentQueueType parse(final String queueType) { if (null == queueType) { return NONE; } try { return valueOf(queueType.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("\"%s\" is not a valid queue type.", queueType)); } } }
Add helper on not-well-formed commands
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my profile description or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") # mark as read if it # is not a mention n.mark() client.logout()
Fix a bug in .objective utility function
""" Object-oriented programming utilities. """ import inspect from taipan.functional import ensure_callable from taipan.strings import is_string __all__ = ['is_internal', 'is_magic'] def is_internal(member): """Checks whether given class/instance member, or its name, is internal.""" name = _get_member_name(member) return name.startswith('_') and not is_magic(name) def is_magic(member): """Checks whether given class/instance member, or its name, is "magic". Magic fields and methods have names that begin and end with double underscores, such ``__hash__`` or ``__eq__``. """ name = _get_member_name(member) return len(name) > 4 and name.startswith('__') and name.endswith('__') # Utility functions def _get_member_name(member): if is_string(member): return member # Python has no "field declaration" objects, so the only valid # class or instance member is actually a method from taipan.objective.methods import ensure_method ensure_method(member) return member.__name__ def _get_first_arg_name(function): argnames, _, _, _ = inspect.getargspec(function) return argnames[0] if argnames else None from .base import * from .methods import * from .modifiers import *
""" Object-oriented programming utilities. """ import inspect from taipan._compat import IS_PY26, IS_PY3 from taipan.functional import ensure_callable from taipan.strings import is_string __all__ = ['is_internal', 'is_magic'] def is_internal(member): """Checks whether given class/instance member, or its name, is internal.""" name = _get_member_name(member) return name.startswith('_') and not is_magic(name) def is_magic(member): """Checks whether given class/instance member, or its name, is "magic". Magic fields and methods have names that begin and end with double underscores, such ``__hash__`` or ``__eq__``. """ name = _get_member_name(member) return len(name) > 4 and name.startswith('__') and name.endswith('__') # Utility functions def _get_member_name(member): if is_string(member): return member # Python has no "field declaration" objects, so the only valid # class or instance member is actually a method ensure_method(member) return member.__name__ def _get_first_arg_name(function): argnames, _, _, _ = inspect.getargspec(function) return argnames[0] if argnames else None from .base import * from .methods import * from .modifiers import *
Fix shadow on iOS too
/** * A simple directive that will add or remove a class to the body of the document if the document has been scrolled. */ export function ScrollClass() { return { restrict: 'A', scope: {}, link: function($scope, elem, attrs) { const threshold = attrs.scrollClassThreshold || 0; function stickyHeader() { const scrolled = document.body.scrollTop > threshold || document.documentElement.scrollTop > threshold; elem[0].classList.toggle(attrs.scrollClass, scrolled); } let rafTimer; function scrollHandler() { cancelAnimationFrame(rafTimer); rafTimer = requestAnimationFrame(stickyHeader); } document.addEventListener('scroll', scrollHandler, false); $scope.$on('$destroy', () => { document.removeEventListener('scroll', scrollHandler); cancelAnimationFrame(rafTimer); }); } }; }
/** * A simple directive that will add or remove a class to the body of the document if the document has been scrolled. */ export function ScrollClass() { return { restrict: 'A', scope: {}, link: function($scope, elem, attrs) { const threshold = attrs.scrollClassThreshold || 0; function stickyHeader() { const scrolled = document.documentElement.scrollTop > threshold; elem[0].classList.toggle(attrs.scrollClass, scrolled); } let rafTimer; function scrollHandler() { cancelAnimationFrame(rafTimer); rafTimer = requestAnimationFrame(stickyHeader); } document.addEventListener('scroll', scrollHandler, false); $scope.$on('$destroy', () => { document.removeEventListener('scroll', scrollHandler); cancelAnimationFrame(rafTimer); }); } }; }
Make PHP5 lexer default DOMLex. git-svn-id: 25f448894bd6eb0cddf10ded73b4f5a7ea3203f3@84 48356398-32a2-884e-a903-53898d9a118a
<?php /** * Forgivingly lexes SGML style documents: HTML, XML, XHTML, etc. */ require_once 'HTMLPurifier/Token.php'; class HTMLPurifier_Lexer { function tokenizeHTML($string) { trigger_error('Call to abstract class', E_USER_ERROR); } // we don't really care if it's a reference or a copy function create($prototype = null) { static $lexer = null; if ($prototype) { $lexer = $prototype; } if (empty($lexer)) { if (version_compare(PHP_VERSION, '5', '>=')) { require_once 'HTMLPurifier/Lexer/DOMLex.php'; $lexer = new HTMLPurifier_Lexer_DOMLex(); } else { require_once 'HTMLPurifier/Lexer/DirectLex.php'; $lexer = new HTMLPurifier_Lexer_DirectLex(); } } return $lexer; } } ?>
<?php /** * Forgivingly lexes SGML style documents: HTML, XML, XHTML, etc. */ require_once 'HTMLPurifier/Token.php'; class HTMLPurifier_Lexer { function tokenizeHTML($string) { trigger_error('Call to abstract class', E_USER_ERROR); } // we don't really care if it's a reference or a copy function create($prototype = null) { static $lexer = null; if ($prototype) { $lexer = $prototype; } if (empty($lexer)) { require_once 'HTMLPurifier/Lexer/DirectLex.php'; $lexer = new HTMLPurifier_Lexer_DirectLex(); } return $lexer; } } ?>
Change comments to make sense
import sys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import tweepy #Get String to track on argTag = sys.argv[1] #Class for listening to all tweets class TweetListener(StreamListener): def on_status(self, status): print status.created_at #Write timestamp to file f = open("logs/" + argTag + ".txt", "a") f.write(str(status.created_at) + "\n") f.close() return True def on_error(self, status): print status if __name__ == '__main__': listener = TweetListener() #Keys CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' #Initialise and Authorise auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) stream = Stream(auth, listener) stream.filter(track = [argTag])
import sys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import tweepy #Get Hashtag to track argTag = sys.argv[1] #Class for listening to all tweets class TweetListener(StreamListener): def on_status(self, status): print status.created_at #Write timestamp to file f = open("logs/" + argTag + ".txt", "a") f.write(str(status.created_at) + "\n") f.close() return True def on_error(self, status): print status if __name__ == '__main__': listener = TweetListener() #Keys CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' #Initialise and Authorise auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) stream = Stream(auth, listener) stream.filter(track = [argTag])
Install uwsgi in venv on web upgrade
#!/usr/bin/python3 import errno import pathlib import platform import sys import subprocess def main(): dist = platform.dist() if dist[0] != 'debian' and dist[0] != 'Ubuntu': print('This script can only be run on Debian GNU/Linux or Ubuntu.') sys.exit(errno.EPERM) workdir = pathlib.Path(__file__).resolve().parent.parent with (workdir / 'etc' / 'revision.txt').open('r') as revision_file: revision = (revision_file.readline().strip()) venv_dir = pathlib.Path('/home/cliche/venv_{}'.format(revision)) subprocess.check_call( [ 'sudo', '-ucliche', str(venv_dir / 'bin' / 'pip'), 'install', 'uwsgi', ] ) if __name__ == '__main__': main()
#!/usr/bin/python3 import errno import pathlib import platform import sys import subprocess def main(): dist = platform.dist() if dist[0] != 'debian' and dist[0] != 'Ubuntu': print('This script can only be run on Debian GNU/Linux or Ubuntu.') sys.exit(errno.EPERM) workdir = pathlib.Path(__file__).resolve().parent.parent subprocess.check_call( [ 'cp' ] + [str(path) for path in ((workdir / 'scripts').glob('*'))] + [ str(workdir / 'deploy' / 'tmp' / 'scripts') ] ) if __name__ == '__main__': main()
Print the messages we sent.
// Defines the top-level angular functionality. This will likely be refactored // as I go. var pyrcApp = angular.module("pyrcApp", []); pyrcApp.controller("ircCtrl", function($scope) { $scope.messages = []; $scope.msg = ""; $scope.username = "Pyrc"; // Define the controller method for sending an IRC message. $scope.sendIrcMessage = function() { message = irc.privmsg("#python-requests", $scope.msg); window.conn.send(message); $scope.messages.push({ from: $scope.username, text: $scope.msg }); // Clear the message box. $scope.msg = ""; }; ircLoop($scope.username, function(message) { $scope.$apply(function() { if (message.command == "PRIVMSG") { $scope.messages.push({ from: message.prefix.split('!', 2)[0], text: message.trailing }); } }); }); });
// Defines the top-level angular functionality. This will likely be refactored // as I go. var pyrcApp = angular.module("pyrcApp", []); pyrcApp.controller("ircCtrl", function($scope) { $scope.messages = []; $scope.msg = ""; $scope.username = "Pyrc"; // Define the controller method for sending an IRC message. $scope.sendIrcMessage = function() { message = irc.privmsg("#python-requests", $scope.msg); window.conn.send(message); // Clear the message box. $scope.msg = ""; }; ircLoop($scope.username, function(message) { $scope.$apply(function() { if (message.command == "PRIVMSG") { $scope.messages.push({ from: message.prefix.split('!', 2)[0], text: message.trailing }); } }); }); });
ENH: Send contact emails to morten@divito.dk
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = strip_tags(htmlspecialchars($_POST['name'])); $email_address = strip_tags(htmlspecialchars($_POST['email'])); $phone = strip_tags(htmlspecialchars($_POST['phone'])); $message = strip_tags(htmlspecialchars($_POST['message'])); // Create the email and send the message $to = 'morten@divito.dk'; $email_subject = "Ny besked fra $name på divito.dk"; $email_body = "Ny besked fra kontaktfomularen på divito.dk.\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@divito.dk\n"; $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = strip_tags(htmlspecialchars($_POST['name'])); $email_address = strip_tags(htmlspecialchars($_POST['email'])); $phone = strip_tags(htmlspecialchars($_POST['phone'])); $message = strip_tags(htmlspecialchars($_POST['message'])); // Create the email and send the message $to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
Fix bug where chapter wasn't being saved into ref
import Core from './core'; // A search result for a Bible reference search class Reference { // Build the JSON for a search result constructor({name, uid, book, query, version, content}) { if (book && query && version) { this.uid = `${version.id}/${book.id}.${query.chapter}`; this.book = book; this.chapter = query.chapter; this.name = `${book.name} ${query.chapter}`; if (query.verse) { this.uid += `.${query.verse}`; this.name += `:${query.verse}`; this.verse = query.verse; } if (query.endVerse && query.endVerse > query.verse) { this.uid += `-${query.endVerse}`; this.name += `-${query.endVerse}`; this.endVerse = query.endVerse; } this.name += ` (${version.name})`; this.version = version; } else { this.name = name; this.uid = uid; if (content) { this.content = content; } } } // View this reference result on the YouVersion website view() { window.open(`${Core.baseRefURL}/${this.uid.toUpperCase()}`); } } export default Reference;
import Core from './core'; // A search result for a Bible reference search class Reference { // Build the JSON for a search result constructor({name, uid, book, query, version, content}) { if (book && query && version) { this.uid = `${version.id}/${book.id}.${query.chapter}`; this.book = book; this.name = `${book.name} ${query.chapter}`; if (query.verse) { this.uid += `.${query.verse}`; this.name += `:${query.verse}`; this.verse = query.verse; } if (query.endVerse && query.endVerse > query.verse) { this.uid += `-${query.endVerse}`; this.name += `-${query.endVerse}`; this.endVerse = query.endVerse; } this.name += ` (${version.name})`; this.version = version; } else { this.name = name; this.uid = uid; if (content) { this.content = content; } } } // View this reference result on the YouVersion website view() { window.open(`${Core.baseRefURL}/${this.uid.toUpperCase()}`); } } export default Reference;
Order votes by creation date when getting all
const db = require('./postgresql'); const { plainObject, plainObjectOrNull, deprecateObject } = require('./utils'); const Vote = db.sequelize.models.vote; function getVotes(question) { deprecateObject(question); const issueId = question.id || question; return Vote.findAll({ where: { issueId }, order: ['createdAt', 'ASC'], }).map(plainObject); } function getUserVote(issue, user) { deprecateObject(issue); const issueId = issue.id || issue; const userId = user.id || user; return plainObjectOrNull(Vote.findOne({ where: { issueId, userId } })); } function getAnonymousUserVote(issueId, anonymoususerId) { return plainObjectOrNull(Vote.findOne({ where: { issueId, anonymoususerId } })); } function createUserVote(userId, issueId, alternativeId) { return Vote.create({ userId, issueId, alternativeId }); } function createAnonymousVote(anonymoususerId, issueId, alternativeId) { return Vote.create({ anonymoususerId, issueId, alternativeId }); } module.exports = { getVotes, createUserVote, createAnonymousVote, getUserVote, getAnonymousUserVote, };
const db = require('./postgresql'); const { plainObject, plainObjectOrNull, deprecateObject } = require('./utils'); const Vote = db.sequelize.models.vote; function getVotes(question) { deprecateObject(question); const issueId = question.id || question; return Vote.findAll({ where: { issueId } }).map(plainObject); } function getUserVote(issue, user) { deprecateObject(issue); const issueId = issue.id || issue; const userId = user.id || user; return plainObjectOrNull(Vote.findOne({ where: { issueId, userId } })); } function getAnonymousUserVote(issueId, anonymoususerId) { return plainObjectOrNull(Vote.findOne({ where: { issueId, anonymoususerId } })); } function createUserVote(userId, issueId, alternativeId) { return Vote.create({ userId, issueId, alternativeId }); } function createAnonymousVote(anonymoususerId, issueId, alternativeId) { return Vote.create({ anonymoususerId, issueId, alternativeId }); } module.exports = { getVotes, createUserVote, createAnonymousVote, getUserVote, getAnonymousUserVote, };
Undo code for client logic
DropboxOAuth = {}; // Request dropbox credentials for the user // @param options {optional} // @param callback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. DropboxOAuth.requestCredential = function (options, callback) { // support both (options, callback) and (callback). if (!callback && typeof options === 'function') { callback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'dropbox'}); if (!config) { callback && callback(new ServiceConfiguration.ConfigError("Service not configured")); return; } var credentialToken = Random.secret(); var loginStyle = OAuth._loginStyle('dropbox', config, options); var loginUrl = 'https://www.dropbox.com/1/oauth2/authorize' + '?response_type=code' + '&client_id=' + config.clientId + '&redirect_uri=' + OAuth._redirectUri('dropbox', config, {}, {secure: true}) + '&state=' + OAuth._stateParam(loginStyle, credentialToken); loginUrl = loginUrl.replace('?close&', '?close=true&'); OAuth.launchLogin({ loginService: "dropbox", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: callback, credentialToken: credentialToken, popupOptions: { height: 600 } }); };
DropboxOAuth = {}; // Request dropbox credentials for the user // @param options {optional} // @param callback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. DropboxOAuth.requestCredential = function (options, callback) { // support both (options, callback) and (callback). if (!callback && typeof options === 'function') { callback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'dropbox'}); if (!config) { callback && callback(new ServiceConfiguration.ConfigError("Service not configured")); return; } var credentialToken = Random.secret(); var loginStyle = OAuth._loginStyle('dropbox', config, options); var loginUrl = 'https://www.dropbox.com/1/oauth2/authorize' + '?response_type=code' + '&client_id=' + config.clientId + '&redirect_uri=' + OAuth._redirectUri('dropbox', config, {}, {secure: true}) + '&state=' + OAuth._stateParam(loginStyle, credentialToken).replace('?close&', '?close=true&'); OAuth.launchLogin({ loginService: "dropbox", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: callback, credentialToken: credentialToken, popupOptions: { height: 600 } }); };
Change python version 3 -> 3.4
from setuptools import setup, find_packages setup( name='pylife', version='0.1.0', description='Conway\'s Game of Life with kivy', author='yukirin', author_email='standupdown@gmail.com', url='https://github.com/yukirin/LifeGame-kivy', license='MIT', keywords=['python', 'game', 'life game', 'kivy'], zip_safe=False, platforms=['Linux'], packages=find_packages(), package_data={'pylife': ['lifegame*.*']}, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3.4', 'Development Status :: 4 - Beta', 'Operating System :: POSIX :: Linux', 'Natural Language :: Japanese', 'License :: OSI Approved :: MIT License', 'Topic :: Games/Entertainment' ], install_requires = ['kivy'], entry_points={ 'gui_scripts': ['pylife = pylife.main:run'] }, )
from setuptools import setup, find_packages setup( name='pylife', version='0.1.0', description='Conway\'s Game of Life with kivy', author='yukirin', author_email='standupdown@gmail.com', url='https://github.com/yukirin/LifeGame-kivy', license='MIT', keywords=['python', 'game', 'life game', 'kivy'], zip_safe=False, platforms=['Linux'], packages=find_packages(), package_data={'pylife': ['lifegame*.*']}, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Development Status :: 4 - Beta', 'Operating System :: POSIX :: Linux', 'Natural Language :: Japanese', 'License :: OSI Approved :: MIT License', 'Topic :: Games/Entertainment' ], install_requires = ['kivy'], entry_points={ 'gui_scripts': ['pylife = pylife.main:run'] }, )
Add an override to console.warn for testing to suppress React warnings.
import React from 'react/addons'; let find = React.addons.TestUtils.findRenderedDOMComponentWithTag; let render = React.addons.TestUtils.renderIntoDocument; let Control = reqmod('components/control'); // Since we don't want React warnings about some deprecated stuff being spammed // in our test run, we disable the warnings with this... console.warn = () => { } /** * Control components are those little icon based buttons, which can be toggled * active. */ describe('components/control', () => { it('should render correctly', () => { // First we render the actual 'control' component into our 'document'. let controlComponent = render( <Control icon="book" onClick={() => {}} /> ); // Next we check that it has the correct class... It should not be // toggled 'active' by default. controlComponent.getDOMNode().className.should.equal('control'); // Retrieve the actual 'icon' component from inside the 'control'. let iconComponent = find(controlComponent, 'span'); // Make sure the 'book' icon is reflected in the CSS classes. iconComponent.getDOMNode().className.should.endWith('fa-book'); }); it('should be able to be toggled active', () => { let controlComponent = render( <Control icon="book" onClick={() => {}} active={true} /> ); controlComponent.getDOMNode().className.should.endWith('active'); }); });
import React from 'react/addons'; let find = React.addons.TestUtils.findRenderedDOMComponentWithTag; let render = React.addons.TestUtils.renderIntoDocument; let Control = reqmod('components/control'); /** * Control components are those little icon based buttons, which can be toggled * active. */ describe('components/control', () => { it('should render correctly', () => { // First we render the actual 'control' component into our 'document'. let controlComponent = render( <Control icon="book" onClick={() => {}} /> ); // Next we check that it has the correct class... It should not be // toggled 'active' by default. controlComponent.getDOMNode().className.should.equal('control'); // Retrieve the actual 'icon' component from inside the 'control'. let iconComponent = find(controlComponent, 'span'); // Make sure the 'book' icon is reflected in the CSS classes. iconComponent.getDOMNode().className.should.endWith('fa-book'); }); it('should be able to be toggled active', () => { let controlComponent = render( <Control icon="book" onClick={() => {}} active={true} /> ); controlComponent.getDOMNode().className.should.endWith('active'); }); });
Fix version-specific logic for symfony/process
<?php namespace Trafficgate\Transferer; use PackageVersions\Versions; use PHPUnit\Framework\TestCase; class CommandTestCase extends TestCase { /** * Empty quotes to use for symfony/process test comparators. * * @var string */ public $emptyQuotes; public function setUp(): void { $this->determineEmptyQuotesForSymfonyProcess(); } /** * Symfony/process returns either '' or "" depending on version for empty arguments. * * Versions less than or equal to 4.1.6 return ''. * Versions greather than or equal to 4.1.7 return "". */ private function determineEmptyQuotesForSymfonyProcess() { $this->emptyQuotes = "''"; $symfonyProcessVersion = substr( explode( '@', Versions::getVersion('symfony/process') )[0], 1 ); if (version_compare('4.1.7', $symfonyProcessVersion, '<')) { $this->emptyQuotes = '""'; } } }
<?php namespace Trafficgate\Transferer; use PackageVersions\Versions; use PHPUnit\Framework\TestCase; class CommandTestCase extends TestCase { /** * Empty quotes to use for symfony/process test comparators. * * @var string */ public $emptyQuotes; public function setUp(): void { $this->determineEmptyQuotesForSymfonyProcess(); } /** * Symfony/process returns either '' or "" depending on version. * * Versions less than or equal to 3.4.X return ''. * Versions greather than or equal to 4.0.0 return "". */ private function determineEmptyQuotesForSymfonyProcess() { $this->emptyQuotes = "''"; $symfonyProcessVersion = substr( explode( '@', Versions::getVersion('symfony/process') )[0], 1 ); if (version_compare('4.0.0', $symfonyProcessVersion, '<')) { $this->emptyQuotes = '""'; } } }
Remove import for graphite responder
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder from graphite import GraphiteResponder
Update comments to use new relationship structure
'use strict'; const _ = require('lodash'); function normalizeRelationships(relation, relatedName) { const related = {}; // This handles the short-hand syntax: // // people: 'many-to-one' // if (_.isString(relation)) { related.cardinality = relation; related.resource = relatedName; related.nullable = true; related.host = true; } // This handles the long-hand syntax: // // owner: { // resource: 'people', // cardinality: 'many-to-one' // } // else { related.resource = relation.resource; related.cardinality = relation.cardinality; // Ensure nullable is a Boolean, defaulting to `true`. if (!_.isUndefined(relation.nullable)) { related.nullable = Boolean(relation.nullable); } else { related.nullable = true; } // Ensure host is a Boolean, defaulting to `true`. if (!_.isUndefined(relation.host)) { related.host = Boolean(relation.host); } else { related.host = true; } } return related; } module.exports = function(relationships) { return _.mapValues(relationships, normalizeRelationships); };
'use strict'; const _ = require('lodash'); function normalizeRelationships(relation, relatedName) { const related = {}; // This handles the short-hand syntax: // // people: 'many-to-one' // if (_.isString(relation)) { related.cardinality = relation; related.resource = relatedName; related.nullable = true; related.host = true; } // This handles the long-hand syntax: // // owner: { // resource: 'people', // relationship: 'many-to-one' // } // else { related.resource = relation.resource; related.cardinality = relation.cardinality; // Ensure nullable is a Boolean, defaulting to `true`. if (!_.isUndefined(relation.nullable)) { related.nullable = Boolean(relation.nullable); } else { related.nullable = true; } // Ensure host is a Boolean, defaulting to `true`. if (!_.isUndefined(relation.host)) { related.host = Boolean(relation.host); } else { related.host = true; } } return related; } module.exports = function(relationships) { return _.mapValues(relationships, normalizeRelationships); };
Hide user-activity after 10 (instead of 7) days
<?php function smarty_function_user_activity(array $params, Smarty_Internal_Template $template) { $force_display = isset($params['force_display']); /** @var CM_Model_User $user */ $user = $params['user']; if ($user->getVisible()) { /** @var CM_Model_User $viewer */ return '<span class="online">Online</span>'; } $activity_stamp = $user->getLatestactivity(); $activity_delta = time() - $activity_stamp; if (!$force_display && $activity_delta > 10 * 86400) { return ''; } if (($activity_delta / 86400) >= 1) { $count = floor($activity_delta / 86400); $unit = 'd'; } elseif (($activity_delta / 3600) >= 1) { $count = floor($activity_delta / 3600); $unit = 'h'; } elseif (($activity_delta / 60) >= 1) { $count = floor($activity_delta / 60); $unit = 'm'; } else { $count = 1; $unit = 'm'; } return 'Online: ' . $count . '&nbsp;' . CM_Language::section('profile.labels')->text('activity_' . $unit); }
<?php function smarty_function_user_activity(array $params, Smarty_Internal_Template $template) { $force_display = isset($params['force_display']); /** @var CM_Model_User $user */ $user = $params['user']; if ($user->getVisible()) { /** @var CM_Model_User $viewer */ return '<span class="online">Online</span>'; } $activity_stamp = $user->getLatestactivity(); $activity_delta = time() - $activity_stamp; if (!$force_display && $activity_delta > 7 * 86400) { return ''; } if (($activity_delta / 86400) >= 1) { $count = floor($activity_delta / 86400); $unit = 'd'; } elseif (($activity_delta / 3600) >= 1) { $count = floor($activity_delta / 3600); $unit = 'h'; } elseif (($activity_delta / 60) >= 1) { $count = floor($activity_delta / 60); $unit = 'm'; } else { $count = 1; $unit = 'm'; } return 'Online: ' . $count . '&nbsp;' . CM_Language::section('profile.labels')->text('activity_' . $unit); }
Add default value for user role
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 60); $table->tinyInteger('role')->default(0); // default is normal user $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 60); $table->tinyInteger('role'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Include marker for form type
<?php add_action( 'wp_ajax_form_to_disk', 'form_to_disk' ); add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' ); $f2d_option = get_option( 'f2d_options', '' ); function form_to_disk() { global $f2d_option; date_default_timezone_set( 'America/Los_Angeles' ); if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) { $protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] ); $form_data = trim( $_POST[ 'firstName' ] ) . ','; $form_data .= trim( $_POST[ 'lastName' ] ) . ','; $form_data .= trim( $_POST[ 'email' ] ) . ','; $form_data .= trim( $_POST[ 'pageId' ] ); $entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' ) or die( 'Unable to process that request' ); $txt = date( 'Ymd' ); $txt .= ','; $txt .= $form_data; fwrite( $entries, $txt . PHP_EOL ); fclose( $entries ); die(); } }
<?php add_action( 'wp_ajax_form_to_disk', 'form_to_disk' ); add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' ); $f2d_option = get_option( 'f2d_options', '' ); function form_to_disk() { global $f2d_option; date_default_timezone_set('America/Los_Angeles'); if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) { $protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] ); $form_data = trim( $_POST[ 'firstName' ] ) . ','; $form_data .= trim( $_POST[ 'lastName' ] ) . ','; $form_data .= trim( $_POST[ 'email' ] ); $entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' ) or die( 'Unable to process that request' ); $txt = date( 'Ymd' ); $txt .= ','; $txt .= $form_data; fwrite( $entries, $txt . PHP_EOL ); fclose( $entries ); die(); } }
[INTERNAL][FIX] Fix walkthrough step 37 after simplification Change-Id: Id93e8d246a989e2116b442bcb644e09c8a52041a
sap.ui.define([ "sap/ui/base/Object" ], function (UI5Object) { "use strict"; return UI5Object.extend("sap.ui.demo.wt.controller.HelloDialog", { constructor : function (oView) { this._oView = oView; }, open : function () { var oView = this._oView; var oDialog = oView.byId("helloDialog"); // create dialog lazily if (!oDialog) { var oFragmentController = { onCloseDialog : function () { oDialog.close(); } }; // create dialog via fragment factory oDialog = sap.ui.xmlfragment(oView.getId(), "sap.ui.demo.wt.view.HelloDialog", oFragmentController); // connect dialog to the root view of this component (models, lifecycle) oView.addDependent(oDialog); // forward compact/cozy style into dialog jQuery.sap.syncStyleClass(oView.getController().getOwnerComponent().getContentDensityClass(), oView, oDialog); } oDialog.open(); } }); });
sap.ui.define([ "sap/ui/base/Object" ], function (UI5Object) { "use strict"; return UI5Object.extend("sap.ui.demo.wt.controller.HelloDialog", { constructor : function (oView) { this._oView = oView; }, open : function () { var oView = this._oView; var oDialog = oView.byId("helloDialog"); // create dialog lazily if (!oDialog) { var oFragmentController = { onCloseDialog : function () { oDialog.close(); } }; // create dialog via fragment factory oDialog = sap.ui.xmlfragment(oView.getId(), "sap.ui.demo.wt.view.HelloDialog", oFragmentController); // connect dialog to the root view of this component (models, lifecycle) oView.addDependent(oDialog); // forward compact/cozy style into dialog jQuery.sap.syncStyleClass(this._oView.getController().getOwnerComponent().getContentDensityClass(), this._oView, this._oDialog); } oDialog.open(); } }); });
Adjust template js style to rest
/* * <%= props.name %> * <%= props.homepage %> * * Copyright (c) <%= currentYear %> <%= props.author_name %> * Licensed under the <%= props.license %> license. */ (function ($) { // Collection method. $.fn.awesome = function () { return this.each(function (i) { // Do something awesome to each selected element. $(this).html('awesome' + i); }); }; // Static method. $.awesome = function (options) { // Override default options with passed-in options. options = $.extend({}, $.awesome.options, options); // Return something awesome. return 'awesome' + options.punctuation; }; // Static method default options. $.awesome.options = { punctuation: '.' }; // Custom selector. $.expr[':'].awesome = function (elem) { // Is this element awesome? return $(elem).text().indexOf('awesome') !== -1; }; }(jQuery));
/* * <%= props.name %> * <%= props.homepage %> * * Copyright (c) <%= currentYear %> <%= props.author_name %> * Licensed under the <%= props.license %> license. */ (function($) { // Collection method. $.fn.awesome = function() { return this.each(function(i) { // Do something awesome to each selected element. $(this).html('awesome' + i); }); }; // Static method. $.awesome = function(options) { // Override default options with passed-in options. options = $.extend({}, $.awesome.options, options); // Return something awesome. return 'awesome' + options.punctuation; }; // Static method default options. $.awesome.options = { punctuation: '.' }; // Custom selector. $.expr[':'].awesome = function(elem) { // Is this element awesome? return $(elem).text().indexOf('awesome') !== -1; }; }(jQuery));
Fix missing semicolon and missing trailing comma.
import React from 'react'; import refractToComponentsMap from 'refractToComponentMap'; import theme from 'theme'; class Attribute extends React.Component { static propTypes = { element: React.PropTypes.object, expandableCollapsible: React.PropTypes.bool, parentElement: React.PropTypes.object, } static childContextTypes = { theme: React.PropTypes.object, } constructor(props) { super(props); } getChildContext() { return { theme, }; } render() { if (!this.props.element) { return false; } const reactComponent = refractToComponentsMap[this.props.element.element]; if (typeof reactComponent === 'undefined') { return new Error(`Unable to find a rendering component for ${this.props.element.element}`); } return React.createElement(reactComponent, { element: this.props.element, expandableCollapsible: this.props.expandableCollapsible, parentElement: this.props.parentElement, }); } } export default Attribute;
import React from 'react'; import refractToComponentsMap from 'refractToComponentMap'; import theme from 'theme' class Attribute extends React.Component { static propTypes = { element: React.PropTypes.object, expandableCollapsible: React.PropTypes.bool, parentElement: React.PropTypes.object, } static childContextTypes = { theme: React.PropTypes.object, } constructor(props) { super(props); } getChildContext() { return { theme }; } render() { if (!this.props.element) { return false; } const reactComponent = refractToComponentsMap[this.props.element.element]; if (typeof reactComponent === 'undefined') { return new Error(`Unable to find a rendering component for ${this.props.element.element}`); } return React.createElement(reactComponent, { element: this.props.element, expandableCollapsible: this.props.expandableCollapsible, parentElement: this.props.parentElement, }); } } export default Attribute;
Use EventEmitter instead of Timer to load mainpage.js
'use strict'; // This script will be invoked by `./loader.js` with `require` after the Discord App is loaded. const path = require('path'); const electron = require('electron'); const {app} = electron; const loaderConfig = require('./loaderconfig.js').acquire(); console.info('::: loaded', __filename); app.on('browser-window-created', (event, window) => { const webContents = window.webContents; // we have to observe 'did-finish-load' // see https://github.com/electron/electron/blob/master/lib/browser/api/web-contents.js webContents.on('did-finish-load', () => { const url = webContents.getURL(); if (!/^https?:\/\/[\w\.-]+\/channels(\/|$)/.test(url)) return; const mainpageJs = path.join(loaderConfig.invokerDir, 'mainpage.js'); webContents.executeJavaScript(`if(!window.isMainPageScriptLoaded){window.isMainPageScriptLoaded=true;require(${JSON.stringify(mainpageJs)})}`); }); }); require(path.join(loaderConfig.userDir, 'after.js'));
'use strict'; // This script will be invoked by `./loader.js` with `require` after the Discord App is loaded. const path = require('path'); const electron = require('electron'); const {BrowserWindow} = electron; const loaderConfig = require('./loaderconfig.js').acquire(); console.info('::: loaded', __filename); function checkFunc() { const mainpageJs = path.join(loaderConfig.invokerDir, 'mainpage.js'); BrowserWindow.getAllWindows().forEach(window => { const contents = window.webContents; const url = contents.getURL(); if (/^https?:\/\/[\w\.-]+\/channels(\/|$)/.test(url)) { contents.executeJavaScript(`if(!window.isScriptLoaded){window.isScriptLoaded=true;require(${JSON.stringify(mainpageJs)})}`); } }); } (function monitorWebpage() { checkFunc(); setTimeout(monitorWebpage, 1000); })(); require(path.join(loaderConfig.userDir, 'after.js'));
Update 0.1.1 - Added api number reference
import time import datetime import requests import json def get_NEO_flyby(): neo_data = [] des = 0 orbit_id = 1 jd = 2 cd = 3 dist = 4 dist_min = 5 dist_max = 6 v_rel = 7 v_inf = 8 t_signma_F = 9 body = 10 h = 11 unix = time.time() datestamp = datetime.datetime.fromtimestamp(unix).strftime("%Y-%b-%d") json_data_url = requests.get("https://ssd-api.jpl.nasa.gov/cad.api?body=Earth&dist-max=20LD") json_data = json.loads(json_data_url.text) for i in range(len(json_data["data"])): neo_date = json_data["data"][i][cd][:11] neo_time = json_data["data"][i][cd][11:] if neo_date == datestamp: neo_data.append((json_data["data"][i][des],)) # sorte lieber per magnitude und nimm nur das größte objekt, sonst ist der tweet zu lang get_NEO_flyby() # TODO: Iterate over data and return tuple
import time import datetime import requests import json def get_NEO_flyby(): neo_data = [] unix = time.time() datestamp = datetime.datetime.fromtimestamp(unix).strftime("%Y-%b-%d") json_data_url = requests.get("https://ssd-api.jpl.nasa.gov/cad.api?body=Earth&dist-max=20LD") json_data = json.loads(json_data_url.text) for i in range(len(json_data["data"])): neo_date = json_data["data"][i][3][:11] neo_time = json_data["data"][i][3][11:] if neo_date == datestamp: neo_data.append((json_data["data"][i][0],)) # sorte lieber per magnitude und nimm nur das größte objekt, sonst ist der tweet zu lang get_NEO_flyby() # TODO: Add api indicator of numbers # TODO: Iterate over data and return tuple
Add user if not exist
//js for first creation of event. var sql = require('./sql'); exports.createNewEvent = function(req, res){ console.log(req.user); if(!req.user){ res.render('facebook.html'); } //should have a session and profile object. else{ //generate new game: for now just load up current game var fbid = req.user.facebook.id; var uid; var gid; sql.getUserFromFbid(getUid, fbid); function getUid(err, rows){ //take the rows and grab if(err){ console.log(err); } uid = rows[0]; } if (uid == null){//need to add this user sql.registerUser(function(err){}, fbid, req.user.facebook.name); } else{ sql.getGroupsFromUid(getGid, uid); function getGid(err, rows){ if(err){ console.log(err); } gid = rows[0]; } } res.redirect('/game/'+ 1); } };
//js for first creation of event. var sql = require('./sql'); exports.createNewEvent = function(req, res){ console.log(req.user); if(!req.user){ res.render('facebook.html'); } //should have a session and profile object. else{ //generate new game: for now just load up current game var fbid; var uid; var gid; sql.getUserFromFbid(getUid, req.user.facebook.id); function getUid(err, rows){ //take the rows and grab if(err){ console.log(err); } uid = rows[0]; } sql.getGroupsFromUid(getGid, uid); function getGid(err, rows){ if(err){ console.log(err); } gid = rows[0]; } res.redirect('/game/'+gid); } };
Add end of line character
/** * Copyright (c) 2018, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.case_projector; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import com.powsybl.commons.config.InMemoryPlatformConfig; import com.powsybl.commons.config.PlatformConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.FileSystem; public class CaseProjectorPostProcessorTest { private FileSystem fileSystem; private PlatformConfig platformConfig; private PlatformConfig createEmptyPlatformConfig() { fileSystem = Jimfs.newFileSystem(Configuration.unix()); platformConfig = new InMemoryPlatformConfig(fileSystem); return platformConfig; } @Before public void setUp() throws Exception { fileSystem = Jimfs.newFileSystem(Configuration.unix()); platformConfig = createEmptyPlatformConfig(); } @After public void tearDown() throws Exception { fileSystem.close(); } @Test public void testInstCaseProjectorPostProcessor() throws Exception { //when there is no case-projector section, in the configuration, this constructor should not throw any exception CaseProjectorPostProcessor postProcessor = new CaseProjectorPostProcessor(); } }
/** * Copyright (c) 2018, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.case_projector; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import com.powsybl.commons.config.InMemoryPlatformConfig; import com.powsybl.commons.config.PlatformConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.FileSystem; public class CaseProjectorPostProcessorTest { private FileSystem fileSystem; private PlatformConfig platformConfig; private PlatformConfig createEmptyPlatformConfig() { fileSystem = Jimfs.newFileSystem(Configuration.unix()); platformConfig = new InMemoryPlatformConfig(fileSystem); return platformConfig; } @Before public void setUp() throws Exception { fileSystem = Jimfs.newFileSystem(Configuration.unix()); platformConfig = createEmptyPlatformConfig(); } @After public void tearDown() throws Exception { fileSystem.close(); } @Test public void testInstCaseProjectorPostProcessor() throws Exception { //when there is no case-projector section, in the configuration, this constructor should not throw any exception CaseProjectorPostProcessor postProcessor = new CaseProjectorPostProcessor(); } }
Add a --quiet option to the send_all management command.
import logging from django.conf import settings from django.core.management.base import NoArgsCommand from optparse import make_option from mailer.engine import send_all # allow a sysadmin to pause the sending of mail temporarily. PAUSE_SEND = getattr(settings, "MAILER_PAUSE_SEND", False) class Command(NoArgsCommand): help = "Do one pass through the mail queue, attempting to send all mail." option_list = NoArgsCommand.option_list + ( make_option('-q', '--quiet', dest='quiet', default=False, action='store_true', help='Silence output unless an error occurs.'), ) def handle_noargs(self, **options): quiet = options.get('quiet', False) # Set logging level if quiet if quiet: logging.disable(logging.INFO) logging.basicConfig(level=logging.DEBUG, format="%(message)s") logging.info("-" * 72) # if PAUSE_SEND is turned on don't do anything. if not PAUSE_SEND: send_all() else: logging.info("sending is paused, quitting.")
import logging from django.conf import settings from django.core.management.base import NoArgsCommand from mailer.engine import send_all # allow a sysadmin to pause the sending of mail temporarily. PAUSE_SEND = getattr(settings, "MAILER_PAUSE_SEND", False) class Command(NoArgsCommand): help = "Do one pass through the mail queue, attempting to send all mail." def handle_noargs(self, **options): logging.basicConfig(level=logging.DEBUG, format="%(message)s") logging.info("-" * 72) # if PAUSE_SEND is turned on don't do anything. if not PAUSE_SEND: send_all() else: logging.info("sending is paused, quitting.")
Use process.env.MONGOLAB_URI instead of hard-coded URI
var path = require('path'), rootPath = path.normalize(__dirname + '/..'), env = process.env.NODE_ENV || 'development'; var config = { development: { root: rootPath, app: { name: 'teaching-heigvd-tweb-2015-project' }, port: 3000, db: 'mongodb://localhost/teaching-heigvd-tweb-2015-project-development' }, test: { root: rootPath, app: { name: 'teaching-heigvd-tweb-2015-project' }, port: 3000, db: 'mongodb://localhost/teaching-heigvd-tweb-2015-project-test' }, production: { root: rootPath, app: { name: 'teaching-heigvd-tweb-2015-project' }, port: process.env.PORT, db: process.env.MONGOLAB_URI //db: 'mongodb://jermoret:_Ma$t3rQ#b0rd@ds045454.mongolab.com:45454/heroku_scf8b718' } }; module.exports = config[env];
var path = require('path'), rootPath = path.normalize(__dirname + '/..'), env = process.env.NODE_ENV || 'development'; var config = { development: { root: rootPath, app: { name: 'teaching-heigvd-tweb-2015-project' }, port: 3000, db: 'mongodb://localhost/teaching-heigvd-tweb-2015-project-development' }, test: { root: rootPath, app: { name: 'teaching-heigvd-tweb-2015-project' }, port: 3000, db: 'mongodb://localhost/teaching-heigvd-tweb-2015-project-test' }, production: { root: rootPath, app: { name: 'teaching-heigvd-tweb-2015-project' }, port: process.env.PORT, //db: process.env.MONGOLAB_URI db: 'mongodb://jermoret:_Ma$t3rQ#b0rd@ds045454.mongolab.com:45454/heroku_scf8b718' } }; module.exports = config[env];
GoogleJsapi: Load Google JS API only if not already present on the page
import Component from '@ember/component'; function createEvent(name) { let event = document.createEvent('Event'); event.initEvent(name, true, true); return event; } export default Component.extend({ tagName: '', didInsertElement() { loadJsApi() .then(api => loadCoreChart(api)) .then(() => { window.googleChartsLoaded = true; document.dispatchEvent(createEvent('googleChartsLoaded')); }); }, }); async function loadScript(src) { await new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; script.onload = resolve; script.onerror = reject; document.body.appendChild(script); }); } async function loadJsApi() { if (!window.google) { await loadScript('https://www.google.com/jsapi'); } return window.google; } async function loadCoreChart(api) { await new Promise(resolve => { api.load('visualization', '1.0', { packages: ['corechart'], callback: resolve, }); }); }
import Component from '@ember/component'; function createEvent(name) { let event = document.createEvent('Event'); event.initEvent(name, true, true); return event; } export default Component.extend({ tagName: '', didInsertElement() { loadJsApi() .then(api => loadCoreChart(api)) .then(() => { window.googleChartsLoaded = true; document.dispatchEvent(createEvent('googleChartsLoaded')); }); }, }); async function loadScript(src) { await new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; script.onload = resolve; script.onerror = reject; document.body.appendChild(script); }); } async function loadJsApi() { await loadScript('https://www.google.com/jsapi'); return window.google; } async function loadCoreChart(api) { await new Promise(resolve => { api.load('visualization', '1.0', { packages: ['corechart'], callback: resolve, }); }); }
Make Eventer.removeListener actually, like, remove passed listener.
;(function(exports) { function Eventer() { var callbacks = {}; this.addListener = function(obj, event, callback) { callbacks[event] = callbacks[event] || []; callbacks[event].push({ obj: obj, callback: callback }); return this; }; this.addListener this.on = this.addListener; this.removeListener = function(obj, event) { for(var i = 0; i < callbacks[event].length; i++) { if(callbacks[event][i].obj === obj) { callbacks[event].splice(i, 1); break; } } }; this.emit = function(event, data) { var eventCallbacks = callbacks[event]; if(eventCallbacks !== undefined) { for(var i = 0; i < eventCallbacks.length; i++) { var callbackObj = eventCallbacks[i]; callbackObj.callback.call(callbackObj.obj, data); } } return this; }; } exports.Eventer = Eventer; })(typeof exports === 'undefined' ? this : exports)
;(function(exports) { function Eventer() { var callbacks = {}; this.addListener = function(obj, event, callback) { callbacks[event] = callbacks[event] || []; callbacks[event].push({ obj: obj, callback: callback }); return this; }; this.addListener this.on = this.addListener; this.removeListener = function(obj, event) { for(var i in callbacks) { if(callbacks[i].obj === obj) { delete callbacks[i]; break; } } }; this.emit = function(event, data) { var eventCallbacks = callbacks[event]; if(eventCallbacks !== undefined) { for(var i = 0; i < eventCallbacks.length; i++) { var callbackObj = eventCallbacks[i]; callbackObj.callback.call(callbackObj.obj, data); } } return this; }; } exports.Eventer = Eventer; })(typeof exports === 'undefined' ? this : exports)
Add block-based effect target flag
package com.elmakers.mine.bukkit.api.effect; import org.bukkit.Color; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.api.block.MaterialAndData; import org.bukkit.entity.Entity; import java.util.Collection; import java.util.Map; public interface EffectPlayer { public void setEffectPlayList(Collection<EffectPlay> plays); public void setEffect(Effect effect); public void setEffectData(int data); public void setScale(float scale); public void setSound(Sound sound); public void setSound(Sound sound, float volume, float pitch); public void setParameterMap(Map<String, String> parameters); public void setDelayTicks(int ticks); public void setParticleOverride(String particleType); public void setMaterial(MaterialAndData material); public void setMaterial(Block block); public void setColor(Color color); public boolean shouldUseHitLocation(); public boolean shouldUseWandLocation(); public boolean shouldUseEyeLocation(); public boolean shouldUseBlockLocation(); public void start(Location origin, Location target); public void start(Entity origin, Entity target); public void start(Location origin, Entity originEntity, Location target, Entity targetEntity); public void start(Location origin, Entity originEntity, Location target, Entity targetEntity, Collection<Entity> targets); }
package com.elmakers.mine.bukkit.api.effect; import org.bukkit.Color; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.api.block.MaterialAndData; import org.bukkit.entity.Entity; import java.util.Collection; import java.util.Map; public interface EffectPlayer { public void setEffectPlayList(Collection<EffectPlay> plays); public void setEffect(Effect effect); public void setEffectData(int data); public void setScale(float scale); public void setSound(Sound sound); public void setSound(Sound sound, float volume, float pitch); public void setParameterMap(Map<String, String> parameters); public void setDelayTicks(int ticks); public void setParticleOverride(String particleType); public void setMaterial(MaterialAndData material); public void setMaterial(Block block); public void setColor(Color color); public boolean shouldUseHitLocation(); public boolean shouldUseWandLocation(); public boolean shouldUseEyeLocation(); public void start(Location origin, Location target); public void start(Entity origin, Entity target); public void start(Location origin, Entity originEntity, Location target, Entity targetEntity); public void start(Location origin, Entity originEntity, Location target, Entity targetEntity, Collection<Entity> targets); }
Update service provider Applications , JwtAuth
<?php namespace JwtAuth; use Illuminate\Support\ServiceProvider; class JwtAuthServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { // Find path to the package $componenentsFileName = with(new ReflectionClass('\JwtAuth\JwtAuthServiceProvider'))->getFileName(); $componenentsPath = dirname($componenentsFileName); $this->loadViewsFrom($componenentsPath . '/../views', 'jwtauth'); // include $componenentsPath . '/../routes.php'; } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
<?php namespace JwtAuth; use Illuminate\Support\ServiceProvider; class JwtAuthServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }