text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add verbose as viper flag and fix spelling
|
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
)
var verbose bool = false
var cfgFile string
var RootCmd = &cobra.Command{
Short: "Proj simplifies local development config",
Long: ``,
}
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "$HOME/.proj.yaml", "Path to config file")
RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose logs")
viper.BindPFlag("verbose", RootCmd.PersistentFlags().Lookup("verbose"))
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
}
viper.SetConfigName(".proj") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
viper.AutomaticEnv() // read in environment variables that match
viper.SetEnvPrefix("proj")
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
|
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
)
var Vebose bool = false
var cfgFile string
var RootCmd = &cobra.Command{
Short: "Proj simplifies local development config",
Long: ``,
}
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "$HOME/.proj.yaml", "Path to config file")
RootCmd.PersistentFlags().BoolVarP(&Vebose, "verbose", "v", false, "Enable verbose logs")
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
}
viper.SetConfigName(".proj") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
viper.AutomaticEnv() // read in environment variables that match
viper.SetEnvPrefix("proj")
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
|
Update the AI Intrumentation Key
|
var appInsights=window.appInsights||function(config){
function r(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o="script",s=u.createElement(o),i,f;s.src=config.url||"//az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(s);try{t.cookie=u.cookie}catch(h){}for(t.queue=[],i=["Event","Exception","Metric","PageView","Trace","Dependency"];i.length;)r("track"+i.pop());return r("setAuthenticatedUserContext"),r("clearAuthenticatedUserContext"),config.disableExceptionTracking||(i="onerror",r("_"+i),f=e[i],e[i]=function(config,r,u,e,o){var s=f&&f(config,r,u,e,o);return s!==!0&&t["_"+i](config,r,u,e,o),s}),t
}({
instrumentationKey:"2e94078d-9bcc-42cf-948f-e1b386240ded"
});
window.appInsights=appInsights;
appInsights.trackPageView();
|
var appInsights=window.appInsights||function(config){
function r(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o="script",s=u.createElement(o),i,f;s.src=config.url||"//az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(s);try{t.cookie=u.cookie}catch(h){}for(t.queue=[],i=["Event","Exception","Metric","PageView","Trace","Dependency"];i.length;)r("track"+i.pop());return r("setAuthenticatedUserContext"),r("clearAuthenticatedUserContext"),config.disableExceptionTracking||(i="onerror",r("_"+i),f=e[i],e[i]=function(config,r,u,e,o){var s=f&&f(config,r,u,e,o);return s!==!0&&t["_"+i](config,r,u,e,o),s}),t
}({
instrumentationKey:"9ba12fc8-eff5-4671-9458-673d465a9297"
});
window.appInsights=appInsights;
appInsights.trackPageView();
|
Fix changing locale after app has booted
|
<?php namespace Jenssegers\Date;
use Illuminate\Support\ServiceProvider;
class DateServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->app['events']->listen('locale.changed', function() {
$this->setLocale();
});
$this->setLocale();
}
/**
* Set the locale.
*
*/
protected function setLocale()
{
$locale = $this->app['translator']->getLocale();
Date::setLocale($locale);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// Nothing.
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['Date'];
}
}
|
<?php namespace Jenssegers\Date;
use Illuminate\Support\ServiceProvider;
class DateServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$locale = $this->app['translator']->getLocale();
Date::setLocale($locale);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// Nothing.
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['Date'];
}
}
|
Add more info to bad command warning
|
#!/usr/bin/env node
(function() {
'use strict';
var program = require('commander');
var packageInfo = require('../package.json');
var openurl = require('openurl');
program
.usage('[options]')
.description('Radiian creates Ansible provisioning files for immutable infrastructure on AWS.\n' +
' Run `radiian init` to begin.')
.version(packageInfo.version)
.option('-o, --online-help', 'Opens online help');
program
.command('init', 'initiate/start radiian')
.action(function(input) {
if(input !== 'init') {
console.log('\nError: unknown option `' + input + '`. Run `radiian --help` for help.\n');
}
});
program.parse(process.argv);
// If no arguments are passed, display help menu
if (!process.argv.slice(2).length) { program.help(); }
if (program.onlineHelp) {
openurl.open('https://github.com/radify/radiian#readme');
}
}());
|
#!/usr/bin/env node
(function() {
'use strict';
var program = require('commander');
var packageInfo = require('../package.json');
var openurl = require('openurl');
program
.usage('[options]')
.description('Radiian creates Ansible provisioning files for immutable infrastructure on AWS.\n' +
' Run `radiian init` to begin.')
.version(packageInfo.version)
.option('-o, --online-help', 'Opens online help');
program
.command('init', 'initiate/start radiian')
.action(function(input) {
if(input !== 'init') {
console.log('\nerror: unknown option `' + input + '`\n');
}
});
program.parse(process.argv);
// If no arguments are passed, display help menu
if (!process.argv.slice(2).length) { program.help(); }
if (program.onlineHelp) {
openurl.open('https://github.com/radify/radiian#readme');
}
}());
|
Improve after PR on ChainAdapter
|
<?php
/*
* This file is part of php-cache organization.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\AdapterBundle\Factory;
use Cache\Adapter\Chain\CachePoolChain;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @author Aaron Scherer <aequasi@gmail.com>
*/
class ChainFactory extends AbstractAdapterFactory
{
protected static $dependencies = [
['requiredClass' => 'Cache\Adapter\Chain\CachePoolChain', 'packageName' => 'cache/chain-adapter'],
];
/**
* {@inheritdoc}
*/
public function getAdapter(array $config)
{
return new CachePoolChain($config['services'], ['skip_on_failure' => $config['skipOnFailure']]);
}
/**
* {@inheritdoc}
*/
protected static function configureOptionResolver(OptionsResolver $resolver)
{
parent::configureOptionResolver($resolver);
$resolver->setRequired('services');
$resolver->setAllowedTypes('services', ['array']);
$resolver->setDefault('skipOnFailure', false);
}
}
|
<?php
/*
* This file is part of php-cache organization.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\AdapterBundle\Factory;
use Cache\Adapter\Chain\CachePoolChain;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @author Aaron Scherer <aequasi@gmail.com>
*/
class ChainFactory extends AbstractAdapterFactory
{
protected static $dependencies = [
['requiredClass' => 'Cache\Adapter\Chain\CachePoolChain', 'packageName' => 'cache/chain-adapter'],
];
/**
* {@inheritdoc}
*/
public function getAdapter(array $config)
{
return new CachePoolChain($config['services'], $config['skipOnFailure']);
}
/**
* {@inheritdoc}
*/
protected static function configureOptionResolver(OptionsResolver $resolver)
{
parent::configureOptionResolver($resolver);
$resolver->setRequired('services');
$resolver->setAllowedTypes('services', ['array']);
$resolver->setDefault('skipOnFailure', false);
}
}
|
Fix flake8 warning when running on Python 3
|
from __future__ import print_function
import logging
import sys
import threading
import time
import spotify
if len(sys.argv) != 3:
sys.exit('Usage: %s USERNAME PASSWORD' % sys.argv[0])
username, password = sys.argv[1], sys.argv[2]
def login(session, username, password):
logged_in_event = threading.Event()
def logged_in_listener(session, error_type):
logged_in_event.set()
session.on(spotify.SessionEvent.LOGGED_IN, logged_in_listener)
session.login(username, password)
if not logged_in_event.wait(10):
raise RuntimeError('Login timed out')
while session.connection.state != spotify.ConnectionState.LOGGED_IN:
time.sleep(0.1)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
session = spotify.Session()
loop = spotify.EventLoop(session)
loop.start()
login(session, username, password)
logger.debug('Getting playlist')
pl = session.get_playlist(
'spotify:user:durden20:playlist:1chOHrXPCFcShCwB357MFX')
logger.debug('Got playlist %r %r', pl, pl._sp_playlist)
logger.debug('Loading playlist %r %r', pl, pl._sp_playlist)
pl.load()
logger.debug('Loaded playlist %r %r', pl, pl._sp_playlist)
print(pl)
print(pl.tracks)
|
import logging
import sys
import threading
import time
import spotify
if len(sys.argv) != 3:
sys.exit('Usage: %s USERNAME PASSWORD' % sys.argv[0])
username, password = sys.argv[1], sys.argv[2]
def login(session, username, password):
logged_in_event = threading.Event()
def logged_in_listener(session, error_type):
logged_in_event.set()
session.on(spotify.SessionEvent.LOGGED_IN, logged_in_listener)
session.login(username, password)
if not logged_in_event.wait(10):
raise RuntimeError('Login timed out')
while session.connection.state != spotify.ConnectionState.LOGGED_IN:
time.sleep(0.1)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
session = spotify.Session()
loop = spotify.EventLoop(session)
loop.start()
login(session, username, password)
logger.debug('Getting playlist')
pl = session.get_playlist(
'spotify:user:durden20:playlist:1chOHrXPCFcShCwB357MFX')
logger.debug('Got playlist %r %r', pl, pl._sp_playlist)
logger.debug('Loading playlist %r %r', pl, pl._sp_playlist)
pl.load()
logger.debug('Loaded playlist %r %r', pl, pl._sp_playlist)
print pl
print pl.tracks
|
Use the new pref name for the remote server URL
|
// Stalling server
// https://bugzilla.mozilla.org/show_bug.cgi?id=1165816
//
// To use:
//
// 1. start the server using `node ./index.js`
// 2. set `browser.safebrowsing.downloads.remote.url` to `http://localhost:8000`
// 3. go to <http://testsafebrowsing.appspot.com/> and download the second binary under "Download Warnings"
const http = require('http');
var server = http.createServer(
function (request, response) {
var data = '';
request.on('data', function (chunk) {
data += chunk;
});
request.on('end', function () {
console.log(request.method + ' ' + request.url);
console.log(request.headers);
console.log(data);
// just stall, don't return
});
}
);
const PORT = 8000;
server.listen(PORT);
console.log('Listening at http://localhost:' + PORT);
|
// Stalling server
// https://bugzilla.mozilla.org/show_bug.cgi?id=1165816
//
// To use:
//
// 1. start the server using `node ./index.js`
// 2. set browser.safebrowsing.appRepURL` to `http://localhost:8000`
// 3. go to <http://testsafebrowsing.appspot.com/> and download the second binary under "Download Warnings"
const http = require('http');
var server = http.createServer(
function (request, response) {
var data = '';
request.on('data', function (chunk) {
data += chunk;
});
request.on('end', function () {
console.log(request.method + ' ' + request.url);
console.log(request.headers);
console.log(data);
// just stall, don't return
});
}
);
const PORT = 8000;
server.listen(PORT);
console.log('Listening at http://localhost:' + PORT);
|
Allow to customize the default avatar by context
|
// Package public adds some public routes that can be used to give information
// to anonymous users, or to the not yet authentified cozy owner on its login
// page.
package public
import (
"net/http"
"time"
"github.com/cozy/cozy-stack/pkg/statik/fs"
"github.com/cozy/cozy-stack/web/middlewares"
"github.com/cozy/cozy-stack/web/statik"
"github.com/cozy/echo"
)
// Avatar returns the default avatar currently.
func Avatar(c echo.Context) error {
inst := middlewares.GetInstance(c)
f, ok := fs.Get("/images/default-avatar.png", inst.ContextName)
if !ok {
f, ok = fs.Get("/images/default-avatar.png", "")
if !ok {
return echo.NewHTTPError(http.StatusNotFound, "Page not found")
}
}
handler := statik.NewHandler()
handler.ServeFile(c.Response(), c.Request(), f, true)
return nil
}
// Routes sets the routing for the public service
func Routes(router *echo.Group) {
cacheControl := middlewares.CacheControl(middlewares.CacheOptions{
MaxAge: 24 * time.Hour,
})
router.GET("/avatar", Avatar, cacheControl, middlewares.NeedInstance)
}
|
// Package public adds some public routes that can be used to give information
// to anonymous users, or to the not yet authentified cozy owner on its login
// page.
package public
import (
"net/http"
"time"
"github.com/cozy/cozy-stack/pkg/statik/fs"
"github.com/cozy/cozy-stack/web/middlewares"
"github.com/cozy/cozy-stack/web/statik"
"github.com/cozy/echo"
)
// Avatar returns the default avatar currently.
func Avatar(c echo.Context) error {
f, ok := fs.Get("/images/default-avatar.png", "")
if !ok {
return echo.NewHTTPError(http.StatusNotFound, "Page not found")
}
handler := statik.NewHandler()
handler.ServeFile(c.Response(), c.Request(), f, true)
return nil
}
// Routes sets the routing for the public service
func Routes(router *echo.Group) {
cacheControl := middlewares.CacheControl(middlewares.CacheOptions{
MaxAge: 24 * time.Hour,
})
router.GET("/avatar", Avatar, cacheControl)
}
|
Fix compiler error on validate budget handler
|
package org.openlmis.core.upload;
import org.openlmis.core.domain.BaseModel;
import org.openlmis.core.domain.Budget;
import org.openlmis.core.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BudgetHandler extends AbstractModelPersistenceHandler {
@Autowired
private BudgetService service;
@Autowired
private FacilityService facilityService;
@Autowired
private ProgramService programService;
@Autowired
private ProcessingPeriodService processingPeriodService;
@Override
protected BaseModel getExisting(BaseModel record) {
Budget budget = ((Budget) record);
return service.getByCodes(budget.getProgram().getCode(), budget.getPeriod().getName(), budget.getFacility().getCode() );
}
@Override
protected void save(BaseModel record) {
fillReferenceData((Budget) record);
validateBudget((Budget) record);
service.save((Budget) record);
}
private void fillReferenceData(Budget budget){
// set the id's of all reference data
// this is to make sure that the save routine will be able to save this budget information
budget.setFacility( facilityService.getByCode(budget.getFacility() ) );
budget.setProgram( programService.getByCode(budget.getProgram().getCode()));
budget.getPeriod().setId(processingPeriodService.getIdByName(budget.getPeriod().getName()));
}
private void validateBudget(Budget budget){
}
@Override
protected String getDuplicateMessageKey() {
return "error.duplicate.Budget";
}
}
|
package org.openlmis.core.upload;
import org.openlmis.core.domain.BaseModel;
import org.openlmis.core.domain.Budget;
import org.openlmis.core.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BudgetHandler extends AbstractModelPersistenceHandler {
@Autowired
private BudgetService service;
@Autowired
private FacilityService facilityService;
@Autowired
private ProgramService programService;
@Autowired
private ProcessingPeriodService processingPeriodService;
@Override
protected BaseModel getExisting(BaseModel record) {
Budget budget = ((Budget) record);
return service.getByCodes(budget.getProgram().getCode(), budget.getPeriod().getName(), budget.getFacility().getCode() );
}
@Override
protected void save(BaseModel record) {
fillReferenceData((Budget) record);
validateBudget((Budget) record);
service.save((Budget) record);
}
private void fillReferenceData(Budget budget){
// set the id's of all reference data
// this is to make sure that the save routine will be able to save this budget information
budget.setFacility( facilityService.getByCode(budget.getFacility() ) );
budget.setProgram( programService.getByCode(budget.getProgram().getCode()));
budget.getPeriod().setId(processingPeriodService.getIdByName(budget.getPeriod().getName()));
}
private void validateBudget(Budget budget){
facilityService.is
}
@Override
protected String getDuplicateMessageKey() {
return "error.duplicate.Budget";
}
}
|
Remove explicit layout; too eager
|
import Ember from 'ember';
import Stage from '../system/stage';
export default Ember.Component.extend({
classNames: [ 'data-visual' ],
width: 300,
height: 150,
stage: null,
initializeGraphicsContext() {
var element = this.element;
var fragment = document.createDocumentFragment();
Stage.stages.forEach(stage => {
fragment.appendChild(document.createComment(stage));
});
element.insertBefore(fragment, element.firstChild);
this.set('stage', Stage.create({ element }));
this.measure();
},
measure() {
this.set('width', this.$().width());
this.set('height', this.$().height());
},
didInsertElement() {
Ember.$(window).on(`resize.${this.get('elementId')}`, Ember.run.bind(this, this.measure));
Ember.run.scheduleOnce('render', this, this.initializeGraphicsContext);
},
willDestroyElement() {
Ember.$(window).off(`resize.${this.get('elementId')}`);
}
});
|
import Ember from 'ember';
import layout from '../templates/components/data-visual';
import Stage from '../system/stage';
export default Ember.Component.extend({
classNames: [ 'data-visual' ],
layout,
width: 300,
height: 150,
stage: null,
initializeGraphicsContext() {
var element = this.element;
var fragment = document.createDocumentFragment();
Stage.stages.forEach(stage => {
fragment.appendChild(document.createComment(stage));
});
element.insertBefore(fragment, element.firstChild);
this.set('stage', Stage.create({ element }));
this.measure();
},
measure() {
this.set('width', this.$().width());
this.set('height', this.$().height());
},
didInsertElement() {
Ember.$(window).on(`resize.${this.get('elementId')}`, Ember.run.bind(this, this.measure));
Ember.run.scheduleOnce('render', this, this.initializeGraphicsContext);
},
willDestroyElement() {
Ember.$(window).off(`resize.${this.get('elementId')}`);
}
});
|
Fix qmentaobject test to work with dynamic metaobject.
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests for static methos conflicts with class methods'''
import unittest
from PySide.QtCore import *
class Foo(QFile):
pass
class qmetaobject_test(unittest.TestCase):
def test_QMetaObject(self):
qobj = QObject()
qobj_metaobj = qobj.metaObject()
self.assertEqual(qobj_metaobj.className(), "QObject")
obj = QFile()
m = obj.metaObject()
self.assertEqual(m.className(), "QFile")
self.assertNotEqual(m.methodCount(), qobj_metaobj.methodCount())
obj = Foo()
m = obj.metaObject()
self.assertEqual(m.className(), "Foo")
f = QFile()
fm = f.metaObject()
self.assertEqual(m.methodCount(), fm.methodCount())
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests for static methos conflicts with class methods'''
import unittest
from PySide.QtCore import *
class Foo(QFile):
pass
class qmetaobject_test(unittest.TestCase):
def test_QMetaObject(self):
qobj = QObject()
qobj_metaobj = qobj.metaObject()
self.assertEqual(qobj_metaobj.className(), "QObject")
obj = QFile()
m = obj.metaObject()
self.assertEqual(m.className(), "QFile")
self.assertNotEqual(m.methodCount(), qobj_metaobj.methodCount())
obj = Foo()
m = obj.metaObject()
self.assertEqual(m.className(), "Foo")
self.assertEqual(m.methodCount(), QFile().metaObject().methodCount())
if __name__ == '__main__':
unittest.main()
|
Remove XFAIL on functional tor test
|
import os
import re
import pytest
sdvars = pytest.securedrop_test_vars
@pytest.mark.parametrize('site', sdvars.tor_url_files)
@pytest.mark.skipif(os.environ.get('FPF_CI', 'false') == "false",
reason="Can only assure Tor is configured in CI atm")
def test_www(Command, site):
"""
Ensure tor interface is reachable and returns expected content.
"""
# Extract Onion URL from saved onion file, fetched back from app-staging.
onion_url_filepath = os.path.join(
os.path.dirname(__file__),
"../../install_files/ansible-base/{}".format(site['file'])
)
onion_url_raw = open(onion_url_filepath, 'ro').read()
onion_url = re.search("\w+\.onion", onion_url_raw).group()
# Fetch Onion URL via curl to confirm interface is rendered correctly.
curl_tor = 'curl -s --socks5-hostname "${{TOR_PROXY}}":9050 {}'.format(
onion_url)
curl_tor_status = '{} -o /dev/null -w "%{{http_code}}"'.format(curl_tor)
site_scrape = Command.check_output(curl_tor)
assert Command.check_output(curl_tor_status) == "200"
assert site['check_string'] in site_scrape
assert site['error_string'] not in site_scrape
|
import os
import re
import pytest
sdvars = pytest.securedrop_test_vars
@pytest.mark.xfail
@pytest.mark.parametrize('site', sdvars.tor_url_files)
@pytest.mark.skipif(os.environ.get('FPF_CI', 'false') == "false",
reason="Can only assure Tor is configured in CI atm")
def test_www(Command, site):
"""
Ensure tor interface is reachable and returns expected content.
"""
# Extract Onion URL from saved onion file, fetched back from app-staging.
onion_url_filepath = os.path.join(
os.path.dirname(__file__),
"../../install_files/ansible-base/{}".format(site['file'])
)
onion_url_raw = open(onion_url_filepath, 'ro').read()
onion_url = re.search("\w+\.onion", onion_url_raw).group()
# Fetch Onion URL via curl to confirm interface is rendered correctly.
curl_tor = 'curl -s --socks5-hostname "${{TOR_PROXY}}":9050 {}'.format(
onion_url)
curl_tor_status = '{} -o /dev/null -w "%{{http_code}}"'.format(curl_tor)
site_scrape = Command.check_output(curl_tor)
assert Command.check_output(curl_tor_status) == "200"
assert site['check_string'] in site_scrape
assert site['error_string'] not in site_scrape
|
XWIKI-2054: Add Utility API to remove all non alpha numeric chartacters from some text
* Fixed unit tests so that it works on all system encodings
Note: I don't know to test an accent properly...
git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@7268 f329d543-caf0-0310-9063-dda96c69346f
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.util;
import junit.framework.TestCase;
/**
* Unit tests for {@link com.xpn.xwiki.util.Util}.
*
* @version $Id: $
*/
public class UtilTest extends TestCase
{
public void testConvertToAlphaNumeric()
{
assertEquals("Search", Util.convertToAlphaNumeric("Search"));
assertEquals("Search", Util.convertToAlphaNumeric("S.earch"));
assertEquals("e", Util.convertToAlphaNumeric("e$%#^()"));
}
}
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.util;
import junit.framework.TestCase;
/**
* Unit tests for {@link com.xpn.xwiki.util.Util}.
*
* @version $Id: $
*/
public class UtilTest extends TestCase
{
public void testConvertToAlphaNumeric()
{
assertEquals("Search", Util.convertToAlphaNumeric("Search"));
assertEquals("Search", Util.convertToAlphaNumeric("S.earch"));
assertEquals("e", Util.convertToAlphaNumeric("$%#^()"));
}
}
|
Remove more unneeded DI in mFA
|
"use strict";
angular.module('arethusa.morph').directive('morphFormAttributes', [
'morph',
function(morph) {
return {
restrict: 'A',
scope: {
form: '=morphFormAttributes',
tokenId: '='
},
link: function(scope, element, attrs) {
var id = scope.tokenId;
scope.m = morph;
scope.attrs = morph.sortAttributes(scope.form.attributes);
scope.inv = scope.form.lexInv;
scope.askForRemoval = function() {
scope.confirmationRequested = true;
};
scope.skipRemoval = function() {
scope.confirmationRequested = false;
};
scope.removeForm = function() {
if (scope.form.selected) {
morph.unsetState(id);
}
morph.removeForm(id, scope.form);
};
},
templateUrl: 'templates/arethusa.morph/morph_form_attributes.html'
};
}
]);
|
"use strict";
angular.module('arethusa.morph').directive('morphFormAttributes', [
'morph',
'$document',
function(morph, $document) {
return {
restrict: 'A',
scope: {
form: '=morphFormAttributes',
tokenId: '='
},
link: function(scope, element, attrs) {
var id = scope.tokenId;
scope.m = morph;
scope.attrs = morph.sortAttributes(scope.form.attributes);
scope.inv = scope.form.lexInv;
scope.askForRemoval = function() {
scope.confirmationRequested = true;
};
scope.skipRemoval = function() {
scope.confirmationRequested = false;
};
scope.removeForm = function() {
if (scope.form.selected) {
morph.unsetState(id);
}
morph.removeForm(id, scope.form);
};
},
templateUrl: 'templates/arethusa.morph/morph_form_attributes.html'
};
}
]);
|
Remove star section from help
|
import React from 'react';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import './Help.css';
const Help = ({ sidebarExpanded }) => {
const marginStyles = {
expanded: {
marginLeft: 200,
},
mini: {
marginLeft: 56,
},
};
return (
<div
className="Help"
style={
sidebarExpanded ?
marginStyles.expanded :
marginStyles.mini
}
>
<List>
<ListItem
primaryText="Version"
secondaryText="Flex (1.0.0)"
/>
<Divider />
<ListItem
primaryText="Github repository"
secondaryText="https://github.com/mkermani144/wanna"
/>
<Divider />
<ListItem
primaryText="License"
secondaryText="MIT"
/>
<Divider />
</List>
</div>
);
};
export default Help;
|
import React from 'react';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import './Help.css';
const Help = ({ sidebarExpanded }) => {
const marginStyles = {
expanded: {
marginLeft: 200,
},
mini: {
marginLeft: 56,
},
};
return (
<div
className="Help"
style={
sidebarExpanded ?
marginStyles.expanded :
marginStyles.mini
}
>
<List>
<ListItem
primaryText="Version"
secondaryText="Flex (1.0.0)"
/>
<Divider />
<ListItem
primaryText="Github repository"
secondaryText="https://github.com/mkermani144/wanna"
/>
<Divider />
<ListItem
primaryText="Star Wanna on Github"
secondaryText="Stars: 6"
/>
<Divider />
<ListItem
primaryText="License"
secondaryText="MIT"
/>
<Divider />
</List>
</div>
);
};
export default Help;
|
Tweak SimpleRunner.run: make it close to the parallel one
|
from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
for parent in task.get_parents():
# This is redundant because `.load` or `.run` is called
# for *all* tasks regardless the state (need rerun or not).
cls.run(parent)
# .. note:: Do *not* put ``cls.run(parent)`` in the next try
# block because the error in parent task is treated by its
# `post_error_run` hook.
task.pre_run()
try:
if task.is_finished():
task.load()
else:
task.run()
task.post_success_run()
except Exception as e:
task.post_error_run(e)
raise
|
from .base import BaseRunner
class SimpleRunner(BaseRunner):
"""
Simple blocking task runner.
"""
@classmethod
def run(cls, task):
"""
Simple blocking task runner.
Run `task` and its unfinished ancestors.
"""
task.pre_run()
try:
for parent in task.get_parents():
# This is redundant because `.load` or `.run` is called
# for *all* tasks regardless the state (need rerun or not).
cls.run(parent)
if task.is_finished():
task.load()
else:
task.run()
task.post_success_run()
except Exception as e:
task.post_error_run(e)
raise
|
Update CoffeeScript docs to use the current ES6 syntax
|
// CoffeeScript compilation. This must be enabled by modification
// of Gruntfile.js.
//
// The `bare` option is used since this file will be transpiled
// anyway. In CoffeeScript files, you need to escape out for
// some ES6 features like import and export. For example:
//
// `import User from 'appkit/models/user'`
//
// Post = Em.Object.extend
// init: (userId) ->
// @set 'user', User.findById(userId)
//
// `export default Post`
//
module.exports = {
"test": {
options: {
bare: true
},
files: [{
expand: true,
cwd: 'tests/',
src: ['**/*.coffee', '!vendor/**/*.coffee'],
dest: 'tmp/javascript/tests',
ext: '.js'
}]
},
"app": {
options: {
bare: true
},
files: [{
expand: true,
cwd: 'app/',
src: '**/*.coffee',
dest: 'tmp/javascript/app',
ext: '.js'
}]
}
};
|
// CoffeeScript compilation. This must be enabled by modification
// of Gruntfile.js.
//
// The `bare` option is used since this file will be transpiled
// anyway. In CoffeeScript files, you need to escape out for
// some ES6 features like import and export. For example:
//
// `import 'appkit/models/user' as User`
//
// Posts = Em.Object.extend
// init: (userId) ->
// @set 'user', User.findById(userId)
//
// `export = Posts`
//
module.exports = {
"test": {
options: {
bare: true
},
files: [{
expand: true,
cwd: 'tests/',
src: ['**/*.coffee', '!vendor/**/*.coffee'],
dest: 'tmp/javascript/tests',
ext: '.js'
}]
},
"app": {
options: {
bare: true
},
files: [{
expand: true,
cwd: 'app/',
src: '**/*.coffee',
dest: 'tmp/javascript/app',
ext: '.js'
}]
}
};
|
Add breadcrumb comment for future debugging purposes
[#129559315]
|
'use strict';
import localForage from 'localforage';
import React, { Component, PropTypes } from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import { persistStore } from 'redux-persist';
import routes from '../routes';
export default class Root extends Component {
constructor() {
super();
this.state = { rehydrated: false };
}
/* Moving the persistStore() call to this event handler to prevent the root
* view from loading until after the store has been rehydrated
*
* HINT: call persistStore(...).purge() to clear all data if things get out
* of whack
*/
componentWillMount() {
persistStore(this.props.store, { storage: localForage }, () => {
this.setState({ rehydrated: true });
});
}
render() {
if (!this.state.rehydrated) {
return null;
}
const { history, store } = this.props;
return (
<Provider store={store}>
<div>
<Router history={history} routes={routes} />
</div>
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
|
'use strict';
import localForage from 'localforage';
import React, { Component, PropTypes } from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import { persistStore } from 'redux-persist';
import routes from '../routes';
export default class Root extends Component {
constructor() {
super();
this.state = { rehydrated: false };
}
// Moving the persistStore() call to this event handler to prevent the root
// view from loading until after the store has been rehydrated
componentWillMount() {
persistStore(this.props.store, { storage: localForage }, () => {
this.setState({ rehydrated: true });
});
}
render() {
if (!this.state.rehydrated) {
return null;
}
const { history, store } = this.props;
return (
<Provider store={store}>
<div>
<Router history={history} routes={routes} />
</div>
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
|
Replace if with just an else
|
<?php
/**
* Created by PhpStorm.
* User: inste
* Date: 07.09.2015
* Time: 16.17
*/
$langs = [
'en' => 'English',
'no' => 'Norsk',
];
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'en';
}
else{
$_SESSION['lang'] = $_POST['lang'];
}
function trans($index, $replace = ''){
global $langs;
$text = include('lang/'.$langs[$_SESSION['lang']].'.php');
$text = $text[$index];
if($replace !== ''){
foreach($replace as $key => $word){
$text = str_replace(':'.$key, $word, $text);
}
}
$text = htmlentities($text);
$text = str_replace(["<i>", "<b>", "</i>", "</b>", "<br />", "<br/>"], ["<i>", "<b>", "</i>", "</b>", "<br />", "<br />"], $text);
return $text;
}
|
<?php
/**
* Created by PhpStorm.
* User: inste
* Date: 07.09.2015
* Time: 16.17
*/
$langs = [
'en' => 'English',
'no' => 'Norsk',
];
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'en';
}
if(isset($_POST['lang'])){
$_SESSION['lang'] = $_POST['lang'];
}
function trans($index, $replace = ''){
global $langs;
$text = include('lang/'.$langs[$_SESSION['lang']].'.php');
$text = $text[$index];
if($replace !== ''){
foreach($replace as $key => $word){
$text = str_replace(':'.$key, $word, $text);
}
}
$text = htmlentities($text);
$text = str_replace(["<i>", "<b>", "</i>", "</b>", "<br />", "<br/>"], ["<i>", "<b>", "</i>", "</b>", "<br />", "<br />"], $text);
return $text;
}
|
Stop right trimming markdown strings
|
import showdown from "showdown"
module.exports = {
getShowdownConverter: (mediaPath) => {
return new showdown.Converter({
extensions: [
(converter) => [
{
type : "lang",
filter : md => md.trimLeft().replace(/(^\b.+\b: .*|^---$)[\s\S]*?---/m, "")
},
{
type : "lang",
regex : /(!\[.*?\]\()((?!http)\/?)/g,
replace : `$1file://${encodeURI(mediaPath)}/`
}
]
]
})
}
}
|
import showdown from "showdown"
module.exports = {
getShowdownConverter: (mediaPath) => {
return new showdown.Converter({
extensions: [
(converter) => [
{
type : "lang",
filter : md => md.trim().replace(/(^\b.+\b: .*|^---$)[\s\S]*?---/m, "")
},
{
type : "lang",
regex : /(!\[.*?\]\()((?!http)\/?)/g,
replace : `$1file://${encodeURI(mediaPath)}/`
}
]
]
})
}
}
|
Apply long log formatter only in debug
|
import sys
import logging
def init_logger(formatter):
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(formatter))
logging.basicConfig(
level=logging.INFO,
handlers=[handler])
return handler, logging.getLogger('CARTOframes')
handler, log = init_logger('%(message)s')
def set_log_level(level):
"""Set the level of the log in the library.
Args:
level (str): log level name. By default it's set to "info". Valid log levels are:
critical, error, warning, info, debug, notset.
"""
levels = {
'critical': logging.CRITICAL,
'error': logging.ERROR,
'warning': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG,
'notset': logging.NOTSET
}
if level not in levels:
return ValueError('Wrong log level. Valid log levels are: critical, error, warning, info, debug, notset.')
level = levels[level]
if level == logging.DEBUG:
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
else:
handler.setFormatter(logging.Formatter('%(message)s'))
log.setLevel(level)
|
import sys
import logging
def init_logger():
logging.basicConfig(
stream=sys.stdout,
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO)
return logging.getLogger('CARTOframes')
def set_log_level(level):
"""Set the level of the log in the library.
Args:
level (str): log level name. By default it's set to "info". Valid log levels are:
critical, error, warning, info, debug, notset.
"""
levels = {
'critical': logging.CRITICAL,
'error': logging.ERROR,
'warning': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG,
'notset': logging.NOTSET
}
if level not in levels:
return ValueError('Wrong log level. Valid log levels are: critical, error, warning, info, debug, notset.')
log.setLevel(levels[level])
log = init_logger()
|
Update docker images to version 33
|
/*
* 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 io.prestosql.tests.product.launcher.env;
public final class EnvironmentDefaults
{
public static final String DOCKER_IMAGES_VERSION = "33";
public static final String HADOOP_BASE_IMAGE = "prestodev/hdp2.6-hive";
public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";
private EnvironmentDefaults() {}
}
|
/*
* 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 io.prestosql.tests.product.launcher.env;
public final class EnvironmentDefaults
{
public static final String DOCKER_IMAGES_VERSION = "32";
public static final String HADOOP_BASE_IMAGE = "prestodev/hdp2.6-hive";
public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";
private EnvironmentDefaults() {}
}
|
Change default value for overwire
|
<?php
/**
* This file is part of the Kappa\FileSystem package.
*
* (c) Ondřej Záruba <zarubaondra@gmail.com>
*
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Kappa\FileSystem;
/**
* Class FileSystem
* @package Kappa\FileSystem
*/
class FileSystem
{
/**
* @param File|Directory $object
* @throws InvalidArgumentException
*/
public static function remove($object)
{
if (!$object instanceof File && !$object instanceof Directory) {
throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
}
\Nette\Utils\FileSystem::delete($object->getInfo()->getPathname());
}
/**
* @param File|Directory $object
* @param string $newName
* @param bool $overwrite
* @return Directory|File
* @throws InvalidArgumentException
*/
public static function rename($object, $newName, $overwrite = true)
{
if (!$object instanceof File && !$object instanceof Directory) {
throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
}
$newName = $object->getInfo()->getPath() . DIRECTORY_SEPARATOR . $newName;
\Nette\Utils\FileSystem::rename($object->getInfo()->getPathname(), $newName, $overwrite);
if ($object instanceof File) {
return File::open($newName);
} else {
return Directory::open($newName);
}
}
}
|
<?php
/**
* This file is part of the Kappa\FileSystem package.
*
* (c) Ondřej Záruba <zarubaondra@gmail.com>
*
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Kappa\FileSystem;
/**
* Class FileSystem
* @package Kappa\FileSystem
*/
class FileSystem
{
/**
* @param File|Directory $object
* @throws InvalidArgumentException
*/
public static function remove($object)
{
if (!$object instanceof File && !$object instanceof Directory) {
throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
}
\Nette\Utils\FileSystem::delete($object->getInfo()->getPathname());
}
/**
* @param File|Directory $object
* @param string $newName
* @param bool $overwrite
* @return Directory|File
* @throws InvalidArgumentException
*/
public static function rename($object, $newName, $overwrite = false)
{
if (!$object instanceof File && !$object instanceof Directory) {
throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
}
$newName = $object->getInfo()->getPath() . DIRECTORY_SEPARATOR . $newName;
\Nette\Utils\FileSystem::rename($object->getInfo()->getPathname(), $newName, $overwrite);
if ($object instanceof File) {
return File::open($newName);
} else {
return Directory::open($newName);
}
}
}
|
Fix object mapper after update
|
/*
* Copyright 2016 Studentmediene i Trondheim AS
*
* 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 no.dusken.momus.mapper;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
/**
* An ObjectMapper that registers a HibernateModule, so a JSON serialization
* doesn't fail with Hibernate lazy-loading.
*/
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
// converts lastName to last_name and the other way
setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm a z"));
registerModule(new Hibernate5Module());
}
}
|
/*
* Copyright 2016 Studentmediene i Trondheim AS
*
* 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 no.dusken.momus.mapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
/**
* An ObjectMapper that registers a HibernateModule, so a JSON serialization
* doesn't fail with Hibernate lazy-loading.
*/
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
// converts lastName to last_name and the other way
setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
registerModule(new Hibernate4Module());
}
}
|
Make setSQLManager forced to load queries to avoid NPE and misunderstanding
|
package org.tt.core.dm;
import org.tt.core.fetch.AbstractDataFetcher;
import org.tt.core.sql.AbstractQueries;
import org.tt.core.sql.AbstractSQLManager;
public class TTFactory {
private static AbstractSQLManager sqlm;
private static AbstractDataFetcher df;
private static TTFactory ttf;
private TTFactory() {
}
public static TTFactory getInstance() {
if (ttf == null) {
ttf = new TTFactory();
}
return ttf;
}
public void setSQLManager(AbstractSQLManager sqlm, AbstractQueries qrs) {
this.sqlm = sqlm;
this.sqlm.setQueries(qrs);
}
public void setDataFetcher(AbstractDataFetcher df) {
this.df = df;
}
public TTUpdateManager produceUpdateManager() {
return new TTUpdateManager(sqlm, df);
}
public TTDeliveryManager produceDeliveryManager() {
return new TTDeliveryManager(sqlm);
}
}
|
package org.tt.core.dm;
import org.tt.core.fetch.AbstractDataFetcher;
import org.tt.core.sql.AbstractQueries;
import org.tt.core.sql.AbstractSQLManager;
public class TTFactory {
private static AbstractSQLManager sqlm;
private static AbstractQueries qrs;
private static AbstractDataFetcher df;
private static TTFactory ttf;
private TTFactory() {
}
public static TTFactory getInstance() {
if (ttf == null) {
ttf = new TTFactory();
}
return ttf;
}
public void setSQLManager(AbstractSQLManager sqlm) {
this.sqlm = sqlm;
}
public void setSQLQueries(AbstractQueries qrs) {
this.qrs = qrs;
}
public void setDataFetcher(AbstractDataFetcher df) {
this.df = df;
}
public TTUpdateManager produceUpdateManager() {
return new TTUpdateManager(sqlm, df);
}
public TTDeliveryManager produceDeliveryManager() {
return new TTDeliveryManager(sqlm);
}
}
|
Revert "add bootstrap and fa"
This reverts commit be67b1f22a984c8cee25fda20a50e19d3852a045.
|
import angular from 'angular';
import uiRouter from '@uirouter/angularjs';
import AngularMaterials from 'angular-material';
import Pages from './pages/pages.module';
import Components from './components/components.module';
import Services from './services/services.module';
import Directives from './directives/directives.module';
import AppComponent from './app.component';
import 'normalize.css';
angular.module('app', [
uiRouter,
AngularMaterials,
Pages,
Components,
Services,
Directives
])
.config(($locationProvider) => {
"ngInject";
// @see: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions
// #how-to-configure-your-server-to-work-with-html5mode
$locationProvider.html5Mode(true).hashPrefix('!');
})
.component('app', AppComponent);
|
import angular from 'angular';
import uiRouter from '@uirouter/angularjs';
import AngularMaterials from 'angular-material';
// import 'bootstrap/dist/css/bootstrap.css';
import 'font-awesome/css/font-awesome.css';
import uiBootstrap from 'angular-ui-bootstrap';
import Pages from './pages/pages.module';
import Components from './components/components.module';
import Services from './services/services.module';
import Directives from './directives/directives.module';
import AppComponent from './app.component';
import 'normalize.css';
angular.module('app', [
uiRouter,
AngularMaterials,
Pages,
Components,
Services,
Directives
])
.config(($locationProvider) => {
"ngInject";
// @see: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions
// #how-to-configure-your-server-to-work-with-html5mode
$locationProvider.html5Mode(true).hashPrefix('!');
})
.component('app', AppComponent);
|
Add total score to stats
|
class Stats extends Phaser.State {
create() {
this.totalScore = this.game.state.states['Main'].totalScore
this.game.stage.backgroundColor = '#DFF4FF';
let statsHeader = "STATS"
let continuePhrase = "Tap to Continue"
this.statsHeaderText = this.game.add.text(650, 50, statsHeader, { font: "250px Revalia", textalign: "center"});
this.continueText = this.game.add.text(820, 300, continuePhrase, { font: "50px Arial", textalign: "center"});
// this.playerName = prompt("Please enter your name", "Player");
this.playerScore = this.game.add.text(1000, 800, ("Total Score: " + this.totalScore), { font: "60px Arial", fill: "#fffff"});
}
update() {
if(this.game.input.activePointer.justPressed()) {
this.game.state.start('End');
}
}
}
export default Stats;
|
class Stats extends Phaser.State {
create() {
this.totalScore = this.game.state.states['Main'].totalScore
this.game.stage.backgroundColor = '#DFF4FF';
let statsHeader = "STATS"
let continuePhrase = "Tap to Continue"
this.statsHeaderText = this.game.add.text(650, 50, statsHeader, { font: "250px Revalia", textalign: "center"});
this.continueText = this.game.add.text(820, 300, continuePhrase, { font: "50px Arial", textalign: "center"});
this.playerName = prompt("Please enter your name", "Player");
this.playerScore = this.game.add.text(20, 20, (this.playerName + "'s Score: " + this.totalScore), { font: "60px Arial", fill: "#fffff"});
}
update() {
if(this.game.input.activePointer.justPressed()) {
this.game.state.start('End');
}
}
}
export default Stats;
|
Remove call to `getStatus` also
|
var _ = require('underscore'),
DBPull = require('../models/db_pull'),
DBStatus = require('../models/db_status'),
config = require('../config'),
Signature = require('../models/signature');
module.exports = {
updatePull: function(updatedPull) {
var dbPull = new DBPull(updatedPull.data);
dbPull.save();
updatePullSignatures(updatedPull);
},
updateCommitStatus: function(updatedStatus) {
var dbStatus = new DBStatus(updatedStatus.data);
dbStatus.save();
}
// After restarting Pulldasher and updating all the open pulls, this
// updates closed pulls that are still set as 'open' in the DB, but have
// since been closed.
// @TODO closeStalePulls:
};
function updatePullSignatures(pull) {
// TODO build query here
// pull.signatures is an array of signatures for the pull and already has active set to true/false
// all signatures for this pull that are in the database but are not in this pull.signatures array should
// be set to active=false
}
|
var _ = require('underscore'),
DBPull = require('../models/db_pull'),
DBStatus = require('../models/db_status'),
config = require('../config'),
Signature = require('../models/signature');
module.exports = {
updatePull: function(updatedPull) {
var dbPull = new DBPull(updatedPull.data);
dbPull.save();
updatePullSignatures(updatedPull);
},
updateCommitStatus: function(updatedStatus) {
var dbStatus = new DBStatus(updatedStatus.data);
dbStatus.save();
}
// After restarting Pulldasher and updating all the open pulls, this
// updates closed pulls that are still set as 'open' in the DB, but have
// since been closed.
// @TODO closeStalePulls:
};
function updatePullSignatures(pull) {
// TODO build query here
// pull.signatures is an array of signatures for the pull and already has active set to true/false
// all signatures for this pull that are in the database but are not in this pull.signatures array should
// be set to active=false
console.log(pull.getStatus());
}
|
Add comments to make two-tier command clearer
|
module.exports = {
commands: {
random: {
help: 'Selects a random choice or number',
command: function (bot, msg) {
if (msg.args.length > 2) { // e.g. !random foo bar baz
// Select a random choice from a list:
msg.args.shift()
return msg.args[Math.floor(Math.random() * msg.args.length)]
} else if (msg.args.length === 2) { // e.g. !random 6
// Select a random integer from a range:
var res = Math.floor(Math.random() * Math.floor(msg.args[1]))
if (!isNaN(res)) {
return res.toString()
}
}
return 'Usage: (<number>|<choice 1> … <choice n>)'
}
},
coin: {
help: 'Flips a coin',
command: function () {
var faces = ['Heads!', 'Tails!']
return faces[Math.floor(Math.random() * faces.length)]
}
}
}
}
|
module.exports = {
commands: {
random: {
help: 'Selects a random choice or number',
command: function (bot, msg) {
if (msg.args.length > 2) {
msg.args.shift()
return msg.args[Math.floor(Math.random() * msg.args.length)]
} else if (msg.args.length === 2) {
var res = Math.floor(Math.random() * Math.floor(msg.args[1]))
if (!isNaN(res)) {
return res.toString()
}
}
return 'Usage: (<number>|<choice 1> … <choice n>)'
}
},
coin: {
help: 'Flips a coin',
command: function () {
var faces = ['Heads!', 'Tails!']
return faces[Math.floor(Math.random() * faces.length)]
}
}
}
}
|
Stop calling apc_store() with an array
Summary: Older versions of APC (AND HPHP) don't like apc_store() being called with an array, so it's easier to just foreach it each time.
Test Plan: make sure nothing breaks
Reviewers: epriestley
Reviewed By: epriestley
CC: aran, Korvin
Differential Revision: https://secure.phabricator.com/D5581
|
<?php
/**
* Interface to the APC key-value cache. This is a very high-performance cache
* which is local to the current machine.
*
* @group cache
*/
final class PhutilKeyValueCacheAPC extends PhutilKeyValueCache {
/* -( Key-Value Cache Implementation )------------------------------------- */
public function isAvailable() {
return function_exists('apc_fetch') &&
ini_get('apc.enabled') &&
(ini_get('apc.enable_cli') || php_sapi_name() != 'cli');
}
public function getKeys(array $keys, $ttl = null) {
$results = array();
$fetched = false;
foreach ($keys as $key) {
$result = apc_fetch($key, $fetched);
if ($fetched) {
$results[$key] = $result;
}
}
return $results;
}
public function setKeys(array $keys, $ttl = null) {
// NOTE: Although modern APC supports passing an array to `apc_store()`,
// it is not supported by older version fo APC or by HPHP.
foreach ($keys as $key => $value) {
apc_store($key, $value, $ttl);
}
return $this;
}
public function deleteKeys(array $keys) {
foreach ($keys as $key) {
apc_delete($key);
}
return $this;
}
public function destroyCache() {
apc_clear_cache('user');
return $this;
}
}
|
<?php
/**
* Interface to the APC key-value cache. This is a very high-performance cache
* which is local to the current machine.
*
* @group cache
*/
final class PhutilKeyValueCacheAPC extends PhutilKeyValueCache {
/* -( Key-Value Cache Implementation )------------------------------------- */
public function isAvailable() {
return function_exists('apc_fetch') &&
ini_get('apc.enabled') &&
(ini_get('apc.enable_cli') || php_sapi_name() != 'cli');
}
public function getKeys(array $keys, $ttl = null) {
$results = array();
$fetched = false;
foreach ($keys as $key) {
$result = apc_fetch($key, $fetched);
if ($fetched) {
$results[$key] = $result;
}
}
return $results;
}
public function setKeys(array $keys, $ttl = null) {
if (phutil_is_hiphop_runtime()) {
foreach ($keys as $key => $value) {
apc_store($key, $value, $ttl);
}
} else {
apc_store($keys, null, $ttl);
}
return $this;
}
public function deleteKeys(array $keys) {
foreach ($keys as $key) {
apc_delete($key);
}
return $this;
}
public function destroyCache() {
apc_clear_cache('user');
return $this;
}
}
|
Change target to index.js for web build
|
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var browserify = require('browserify');
var through2 = require('through2');
var babelify = require('babelify');
var webpack = require('webpack-stream');
gulp.task('buildWeb:regular', function() {
return gulp.src('./src/index.js')
.pipe(webpack(require('./webpack.config.js').regular, require('webpack'))) // pass webpack for webpack2
.pipe(gulp.dest('./dist/web'));
});
gulp.task('buildWeb:minified', function() {
return gulp.src('./src/index.js')
.pipe(webpack(require('./webpack.config.js').minified, require('webpack'))) // pass webpack for webpack2
.pipe(gulp.dest('./dist/web'));
});
gulp.task('buildNode',function(){
return gulp.src('./src/**/*.js')
.pipe(babel({
presets: ['es2015'],
plugins: ['babel-plugin-add-module-exports']
}))
.pipe(gulp.dest('./dist/node/'));
});
gulp.task('build', ['buildNode', 'buildWeb']);
gulp.task('buildWeb', ['buildWeb:regular', 'buildWeb:minified']);
|
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var browserify = require('browserify');
var through2 = require('through2');
var babelify = require('babelify');
var webpack = require('webpack-stream');
gulp.task('buildWeb:regular', function() {
return gulp.src('./src/main.js')
.pipe(webpack(require('./webpack.config.js').regular, require('webpack'))) // pass webpack for webpack2
.pipe(gulp.dest('./dist/web'));
});
gulp.task('buildWeb:minified', function() {
return gulp.src('./src/main.js')
.pipe(webpack(require('./webpack.config.js').minified, require('webpack'))) // pass webpack for webpack2
.pipe(gulp.dest('./dist/web'));
});
gulp.task('buildNode',function(){
return gulp.src('./src/**/*.js')
.pipe(babel({
presets: ['es2015'],
plugins: ['babel-plugin-add-module-exports']
}))
.pipe(gulp.dest('./dist/node/'));
});
gulp.task('build', ['buildNode', 'buildWeb']);
gulp.task('buildWeb', ['buildWeb:regular', 'buildWeb:minified']);
|
Support MFA and roles when doing auth
|
package awsSdkGo
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/s3"
)
type Sdk struct {
Ec2 *ec2.EC2
S3 *s3.S3
ASG *autoscaling.AutoScaling
}
func NewSdk(region string) (*Sdk, error) {
sdk := &Sdk{}
session, err := session.NewSessionWithOptions(session.Options{
Config: aws.Config{Region: aws.String(region)},
// Support MFA when authing using assumed roles.
SharedConfigState: session.SharedConfigEnable,
AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
})
if err != nil {
return nil, err
}
sdk.Ec2 = ec2.New(session)
sdk.ASG = autoscaling.New(session)
sdk.S3 = s3.New(session)
return sdk, nil
}
|
package awsSdkGo
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/s3"
)
type Sdk struct {
Ec2 *ec2.EC2
S3 *s3.S3
ASG *autoscaling.AutoScaling
}
func NewSdk(region string) (*Sdk, error) {
sdk := &Sdk{}
session, err := session.NewSession(&aws.Config{Region: aws.String(region)})
if err != nil {
return nil, err
}
sdk.Ec2 = ec2.New(session)
sdk.ASG = autoscaling.New(session)
sdk.S3 = s3.New(session)
return sdk, nil
}
|
Add onChange handle to call back when a field has been changed.
|
angular.module('materialscommons').component('mcEditableHeader', {
template: `
<div layout="column" layout-align="start stretch">
<span ng-if="!$ctrl.editField"
ng-click="$ctrl.editField = true"
ng-class="$ctrl.headerClasses"
style="cursor: pointer">
{{$ctrl.header}}
</span>
<input ng-if="$ctrl.editField"
type="text" class="mc-input-as-line"
on-enter="$ctrl.editField = false"
ng-model="$ctrl.header"
ng-model-options="{debounce: 250}"
ng-change="$ctrl.onChange && $ctrl.onChange()"
ng-class="$ctrl.inputClasses"
ng-mouseleave="$ctrl.editField = false">
</div>
`,
bindings: {
header: '=',
headerClasses: '@',
inputClasses: '@',
onChange: '&'
}
});
|
angular.module('materialscommons').component('mcEditableHeader', {
template: `
<div layout="column" layout-align="start stretch">
<span ng-if="!$ctrl.editField"
ng-click="$ctrl.editField = true"
ng-class="$ctrl.headerClasses"
style="cursor: pointer">
{{$ctrl.header}}
</span>
<input ng-if="$ctrl.editField"
type="text" class="mc-input-as-line"
on-enter="$ctrl.editField = false"
ng-model="$ctrl.header"
ng-class="$ctrl.inputClasses"
ng-mouseleave="$ctrl.editField = false">
</div>
`,
bindings: {
header: '=',
headerClasses: '@',
inputClasses: '@'
}
});
|
Fix the issue with losing pageAction after tab reload
|
var connections = {};
// Listen to messages sent from the DevTools page
chrome.runtime.onConnect.addListener(function (port) {
function extensionListener(message) {
if (message.name == 'init') {
connections[message.tabId] = port;
connections[message.tabId].postMessage({
payload: store.liftedStore.getState(),
source: 'redux-page'
});
}
}
port.onMessage.addListener(extensionListener);
port.onDisconnect.addListener(function (port) {
port.onMessage.removeListener(extensionListener);
Object.keys(connections).forEach(function (id) {
if (connections[id] == port) {
delete connections[id];
}
})
})
});
// Receive message from content script and relay to the devTools page
chrome.runtime.onMessage.addListener(function (request, sender) {
store.liftedStore.setState(request.payload);
if (sender.tab) {
var tabId = sender.tab.id;
store.tabId = tabId;
chrome.pageAction.show(tabId);
if (tabId in connections) {
connections[ tabId ].postMessage(request);
}
}
return true;
});
export function toContentScript(action) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(store.tabId, {action: action}, function(response) {});
});
}
|
var connections = {};
// Listen to messages sent from the DevTools page
chrome.runtime.onConnect.addListener(function (port) {
function extensionListener(message) {
if (message.name == 'init') {
connections[message.tabId] = port;
connections[message.tabId].postMessage({
payload: store.liftedStore.getState(),
source: 'redux-page'
});
}
}
port.onMessage.addListener(extensionListener);
port.onDisconnect.addListener(function (port) {
port.onMessage.removeListener(extensionListener);
Object.keys(connections).forEach(function (id) {
if (connections[id] == port) {
delete connections[id];
}
})
})
});
// Receive message from content script and relay to the devTools page
chrome.runtime.onMessage.addListener(function (request, sender) {
store.liftedStore.setState(request.payload);
if (sender.tab) {
var tabId = sender.tab.id;
if (store.tabId !== tabId) {
store.tabId = tabId;
chrome.pageAction.show(tabId);
}
if (tabId in connections) {
connections[ tabId ].postMessage(request);
}
}
return true;
});
export function toContentScript(action) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(store.tabId, {action: action}, function(response) {});
});
}
|
Add skill rating and make win rate more precise
Fixes #1
|
import fetch from 'node-fetch';
import { API_URL, HTTP_HEADERS } from '../constants';
const headers = HTTP_HEADERS;
const formatStats = (data, battletag, competitive) => {
const stats = data['overall_stats'];
const gameMode = competitive ? 'Competitive' : 'Quick Play';
let level = stats['level'];
if (typeof stats['prestige'] === 'number') {
level += (stats['prestige'] * 100);
}
const winRate = ((stats['wins'] / stats['games']) * 100).toFixed(2);
return `*${battletag}*'s Overall Stats (${gameMode}):
- Level: ${level || 0}
- Games: ${stats['games'] || 0}
- Wins: ${stats['wins'] || 0}
- Losses: ${stats['losses'] || 0}
- Win Rate: ${winRate || 0}%
- Rating: ${stats['comprank'] || 0}`;
}
export const fetchOverallStats = (battletag, competitive) => {
const gameMode = competitive ? 'competitive' : 'general';
const url = `${API_URL}/${battletag}/stats/${gameMode}`;
return fetch(url, { headers })
.then(response => response.json())
.then(json => formatStats(json, battletag, competitive))
.catch(error => {
return `Sorry, I cannot find the user ${battletag}`;
});
}
|
import fetch from 'node-fetch';
import { API_URL, HTTP_HEADERS } from '../constants';
const headers = HTTP_HEADERS;
const formatStats = (data, battletag, competitive) => {
const stats = data['overall_stats'];
const gameMode = competitive ? 'Competitive' : 'Quick Play';
return `*${battletag}*'s Overall Stats (${gameMode}):
- Level: ${stats['level'] || 0}
- Games: ${stats['games'] || 0}
- Wins: ${stats['wins'] || 0}
- Losses: ${stats['losses'] || 0}
- Win Rate: ${stats['win_rate'] || 0}%`;
}
export const fetchOverallStats = (battletag, competitive) => {
const gameMode = competitive ? 'competitive' : 'general';
const url = `${API_URL}/${battletag}/stats/${gameMode}`;
return fetch(url, { headers })
.then(response => response.json())
.then(json => formatStats(json, battletag, competitive))
.catch(error => {
return `Sorry, I cannot find the user ${battletag}`;
});
}
|
Move running flag to before htrtime start
|
'use strict';
export class Timer {
constructor() {
this.reset();
}
/**
* Start the timer
*/
start() {
if(this._ran) throw new Error('timer already ran. use reset() first');
if(this._running) throw new Error('timer currently running');
this._running = true;
this._hrtime = process.hrtime();
}
/**
* Stop the timer
*/
stop() {
if(!this._running) throw new Error('timer not running');
this._hrtime = process.hrtime(this._hrtime);
this._runtime = (this._hrtime[0] * 1000) + (this._hrtime[1] / 1000000);
this._running = false;
this._ran = true;
}
/**
* Get the timer's time
*/
time() {
if(!this._ran) throw new Error('timer not ran yet');
if(this._running) throw new Error('timmer currently running');
return this._runtime;
}
/**
* Return true if the timer has ran and finished
*/
isFinished() {
return this._ran;
}
/**
* Rest timer variables
*/
reset() {
this._hrtime = null;
this._runtime = 0;
this._running = false;
this._ran = false;
}
}
|
'use strict';
export class Timer {
constructor() {
this.reset();
}
/**
* Start the timer
*/
start() {
if(this._ran) throw new Error('timer already ran. use reset() first');
if(this._running) throw new Error('timer currently running');
this._hrtime = process.hrtime();
this._running = true;
}
/**
* Stop the timer
*/
stop() {
if(!this._running) throw new Error('timer not running');
this._hrtime = process.hrtime(this._hrtime);
this._runtime = (this._hrtime[0] * 1000) + (this._hrtime[1] / 1000000);
this._running = false;
this._ran = true;
}
/**
* Get the timer's time
*/
time() {
if(!this._ran) throw new Error('timer not ran yet');
if(this._running) throw new Error('timmer currently running');
return this._runtime;
}
/**
* Return true if the timer has ran and finished
*/
isFinished() {
return this._ran;
}
/**
* Rest timer variables
*/
reset() {
this._hrtime = null;
this._runtime = 0;
this._running = false;
this._ran = false;
}
}
|
Add incremental Tasker delay when retrying tasks
Add missing type cast.
|
<?php
namespace G4\Tasker\Tasker2;
class RetryAfterResolver
{
const RETRY_AFTER_60 = 60;
const RETRY_AFTER_300 = 300;
const RETRY_AFTER_1000 = 1000;
/**
* @var int
*/
private $startedCount;
/**
* RetryAfterResolver constructor.
* @param int $startedCount
*/
public function __construct($startedCount)
{
$this->startedCount = (int) $startedCount;
}
/**
* Return after how much seconds task should be retried based on number of starting
*
* @return int
*/
public function resolve()
{
if ($this->startedCount === 2) {
return self::RETRY_AFTER_300;
}
if ($this->startedCount === 3) {
return self::RETRY_AFTER_1000;
}
return self::RETRY_AFTER_60;
}
}
|
<?php
namespace G4\Tasker\Tasker2;
class RetryAfterResolver
{
const RETRY_AFTER_60 = 60;
const RETRY_AFTER_300 = 300;
const RETRY_AFTER_1000 = 1000;
/**
* @var int
*/
private $startedCount;
/**
* RetryAfterResolver constructor.
* @param $startedCount
*/
public function __construct($startedCount)
{
$this->startedCount = $startedCount;
}
/**
* Return after how much seconds task should be retried based on number of starting
*
* @return int
*/
public function resolve()
{
if ($this->startedCount === 2) {
return self::RETRY_AFTER_300;
}
if ($this->startedCount === 3) {
return self::RETRY_AFTER_1000;
}
return self::RETRY_AFTER_60;
}
}
|
Reduce the number of recent users we display.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
|
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import auth
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.views.decorators.http import require_POST
def content(request):
current = []
if request.user.is_authenticated():
for field in User._meta.fields:
if field.name == 'password':
continue
current.append(
(field.attname, getattr(request.user, field.attname))
)
return render_to_response('debug_toolbar_user_panel/content.html', {
'next': request.GET.get('next'),
'users': User.objects.order_by('-last_login')[:10],
'current': current,
}, context_instance=RequestContext(request))
@require_POST
def login(request, pk):
user = get_object_or_404(User, pk=pk)
# Hacky
user.backend = settings.AUTHENTICATION_BACKENDS[0]
auth.login(request, user)
return HttpResponseRedirect(request.POST.get('next', '/'))
|
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import auth
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.views.decorators.http import require_POST
def content(request):
current = []
if request.user.is_authenticated():
for field in User._meta.fields:
if field.name == 'password':
continue
current.append(
(field.attname, getattr(request.user, field.attname))
)
return render_to_response('debug_toolbar_user_panel/content.html', {
'next': request.GET.get('next'),
'users': User.objects.order_by('-last_login')[:20],
'current': current,
}, context_instance=RequestContext(request))
@require_POST
def login(request, pk):
user = get_object_or_404(User, pk=pk)
# Hacky
user.backend = settings.AUTHENTICATION_BACKENDS[0]
auth.login(request, user)
return HttpResponseRedirect(request.POST.get('next', '/'))
|
Make the Redis connection more robust
When Redis resets the connection, the ECONNRESET error cause the nodejs server
to exit. Capture and log it so that the server lives on. It will reconnect, and
perhaps we'll learn that different errors require different handling after
enough logging.
|
'use strict';
var redis = require('redis'),
coRedis = require('co-redis'),
koa = require('koa');
var app = koa(),
client = redis.createClient(
process.env.REDIS_PORT,
process.env.REDIS_HOST
),
dbCo = coRedis(client);
if (process.env.REDIS_SECRET) {
client.auth(process.env.REDIS_SECRET);
}
client.on('error', function (err) {
console.log('Redis client error: ' + err);
});
app.use(function* () {
var indexkey;
if (this.request.query.index_key) {
indexkey = process.env.APP_NAME +':'+ this.request.query.index_key;
} else {
indexkey = yield dbCo.get(process.env.APP_NAME +':current');
}
var index = yield dbCo.get(indexkey);
this.body = index || '';
});
app.listen(process.env.PORT || 3000);
|
'use strict';
var redis = require('redis'),
coRedis = require('co-redis'),
koa = require('koa');
var app = koa(),
client = redis.createClient(
process.env.REDIS_PORT,
process.env.REDIS_HOST
),
dbCo = coRedis(client);
if (process.env.REDIS_SECRET) {
client.auth(process.env.REDIS_SECRET);
}
app.use(function* () {
var indexkey;
if (this.request.query.index_key) {
indexkey = process.env.APP_NAME +':'+ this.request.query.index_key;
} else {
indexkey = yield dbCo.get(process.env.APP_NAME +':current');
}
var index = yield dbCo.get(indexkey);
this.body = index || '';
});
app.listen(process.env.PORT || 3000);
|
Test suite requires me to spell contenttypes correctly
|
#!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE='django.db.backends.postgresql_psycopg2',
DATABASE_NAME='bitfield_test',
INSTALLED_APPS=[
'django.contrib.contenttypes',
'bitfield',
'bitfield.tests',
],
ROOT_URLCONF='',
DEBUG=False,
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['bitfield']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE='django.db.backends.postgresql_psycopg2',
DATABASE_NAME='bitfield_test',
INSTALLED_APPS=[
'django.contrib.contettypes',
'bitfield',
'bitfield.tests',
],
ROOT_URLCONF='',
DEBUG=False,
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['bitfield']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Set flags to config file settings if not passed.
Will need to set defaults if the var doesn't exist in the config.
|
package configuration
import (
"flag"
"time"
)
// parseConfigFlags overwrites configuration with set flags
func parseConfigFlags(Conf *SplendidConfig) (*SplendidConfig, error) {
// Set to passed flags, otherwise go with config
flag.IntVar(&Conf.Concurrency, "c", Conf.Concurrency, "Number of collector processes")
flag.StringVar(&Conf.SmtpString, "s", Conf.SmtpString, "SMTP server:port")
flag.DurationVar(&Conf.Interval, "interval", Conf.Interval*time.Second, "Run interval")
flag.DurationVar(&Conf.Timeout, "timeout", Conf.Timeout*time.Second, "Collection timeout")
flag.BoolVar(&Conf.Insecure, "insecure", Conf.Insecure, "Allow untrusted SSH keys")
flag.BoolVar(&Conf.HttpEnabled, "web", Conf.HttpEnabled, "Run an HTTP status server")
flag.StringVar(&Conf.HttpListen, "listen", Conf.HttpListen, "Host and port to use for HTTP status server (default: localhost:5000).")
flag.StringVar(&Conf.ConfigFile, "f", Conf.ConfigFile, "Config File")
flag.Parse()
return Conf, nil
}
|
package configuration
import (
"flag"
"time"
)
// parseConfigFlags overwrites configuration with set flags
func parseConfigFlags(Conf *SplendidConfig) (*SplendidConfig, error) {
// TODO: This should only happen if the flag has been passed
flag.StringVar(&Conf.Workspace, "w", "./splendid-workspace", "Workspace")
flag.IntVar(&Conf.Concurrency, "c", 30, "Number of collector processes")
flag.StringVar(&Conf.SmtpString, "s", "localhost:25", "SMTP server:port")
flag.DurationVar(&Conf.Interval, "interval", 300*time.Second, "Run interval")
flag.DurationVar(&Conf.Timeout, "timeout", 60*time.Second, "Collection timeout")
flag.BoolVar(&Conf.Insecure, "insecure", false, "Allow untrusted SSH keys")
flag.BoolVar(&Conf.GitPush, "push", false, "Git push after commit")
flag.BoolVar(&Conf.HttpEnabled, "web", false, "Run an HTTP status server")
flag.StringVar(&Conf.HttpListen, "listen", "localhost:5000", "Host and port to use for HTTP status server (default: localhost:5000).")
flag.StringVar(&Conf.ConfigFile, "f", "sample.conf", "Config File")
flag.Parse()
return Conf, nil
}
|
Add test extension to config
|
module.exports = {
interpolate: /{{([\s\S]+?)}}/g,
modules: [
{
type: 'service',
output: 'app/services/',
fileTypes: '{js,test.js}'
},
{
type: 'filter',
output: 'app/filters/',
fileTypes: '{js,test.js}'
},
{
type: 'factory',
output: 'app/factories/',
fileTypes: '{js,test.js}'
},
{
type: 'constant',
output: 'app/constants/',
fileTypes: '{js,test.js}'
},
{
type: 'component',
output: 'app/components/',
fileTypes: '{scss,js,html,test.js}'
},
{
type: 'controller',
output: 'app/controllers/',
fileTypes: '{scss,js,html,test.js}'
}
]
};
|
module.exports = {
interpolate: /{{([\s\S]+?)}}/g,
modules: [
{
type: 'service',
output: 'app/services/',
fileTypes: '{js,test.js}'
},
{
type: 'filter',
output: 'app/filters/',
fileTypes: '{js,test.js}'
},
{
type: 'factory',
output: 'app/factories/',
fileTypes: '{js,test.js}'
},
{
type: 'constant',
output: 'app/constants/',
fileTypes: '{js,test.js}'
},
{
type: 'component',
output: 'app/components/',
fileTypes: '{scss,js,html}' // ,test.js
},
{
type: 'controller',
output: 'app/controllers/',
fileTypes: '{scss,js,html}' // ,test.js
}
]
};
|
Make Go and Apply button a primary button.
|
<?php
/**
* @file
* template.php
*/
/**
* Implements hook_preprocess_HOOK().
*/
function bootstrap_serchilo_preprocess_block(&$vars) {
switch ($vars['block_html_id']) {
case 'block-serchilo-namespaces':
// Put a well around namespaces block.
$vars['classes_array'][] = 'well';
$vars['classes_array'][] = 'well-sm';
break;
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function bootstrap_serchilo_preprocess_button(&$vars) {
switch ($vars['element']['#id']) {
// Make Go button a primary button.
// Make Apply button a primary button.
case 'edit-submit':
case 'edit-submit-shortcuts':
$vars['element']['#attributes']['class'][] = 'btn-primary';
break;
case 'edit-reset':
// Make Reset button a warning button.
$vars['element']['#attributes']['class'][] = 'btn-warning';
break;
}
}
|
<?php
/**
* @file
* template.php
*/
/**
* Implements hook_preprocess_HOOK().
*/
function bootstrap_serchilo_preprocess_block(&$vars) {
switch ($vars['block_html_id']) {
case 'block-serchilo-namespaces':
// Put a well around namespaces block.
$vars['classes_array'][] = 'well';
$vars['classes_array'][] = 'well-sm';
break;
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function bootstrap_serchilo_preprocess_button(&$vars) {
switch ($vars['element']['#id']) {
case 'edit-submit-shortcuts':
// Make Go button a primary button.
$vars['element']['#attributes']['class'][] = 'btn-primary';
break;
case 'edit-reset':
// Make Reset button a warning button.
$vars['element']['#attributes']['class'][] = 'btn-warning';
break;
}
}
|
Remove django < 1.4 code
|
# -*- coding: utf-8 -*-
# urls.py used as base for developing wirecloud.
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import wirecloud.platform.urls
admin.autodiscover()
urlpatterns = patterns('',
# Showcase
(r'^showcase/', include('wirecloud.platform.widget.showcase_urls')),
# Catalogue
(r'^catalogue', include('wirecloud.catalogue.urls')),
# Proxy
(r'^proxy', include('wirecloud.proxy.urls')),
# Login/logout
url(r'^login/?$', 'django.contrib.auth.views.login', name="login"),
url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"),
url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'),
# Admin interface
(r'^admin/', include(admin.site.urls)),
)
urlpatterns += wirecloud.platform.urls.urlpatterns
urlpatterns += staticfiles_urlpatterns()
handler404 = "django.views.defaults.page_not_found"
handler500 = "wirecloud.commons.views.server_error"
|
# -*- coding: utf-8 -*-
# urls.py used as base for developing wirecloud.
try:
from django.conf.urls import patterns, include, url
except ImportError: # pragma: no cover
# for Django version less than 1.4
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import wirecloud.platform.urls
admin.autodiscover()
urlpatterns = patterns('',
# Showcase
(r'^showcase/', include('wirecloud.platform.widget.showcase_urls')),
# Catalogue
(r'^catalogue', include('wirecloud.catalogue.urls')),
# Proxy
(r'^proxy', include('wirecloud.proxy.urls')),
# Login/logout
url(r'^login/?$', 'django.contrib.auth.views.login', name="login"),
url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"),
url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'),
# Admin interface
(r'^admin/', include(admin.site.urls)),
)
urlpatterns += wirecloud.platform.urls.urlpatterns
urlpatterns += staticfiles_urlpatterns()
handler404 = "django.views.defaults.page_not_found"
handler500 = "wirecloud.commons.views.server_error"
|
Convert tabs to spaces, and set up vim modeline to expand tabs going forward.
|
#! /usr/bin/env python
# vim: set sw=4 ai et sm:
"""dwalk: walk a directory tree, printing entries hierarchically
+ top
| > file
| > file
| + dir
| | > file
| | > file
| | + dir
| | | > file
| | + dir
| | | > file
| | | > file
| + dir
| | + dir
| | | > file"""
import os
import sys
def dwalk(path, header=''):
print header + '+ ' + path
files = []
dirs = []
for e in os.listdir(path):
epath = os.path.join(path, e)
if os.path.isdir(epath):
# print header + '{} is a dir'.format(e)
dirs.append(e)
else:
# print header + '{} is a file'.format(e)
files.append(e)
# print '{} dirs: {}'.format(header, dirs)
# print '{} files: {}'.format(header, files)
for f in sorted(files):
# print header + '| > ' + os.path.join(path, f)
print header + '| > ' + f
for d in sorted(dirs):
dwalk(os.path.join(path,d), header+'| ')
|
#! /usr/bin/env python
"""dwalk: walk a directory tree, printing entries hierarchically
+ top
| > file
| > file
| + dir
| | > file
| | > file
| | + dir
| | | > file
| | + dir
| | | > file
| | | > file
| + dir
| | + dir
| | | > file"""
import os
import sys
def dwalk(path, header=''):
print header + '+ ' + path
files = []
dirs = []
for e in os.listdir(path):
epath = os.path.join(path, e)
if os.path.isdir(epath):
# print header + '{} is a dir'.format(e)
dirs.append(e)
else:
# print header + '{} is a file'.format(e)
files.append(e)
# print '{} dirs: {}'.format(header, dirs)
# print '{} files: {}'.format(header, files)
for f in sorted(files):
# print header + '| > ' + os.path.join(path, f)
print header + '| > ' + f
for d in sorted(dirs):
dwalk(os.path.join(path,d), header+'| ')
|
Fix so that reactors properly return the EU/t on output.
|
package openccsensors.common.sensors.industrialcraft;
import ic2.api.IReactor;
import ic2.api.IC2Reactor;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.src.TileEntity;
import net.minecraft.src.World;
import openccsensors.common.api.ISensorTarget;
import openccsensors.common.sensors.TileSensorTarget;
public class ReactorTarget extends TileSensorTarget implements ISensorTarget
{
ReactorTarget(TileEntity targetEntity) {
super(targetEntity);
}
public Map getDetailInformation(World world)
{
HashMap retMap = new HashMap();
IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord);
retMap.put("Heat", reactor.getHeat());
retMap.put("MaxHeat", reactor.getMaxHeat());
retMap.put("Output", reactor.getOutput() * new IC2Reactor().getEUOutput());
retMap.put("Active", reactor.produceEnergy());
return retMap;
}
}
|
package openccsensors.common.sensors.industrialcraft;
import ic2.api.IReactor;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.src.TileEntity;
import net.minecraft.src.World;
import openccsensors.common.api.ISensorTarget;
import openccsensors.common.sensors.TileSensorTarget;
public class ReactorTarget extends TileSensorTarget implements ISensorTarget
{
ReactorTarget(TileEntity targetEntity) {
super(targetEntity);
}
public Map getDetailInformation(World world)
{
HashMap retMap = new HashMap();
IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord);
retMap.put("Heat", reactor.getHeat());
retMap.put("MaxHeat", reactor.getMaxHeat());
retMap.put("Output", reactor.getOutput());
retMap.put("Active", reactor.produceEnergy());
return retMap;
}
}
|
Allow to filter issue by summary (WAL-197)
|
import template from './issues-helpdesk.html';
export default function issuesHelpdesk() {
return {
restrict: 'E',
template: template,
controller: IssuesHelpdeskController,
controllerAs: '$ctrl',
scope: {},
bindToController: true
};
}
class IssuesHelpdeskController {
constructor() {
this.listFilter = {};
}
onSearch(issue) {
if (!issue) {
this.listFilter = {};
return;
}
let filter = {};
if (issue.caller) {
filter.caller_user = issue.caller.url;
}
if (issue.customer) {
filter.customer = issue.customer.url;
}
if (issue.project) {
filter.project = issue.project.url;
}
if (issue.summary) {
filter.summary = issue.summary;
}
this.listFilter = filter;
}
}
|
import template from './issues-helpdesk.html';
export default function issuesHelpdesk() {
return {
restrict: 'E',
template: template,
controller: IssuesHelpdeskController,
controllerAs: '$ctrl',
scope: {},
bindToController: true
};
}
class IssuesHelpdeskController {
constructor() {
this.listFilter = {};
}
onSearch(issue) {
if (!issue) {
this.listFilter = {};
return;
}
let filter = {};
if (issue.caller) {
filter.caller_user = issue.caller.url;
}
if (issue.customer) {
filter.customer = issue.customer.url;
}
if (issue.project) {
filter.project = issue.project.url;
}
this.listFilter = filter;
}
}
|
Add additional default date check
|
<?php
function convert_mysql_date_to_php_date($date) {
if ($date == "0000-00-00" || $date == NULL || $date == "1969-12-31") {
$date = "N/A";
} else {
$date = date('d-M-y', strtotime($date));
}
return $date;
}
function convert_str_date_to_mysql_date($date) {
if ($date == "N/A" || $date == NULL || $date == "0") {
$date = NULL;
} else {
try {
$date = date('Y-m-d', strtotime($date));
} catch (Exception $e) {
$date = NULL;
}
}
return $date;
}
?>
|
<?php
function convert_mysql_date_to_php_date($date) {
if ($date == "0000-00-00" || $date == NULL) {
$date = "N/A";
} else {
$date = date('d-M-y', strtotime($date));
}
return $date;
}
function convert_str_date_to_mysql_date($date) {
if ($date == "N/A" || $date == "0") {
$date = NULL;
} else {
try {
$date = date('Y-m-d', strtotime($date));
} catch (Exception $e) {
$date = NULL;
}
}
return $date;
}
?>
|
Add the feed forward gain
|
package org.camsrobotics.frc2016;
/**
* Assorted Constants
*
* @author Wesley
*
*/
public class Constants {
/*
* Camera Constants
*/
public final static int cameraFrameHeight = 240;
public final static int cameraFrameWidth = 320;
public final static double cameraFOVAngle = 21.2505055;
/*
* Drive Constants
*/
public final static double kDriveRotationP = 0;
public final static double kDriveRotationI = 0;
public final static double kDriveRotationD = 0;
public final static double kDriveTranslationP = 0;
public final static double kDriveTranslationI = 0;
public final static double kDriveTranslationD = 0;
/*
* Shooter Constants
*/
public final static double kFlywheelF = 0;
public final static double kFlywheelP = 0;
public final static double kFlywheelI = 0;
public final static double kFlywheelD = 0;
public final static double kLiftF = 0;
public final static double kLiftP = 0;
public final static double kLiftI = 0;
public final static double kLiftD = 0;
}
|
package org.camsrobotics.frc2016;
/**
* Assorted Constants
*
* @author Wesley
*
*/
public class Constants {
/*
* Camera Constants
*/
public final static int cameraFrameHeight = 240;
public final static int cameraFrameWidth = 320;
public final static double cameraFOVAngle = 21.2505055;
/*
* Drive Constants
*/
public final static double kDriveRotationP = 0;
public final static double kDriveRotationI = 0;
public final static double kDriveRotationD = 0;
public final static double kDriveTranslationP = 0;
public final static double kDriveTranslationI = 0;
public final static double kDriveTranslationD = 0;
/*
* Shooter Constants
*/
public final static double kFlywheelP = 0;
public final static double kFlywheelI = 0;
public final static double kFlywheelD = 0;
public final static double kLiftP = 0;
public final static double kLiftI = 0;
public final static double kLiftD = 0;
}
|
Simplify the requesting of parameters.
|
from django.core.management.base import BaseCommand
from optparse import make_option
from rapidsms_httprouter.router import get_router
from rapidsms.models import Connection
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option("-p", "--phone", dest="phone"),
make_option("-t", "--text", dest="text"),
)
def handle(self, **options):
phone = options['phone'] or raw_input('Phone number you wish the message to appear to come from: ')
text = options['text'] or raw_input('Text of the message: ')
connection = Connection.objects.get(identity = phone)
router = get_router()
handled = router.handle_incoming(connection.backend.name, connection.identity, text)
self.stdout.write('Done!\n')
|
from django.core.management.base import BaseCommand
from optparse import make_option
from rapidsms_httprouter.router import get_router
from rapidsms.models import Connection
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option("-p", "--phone", dest="phone"),
make_option("-t", "--text", dest="text"),
)
def handle(self, **options):
if not options['phone']:
phone = raw_input('Phone number you wish the message to appear to come from: ')
else:
phone = options['phone']
if not options['text']:
text = raw_input('Text of the message: ')
else:
text = options['text']
connection = Connection.object.get(identity = phone)
router = get_router()
handled = router.handle_incoming(connection.backend.name, connection.identity, text)
self.stdout.write('Done!\n')
|
Add FIXME in product import in producer module
|
from datetime import datetime
from django.db import models
from django.db.models import Sum, signals
from django.utils.translation import ugettext_lazy as _
from plata.product.modules.options.models import Product # FIXME
class ProducerManager(models.Manager):
def active(self):
return self.filter(is_active=True)
class Producer(models.Model):
"""
Optional producer field for every product
"""
is_active = models.BooleanField(_('is active'), default=True)
name = models.CharField(_('name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
ordering = models.PositiveIntegerField(_('ordering'), default=0)
description = models.TextField(_('description'), blank=True)
class Meta:
app_label = 'product'
ordering = ['ordering', 'name']
verbose_name = _('producer')
verbose_name_plural = _('producers')
def __unicode__(self):
return self.name
Product.add_to_class('producer', models.ForeignKey(Producer, blank=True, null=True,
related_name='products', verbose_name=_('producer')))
|
from datetime import datetime
from django.db import models
from django.db.models import Sum, signals
from django.utils.translation import ugettext_lazy as _
from plata.product.modules.options.models import Product
class ProducerManager(models.Manager):
def active(self):
return self.filter(is_active=True)
class Producer(models.Model):
"""
Optional producer field for every product
"""
is_active = models.BooleanField(_('is active'), default=True)
name = models.CharField(_('name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
ordering = models.PositiveIntegerField(_('ordering'), default=0)
description = models.TextField(_('description'), blank=True)
class Meta:
app_label = 'product'
ordering = ['ordering', 'name']
verbose_name = _('producer')
verbose_name_plural = _('producers')
def __unicode__(self):
return self.name
Product.add_to_class('producer', models.ForeignKey(Producer, blank=True, null=True,
related_name='products', verbose_name=_('producer')))
|
Comment out the byte code reflection
|
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class ConstructorInjectionWithByteCodeTest extends TestCase {
private static final String SOURCE =
"<exampleByteCode age='30'>\n"+
" <name>John Doe</name>\n"+
"</exampleByteCode>";
@Root
public static class ExampleByteCode {
@Element
private String name;
@Attribute
private int age;
public ExampleByteCode(@Element String name, @Attribute int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public void testByteCode() throws Exception {
// Persister persister = new Persister();
// ExampleByteCode example = persister.read(ExampleByteCode.class, SOURCE);
// assertEquals(example.getName(), "John Doe");
// assertEquals(example.getAge(), 30);
}
}
|
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class ConstructorInjectionWithByteCodeTest extends TestCase {
private static final String SOURCE =
"<exampleByteCode age='30'>\n"+
" <name>John Doe</name>\n"+
"</exampleByteCode>";
@Root
public static class ExampleByteCode {
@Element
private String name;
@Attribute
private int age;
public ExampleByteCode(@Element String name, @Attribute int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public void testByteCode() throws Exception {
Persister persister = new Persister();
ExampleByteCode example = persister.read(ExampleByteCode.class, SOURCE);
assertEquals(example.getName(), "John Doe");
assertEquals(example.getAge(), 30);
}
}
|
Add function to display a price with units
|
import 'whatwg-fetch';
import _ from 'underscore';
let helpers = {
capitalize,
checkStatus,
displayPrice,
displayPricePerUnit,
findTypeId,
findTypeName,
parseJSON,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
};
function capitalize(string) {
if (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
}
function checkStatus(res) {
if (res.status >= 200 && res.status < 300) {
return res;
}
let error = new Error(res.statusText);
error.res = res;
throw error;
}
function displayPrice(price) {
if (typeof price === 'string') {
// eslint-disable-next-line no-param-reassign
price = Number(price);
}
if (price % 1 === 0) {
return `$${price}`;
}
return `$${price.toFixed(2)}`;
}
function displayPricePerUnit(price, unit) {
if (unit) {
return `${displayPrice(price)} / ${unit}`;
}
return `${displayPrice(price)} / `;
}
function findTypeId(types, name) {
let type = _.findWhere(types, { name });
return type && type.id;
}
function findTypeName(types, id) {
let type = _.findWhere(types, { id });
return type && type.name;
}
function parseJSON(res) {
return res.json();
}
export default helpers;
|
import 'whatwg-fetch';
import _ from 'underscore';
let helpers = {
capitalize,
checkStatus,
displayPrice,
findTypeId,
findTypeName,
parseJSON,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
};
function capitalize(string) {
if (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
}
function checkStatus(res) {
if (res.status >= 200 && res.status < 300) {
return res;
}
let error = new Error(res.statusText);
error.res = res;
throw error;
}
function displayPrice(price) {
if (typeof price === 'string') {
// eslint-disable-next-line no-param-reassign
price = Number(price);
}
if (price % 1 === 0) {
return `$${price}`;
}
return `$${price.toFixed(2)}`;
}
function findTypeId(types, name) {
let type = _.findWhere(types, { name });
return type && type.id;
}
function findTypeName(types, id) {
let type = _.findWhere(types, { id });
return type && type.name;
}
function parseJSON(res) {
return res.json();
}
export default helpers;
|
Clean up destroyed modal properly
|
/** @jsx React.DOM */
define([
"jquery",
"React"
], function($, React) {
return React.createClass({
destroy: function(event) {
if (event.target.className === "modal" ||
event.target.className === "modal-dialog") {
var domNode = this.getDOMNode();
// TODO(ssorallen): Why does this need to unmount from the parentNode?
// If it is unmounted from `domNode`, the second render throws an
// invariant exception.
React.unmountComponentAtNode(domNode.parentNode);
$(domNode).remove();
}
},
render: function() {
return (
<div>
<div className="modal" onClick={this.destroy}>
<div className="modal-dialog">
<div className="modal-content">
{this.props.children}
</div>
</div>
</div>
<div className="modal-backdrop fade in"></div>
</div>
);
}
});
});
|
/** @jsx React.DOM */
define([
"React"
], function(React) {
return React.createClass({
destroy: function(event) {
if (event.target.className === "modal" ||
event.target.className === "modal-dialog") {
var domNode = this.getDOMNode();
React.unmountComponentAtNode(domNode);
$(domNode).remove();
}
},
render: function() {
return (
<div>
<div className="modal" onClick={this.destroy}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-body">
{this.props.children}
</div>
</div>
</div>
</div>
<div className="modal-backdrop fade in"></div>
</div>
);
}
});
});
|
Fix error handling when output file is specified
|
var css = require('./css')
, less = require('./less')
, sass = require('./sass')
, path = require('path')
, writer = require('write-to-path')
module.exports = function (opts, cb) {
if (typeof opts === 'string') opts = {entry: opts};
if (typeof cb === 'string') opts.output = cb;
if (opts.entry.substr(-4) === 'less') {
less(opts, complete)
} else if (opts.entry.substr(-4) === 'scss') {
sass(opts, complete)
} else {
css(opts, complete)
}
function complete (err, src) {
if (err && opts.output) throw err
if (err) return cb(err)
if (opts.transform) src = opts.transform(src)
if (opts.output) {
writer(path.resolve(process.cwd(), opts.output), {debug: opts.debug})(null, src)
} else {
cb(null, src)
}
}
}
|
var css = require('./css')
, less = require('./less')
, sass = require('./sass')
, path = require('path')
, writer = require('write-to-path')
module.exports = function (opts, cb) {
if (typeof opts === 'string') opts = {entry: opts};
if (typeof cb === 'string') opts.output = cb;
if (opts.entry.substr(-4) === 'less') {
less(opts, complete)
} else if (opts.entry.substr(-4) === 'scss') {
sass(opts, complete)
} else {
css(opts, complete)
}
function complete (err, src) {
if (err) return cb(err)
if (opts.transform) src = opts.transform(src)
if (opts.output) {
writer(path.resolve(process.cwd(), opts.output), {debug: opts.debug})(null, src)
} else {
cb(null, src)
}
}
}
|
Change getBundles() method to abstract
|
<?php
namespace Perfumer\Framework\Application;
use Perfumer\Component\Container\Container;
abstract class AbstractApplication
{
/**
* @return void
*/
public function run()
{
$this->before();
$container = new Container();
$container->registerBundles($this->getBundles());
$this->after();
$container->get('proxy')->run();
}
/**
* @return array
*/
abstract public function getBundles();
/**
* @return void
*/
protected function before()
{
}
/**
* @return void
*/
protected function after()
{
}
}
|
<?php
namespace Perfumer\Framework\Application;
use Perfumer\Component\Container\Container;
abstract class AbstractApplication
{
/**
* @return void
*/
public function run()
{
$this->before();
$container = new Container();
$container->registerBundles($this->getBundles());
$this->after();
$container->get('proxy')->run();
}
/**
* @return array
*/
protected function getBundles()
{
return [];
}
/**
* @return void
*/
protected function before()
{
}
/**
* @return void
*/
protected function after()
{
}
}
|
Fix redirects for build creation
|
define([
'app'
], function(app) {
'use strict';
return {
parent: 'project_details',
url: "new/build/",
templateUrl: 'partials/project-build-create.html',
controller: function($scope, $rootScope, $http, $state, flash, projectData) {
$scope.createBuild = function() {
var buildData = angular.copy($scope.build);
buildData.project = projectData.slug;
$http.post('/api/0/builds/', buildData)
.success(function(data){
if (data.length === 0) {
flash('error', 'Unable to create a new build.');
} else if (data.length > 1) {
flash('success', data.length + ' new builds created.');
return $state.go('project_details');
} else {
return $state.go('build_details', {build_id: data[0].id});
}
})
.error(function(){
flash('error', 'Unable to create a new build.');
});
};
$scope.build = {};
}
};
});
|
define([
'app'
], function(app) {
'use strict';
return {
parent: 'project_details',
url: "new/build/",
templateUrl: 'partials/project-build-create.html',
controller: function($scope, $rootScope, $http, $location, flash, projectData) {
$scope.createBuild = function() {
var buildData = angular.copy($scope.build);
buildData.project = projectData.slug;
$http.post('/api/0/builds/', buildData)
.success(function(data){
if (data.length === 0) {
flash('error', 'Unable to create a new build.');
} else if (data.length > 1) {
flash('success', data.length + ' new builds created.');
return $location.path('/projects/' + buildData.project + '/');
} else {
return $location.path('/builds/' + data[0].id + '/');
}
})
.error(function(){
flash('error', 'Unable to create a new build.');
});
};
$scope.build = {};
}
};
});
|
Abort mission, abort mission! Expanded the wrong one.
|
package com.minelittlepony.model.armour;
import com.minelittlepony.model.capabilities.IModelWrapper;
import com.minelittlepony.pony.data.IPonyData;
public class PonyArmor implements IModelWrapper, IEquestrianArmor {
public final ModelPonyArmor outerLayer;
public final ModelPonyArmor innerLayer;
public PonyArmor(ModelPonyArmor outer, ModelPonyArmor inner) {
outerLayer = outer;
innerLayer = inner;
}
@Override
public void apply(IPonyData meta) {
outerLayer.metadata = meta;
innerLayer.metadata = meta;
}
@Override
public void init() {
outerLayer.init(0, 1.05F);
innerLayer.init(0, 0.5F);
}
@Override
public ModelPonyArmor getArmorForLayer(ArmorLayer layer) {
if (layer == ArmorLayer.INNER) {
return innerLayer;
}
return outerLayer;
}
}
|
package com.minelittlepony.model.armour;
import com.minelittlepony.model.capabilities.IModelWrapper;
import com.minelittlepony.pony.data.IPonyData;
public class PonyArmor implements IModelWrapper, IEquestrianArmor {
public final ModelPonyArmor outerLayer;
public final ModelPonyArmor innerLayer;
public PonyArmor(ModelPonyArmor outer, ModelPonyArmor inner) {
outerLayer = outer;
innerLayer = inner;
}
@Override
public void apply(IPonyData meta) {
outerLayer.metadata = meta;
innerLayer.metadata = meta;
}
@Override
public void init() {
outerLayer.init(0, 1);
innerLayer.init(0, 0.55F);
}
@Override
public ModelPonyArmor getArmorForLayer(ArmorLayer layer) {
if (layer == ArmorLayer.INNER) {
return innerLayer;
}
return outerLayer;
}
}
|
Extend time lenght of animations
Extend time lenght of animations to show blocks
|
jQuery(document).ready(function($){
var timelineBlocks = $('.cd-timeline-block'),
offset = 0.8;
// hide timeline blocks which are outside the viewport
hideBlocks(timelineBlocks, offset);
// on scolling, show/animate timeline blocks when enter the viewport
$(window).on('scroll', function(){
(!window.requestAnimationFrame)
? setTimeout(function(){ showBlocks(timelineBlocks, offset); }, 300)
: window.requestAnimationFrame(function(){ showBlocks(timelineBlocks, offset); });
});
function hideBlocks(blocks, offset) {
blocks.each(function(){
( $(this).offset().top > $(window).scrollTop()+$(window).height()*offset ) && $(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden');
});
}
function showBlocks(blocks, offset) {
blocks.each(function(){
( $(this).offset().top <= $(window).scrollTop() + $(window).height() * offset && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) && $(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
});
}
});
|
jQuery(document).ready(function($){
var timelineBlocks = $('.cd-timeline-block'),
offset = 0.8;
//hide timeline blocks which are outside the viewport
hideBlocks(timelineBlocks, offset);
//on scolling, show/animate timeline blocks when enter the viewport
$(window).on('scroll', function(){
(!window.requestAnimationFrame)
? setTimeout(function(){ showBlocks(timelineBlocks, offset); }, 100)
: window.requestAnimationFrame(function(){ showBlocks(timelineBlocks, offset); });
});
function hideBlocks(blocks, offset) {
blocks.each(function(){
( $(this).offset().top > $(window).scrollTop()+$(window).height()*offset ) && $(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden');
});
}
function showBlocks(blocks, offset) {
blocks.each(function(){
( $(this).offset().top <= $(window).scrollTop()+$(window).height()*offset && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) && $(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
});
}
});
|
Fix a webpack plugin for production
|
const path = require('path');
const webpack = require('webpack');
const { isDevelopment, isTest } = require('../configuration');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackSplitByPath = require('webpack-split-by-path');
const basePlugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
__DEV__: isDevelopment
}),
new WebpackSplitByPath([{
name: 'vendor',
path: [path.join(__dirname, '../node_modules')]
}]),
new HtmlWebpackPlugin({ template: './src/index.html', inject: 'body' }),
new CopyWebpackPlugin([{
from: './src/assets/favicon.ico',
to: 'assets'
}]),
new webpack.NoErrorsPlugin()
];
const developmentPlugins = [new webpack.HotModuleReplacementPlugin()];
const productionPlugins = [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
];
module.exports = isTest ? undefined : basePlugins.concat(isDevelopment ?
developmentPlugins :
productionPlugins
);
|
const path = require('path');
const webpack = require('webpack');
const { isDevelopment, isTest } = require('../configuration');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackSplitByPath = require('webpack-split-by-path');
const basePlugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
__DEV__: isDevelopment
}),
new WebpackSplitByPath([{
name: 'vendor',
path: [path.join(__dirname, '../node_modules')]
}]),
new HtmlWebpackPlugin({ template: './src/index.html', inject: 'body' }),
new CopyWebpackPlugin([{
from: './src/assets/favicon.ico',
to: 'assets'
}]),
new webpack.NoErrorsPlugin()
];
const developmentPlugins = [new webpack.HotModuleReplacementPlugin()];
const productionPlugins = [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
];
module.exports = isTest ? undefined : basePlugins.concat(isDevelopment ?
developmentPlugins :
productionPlugins
);
|
Remove link to private document.
|
"""
Eliot: Logging as Storytelling
Suppose we turn from outside estimates of a man, to wonder, with keener
interest, what is the report of his own consciousness about his doings or
capacity: with what hindrances he is carrying on his daily labors; what
fading of hopes, or what deeper fixity of self-delusion the years are
marking off within him; and with what spirit he wrestles against universal
pressure, which will one day be too heavy for him, and bring his heart to
its final pause.
-- George Eliot, "Middlemarch"
"""
# Expose the public API:
from ._message import Message
from ._action import startAction, startTask, Action
from ._output import ILogger, Logger, MemoryLogger
from ._validation import Field, MessageType, ActionType
from ._traceback import writeTraceback, writeFailure
addDestination = Logger._destinations.add
removeDestination = Logger._destinations.remove
__all__ = ["Message", "writeTraceback", "writeFailure",
"startAction", "startTask", "Action",
"Field", "MessageType", "ActionType",
"ILogger", "Logger", "MemoryLogger", "addDestination",
"removeDestination",
]
|
"""
Eliot: An Opinionated Logging Library
Suppose we turn from outside estimates of a man, to wonder, with keener
interest, what is the report of his own consciousness about his doings or
capacity: with what hindrances he is carrying on his daily labors; what
fading of hopes, or what deeper fixity of self-delusion the years are
marking off within him; and with what spirit he wrestles against universal
pressure, which will one day be too heavy for him, and bring his heart to
its final pause.
-- George Eliot, "Middlemarch"
See http://wiki.hybrid-cluster.com/index.php?title=Logging_Design_Document for
motivation.
"""
# Expose the public API:
from ._message import Message
from ._action import startAction, startTask, Action
from ._output import ILogger, Logger, MemoryLogger
from ._validation import Field, MessageType, ActionType
from ._traceback import writeTraceback, writeFailure
addDestination = Logger._destinations.add
removeDestination = Logger._destinations.remove
__all__ = ["Message", "writeTraceback", "writeFailure",
"startAction", "startTask", "Action",
"Field", "MessageType", "ActionType",
"ILogger", "Logger", "MemoryLogger", "addDestination",
"removeDestination",
]
|
[storybook] Read port and enabled status from configuration
|
#!/usr/bin/env node
/* eslint-disable no-process-exit, no-console */
const path = require('path')
const express = require('express')
const middleware = require('@kadira/storybook/dist/server/middleware')
const webpackConfig = require('../config/webpack.config')
const storybook = middleware.default || middleware
let app = null
process.on('message', msg => {
switch (msg.event) {
case 'start':
return startServer(msg)
default:
return unhandledMessage(msg)
}
})
function startServer(msg) {
webpackConfig.setSanityContext(msg.config)
const config = tryLoadConfig(msg.config.basePath)
const enabled = config.enabled !== false
const port = config.port || 9001
if (!enabled) {
return
}
app = express()
app.use(express.static(msg.config.staticPath, {index: false}))
app.use(storybook(path.join(__dirname, '..', 'config')))
app.listen(port, msg.config.httpHost, error => {
if (error) {
// @todo message back that we've exited
throw error
}
process.send({event: 'listening', url: `http://${msg.config.httpHost}:${port}/`})
})
}
function unhandledMessage(msg) {
console.error(`Unhandled message of type "${msg.event}"; %s`, JSON.stringify(msg, null, 2))
}
function tryLoadConfig(basePath) {
try {
return require(path.join(basePath, 'config', '@sanity', 'storybook.json'))
} catch (err) {
return {}
}
}
|
#!/usr/bin/env node
/* eslint-disable no-process-exit, no-console */
const path = require('path')
const express = require('express')
const middleware = require('@kadira/storybook/dist/server/middleware')
const webpackConfig = require('../config/webpack.config')
const storybook = middleware.default || middleware
let app = null
process.on('message', msg => {
switch (msg.event) {
case 'start':
return startServer(msg)
default:
return unhandledMessage(msg)
}
})
function startServer(msg) {
webpackConfig.setSanityContext(msg.config)
app = express()
app.use(express.static(msg.config.staticPath, {index: false}))
app.use(storybook(path.join(__dirname, '..', 'config')))
app.listen(9001, msg.config.httpHost, error => {
if (error) {
// @todo message back that we've exited
throw error
}
process.send({event: 'listening', url: `http://${msg.config.httpHost}:9001/`})
})
}
function unhandledMessage(msg) {
console.error(`Unhandled message of type "${msg.event}"; %s`, JSON.stringify(msg, null, 2))
}
|
Make demo max out at 40 turns
|
var ClassicChess = require('../classic-chess.js');
var GuiBoard = require('../lib/gui_board.js');
var _ = require('lodash');
describe('Classic Chess', function() {
it('everything', function() {
var game = new ClassicChess.Game();
var board = game.board();
var guiBoard = new GuiBoard({
board: board,
player1: game.player1(),
player2: game.player2()
});
console.log('* Start *');
guiBoard.print();
for (var turns = 1; turns <= 40; turns++) {
var turnInfo = game.currentTurnInfo();
console.log('* ' + turnInfo.player().name + '\'s move *');
var piece = _.sample(turnInfo.movablePieces());
game.makeMove({ move: _.sample(piece.possibleMoves({ board: board })) });
guiBoard.print();
}
});
});
|
var ClassicChess = require('../classic-chess.js');
var GuiBoard = require('../lib/gui_board.js');
var _ = require('lodash');
describe('Classic Chess', function() {
it('everything', function() {
var game = new ClassicChess.Game();
var board = game.board();
var guiBoard = new GuiBoard({
board: board,
player1: game.player1(),
player2: game.player2()
});
console.log('* Start *');
guiBoard.print();
for (var turns = 1; turns <= 30; turns++) {
var turnInfo = game.currentTurnInfo();
console.log('* ' + turnInfo.player().name + '\'s move *');
var piece = _.sample(turnInfo.movablePieces());
game.makeMove({ move: _.sample(piece.possibleMoves({ board: board })) });
guiBoard.print();
}
});
});
|
Add host and remove debug
|
#!bin/python
import json
import lib_zpr
from flask import Flask, jsonify, make_response
app = Flask(__name__)
api_version = 'v1.0'
api_base = str('/zpr/{v}'.format(v=api_version))
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
# @app.route('/zpr/job')
# def ls_test():
# return json.dumps(call('ls'))
@app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET'])
def check_job(backup_host):
job = str(lib_zpr.check_zpr_rsync_job(backup_host))
return json.dumps(job)
@app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET'])
def check_offsite_job(backup_host):
lib_zpr.check_duplicity_job(backup_host, print_output=False)
return json.dumps(str(lib_zpr.check_duplicity_out[0]))
if __name__ == '__main__':
app.run(host='127.0.0.1')
|
#!bin/python
import json
import lib_zpr
from flask import Flask, jsonify, make_response
app = Flask(__name__)
api_version = 'v1.0'
api_base = str('/zpr/{v}'.format(v=api_version))
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
# @app.route('/zpr/job')
# def ls_test():
# return json.dumps(call('ls'))
@app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET'])
def check_job(backup_host):
job = str(lib_zpr.check_zpr_rsync_job(backup_host))
return json.dumps(job)
@app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET'])
def check_offsite_job(backup_host):
lib_zpr.check_duplicity_job(backup_host, print_output=False)
return json.dumps(str(lib_zpr.check_duplicity_out[0]))
if __name__ == '__main__':
app.run(debug=True)
|
Add NewHttp to the list of captured interfaces
This adds some nice error reporting info like IP address, cookies, headers, etc.
See https://github.com/getsentry/raven-go/blob/master/http.go#L76
|
package sentry
import (
"errors"
"fmt"
"net/http"
"runtime/debug"
"github.com/getsentry/raven-go"
"github.com/gin-gonic/gin"
)
func Recovery(client *raven.Client, onlyCrashes bool) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
flags := map[string]string{
"endpoint": c.Request.RequestURI,
}
if rval := recover(); rval != nil {
debug.PrintStack()
rvalStr := fmt.Sprint(rval)
packet := raven.NewPacket(rvalStr,
raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)),
raven.NewHttp(c.Request))
client.Capture(packet, flags)
c.AbortWithStatus(http.StatusInternalServerError)
}
if !onlyCrashes {
for _, item := range c.Errors {
packet := raven.NewPacket(item.Error(), &raven.Message{
Message: item.Error(),
Params: []interface{}{item.Meta},
})
client.Capture(packet, flags)
}
}
}()
c.Next()
}
}
|
package sentry
import (
"errors"
"fmt"
"net/http"
"runtime/debug"
"github.com/getsentry/raven-go"
"github.com/gin-gonic/gin"
)
func Recovery(client *raven.Client, onlyCrashes bool) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
flags := map[string]string{
"endpoint": c.Request.RequestURI,
}
if rval := recover(); rval != nil {
debug.PrintStack()
rvalStr := fmt.Sprint(rval)
packet := raven.NewPacket(rvalStr, raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)))
client.Capture(packet, flags)
c.AbortWithStatus(http.StatusInternalServerError)
}
if !onlyCrashes {
for _, item := range c.Errors {
packet := raven.NewPacket(item.Error(), &raven.Message{
Message: item.Error(),
Params: []interface{}{item.Meta},
})
client.Capture(packet, flags)
}
}
}()
c.Next()
}
}
|
Use geodesyTransactionManager in all rest tests.
|
package au.gov.ga.geodesy.interfaces.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import org.testng.annotations.BeforeClass;
import au.gov.ga.geodesy.support.spring.GeodesyRestConfig;
import au.gov.ga.geodesy.support.spring.GeodesyTestConfig;
import au.gov.ga.geodesy.support.spring.PersistenceJpaConfig;
@ContextConfiguration(
classes = {GeodesyTestConfig.class, GeodesyRestConfig.class, PersistenceJpaConfig.class},
loader = AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
@Transactional("geodesyTransactionManager")
public class RestTest extends AbstractTransactionalTestNGSpringContextTests {
@Autowired
private WebApplicationContext webApplicationContext;
protected static MockMvc mvc;
@BeforeClass
public void setUp() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
|
package au.gov.ga.geodesy.interfaces.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.testng.annotations.BeforeClass;
import au.gov.ga.geodesy.support.spring.GeodesyTestConfig;
import au.gov.ga.geodesy.support.spring.PersistenceJpaConfig;
@ContextConfiguration(
classes = {GeodesyTestConfig.class, RestConfig.class, PersistenceJpaConfig.class},
loader = AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
public class RestTest extends AbstractTransactionalTestNGSpringContextTests {
@Autowired
private WebApplicationContext webApplicationContext;
protected static MockMvc mvc;
@BeforeClass
public void setUp() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
|
Fix warnings, and use only one var keyword per function.
|
/*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
jQuery(function() {
var url, reloadPage, statusChecker;
url = window.location.href;
reloadPage = function() {
window.location.replace(url);
};
statusChecker = function() {
jQuery.ajax({
url: url,
success: reloadPage,
error: function(jqXHR, textStatus, errorThrown){
if (jqXHR.status == 503) {
window.setTimeout(statusChecker, 5000);
} else {
// If the page is throwing another type of error let the user see it
reloadPage();
}
}
});
};
window.setTimeout(statusChecker, 5000);
});
|
/*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
jQuery(function() {
var url = window.location.href;
var reloadPage = function() {
window.location.replace(url);
};
var statusChecker = function() {
jQuery.ajax({
url: url,
success: reloadPage,
error: function(jqXHR, textStatus, errorThrown){
if (jqXHR.status == 503) {
window.setTimeout(statusChecker, 5000);
} else {
// If the page is throwing another type of error let the user see it
reloadPage();
}
}
});
}
window.setTimeout(statusChecker, 5000);
});
|
Fix Tax Letter test that was leaving the date to chance
|
import { find, visit } from '@ember/test-helpers';
import { module, test } from "qunit";
import { setupApplicationTest } from 'ember-qunit';
import moment from "moment";
module("Acceptance | download tax letter", function(hooks) {
setupApplicationTest(hooks);
test("tax letter link is visible", async function(assert) {
let lastYear = moment().subtract(1, "year").year();
server.create("user");
server.createList("pledge", 1, {
orderDate: lastYear + "-03-26T11:57:22.139Z"
});
await visit("/");
assert.equal(
find(".tax-letter-link").textContent
.trim(),
`${lastYear} Tax Receipt`
);
});
test("tax letter is not visible if no pledges", async function(assert) {
server.create("user");
server.createList('pledge', 0);
await visit("/");
assert.notOk(find(".tax-letter-link"));
});
test("tax letter is not visible if pledges from ineligible year", async function(assert) {
server.create("user");
server.createList("pledge", 20, {
orderDate: "2015-10-28T07:34:00.502Z"
});
await visit("/");
assert.notOk(find(".tax-letter-link"));
});
});
|
import { find, visit } from '@ember/test-helpers';
import { module, test } from "qunit";
import { setupApplicationTest } from 'ember-qunit';
import moment from "moment";
module("Acceptance | download tax letter", function(hooks) {
setupApplicationTest(hooks);
test("tax letter link is visible", async function(assert) {
let lastYear = moment().subtract(1, "year").year();
server.create("user");
server.createList("pledge", 20);
await visit("/");
assert.equal(
find(".tax-letter-link").textContent
.trim(),
`${lastYear} Tax Receipt`
);
});
test("tax letter is not visible if no pledges", async function(assert) {
server.create("user");
server.createList('pledge', 0);
await visit("/");
assert.notOk(find(".tax-letter-link"));
});
test("tax letter is not visible if pledges from ineligible year", async function(assert) {
server.create("user");
server.createList("pledge", 20, {
orderDate: "2015-10-28T07:34:00.502Z"
});
await visit("/");
assert.notOk(find(".tax-letter-link"));
});
});
|
Check if the user variable is null before passing it as the submitter user
|
<?php
namespace OkulBilisim\OjsImportBundle\Importer\PKP;
use Ojs\JournalBundle\Entity\Article;
use OkulBilisim\OjsImportBundle\Importer\Importer;
class ArticleSubmitterImporter extends Importer
{
/**
* @param UserImporter $userImporter
*/
public function importArticleSubmitter($userImporter)
{
$pendingImports = $this->em->getRepository('OkulBilisimOjsImportBundle:PendingSubmitterImport')->findAll();
$this->consoleOutput->writeln("Importing article submitters...");
foreach ($pendingImports as $import) {
$user = $userImporter->importUser($import->getOldId());
if ($user) {
/** @var Article $article */
$article = $import->getArticle();
$article->setSubmitterUser($user);
$this->em->persist($article);
$this->em->flush($article);
}
}
}
}
|
<?php
namespace OkulBilisim\OjsImportBundle\Importer\PKP;
use Ojs\JournalBundle\Entity\Article;
use OkulBilisim\OjsImportBundle\Importer\Importer;
class ArticleSubmitterImporter extends Importer
{
/**
* @param UserImporter $userImporter
*/
public function importArticleSubmitter($userImporter)
{
$pendingImports = $this->em->getRepository('OkulBilisimOjsImportBundle:PendingSubmitterImport')->findAll();
$this->consoleOutput->writeln("Importing article submitters...");
foreach ($pendingImports as $import) {
$user = $userImporter->importUser($import->getOldId());
/** @var Article $article */
$article = $import->getArticle();
$article->setSubmitterUser($user);
$this->em->persist($article);
$this->em->flush($article);
}
}
}
|
Add NEX navigator.* API support to the shim
|
!(function( global ) {
// NEX<->CRX support set up
var nexAPIStubs = ['app', 'extension', 'windows', 'tabs', 'browserAction', 'contextMenus', 'i18n', 'webRequest', ''];
if(!global.chrome) {
global.chrome = {};
}
for(var i = 0, l = nexAPIStubs.length; i < l; i++) {
global.chrome[ nexAPIStubs[ i ] ] = global.navigator[ nexAPIStubs[ i ] ] || {};
}
var Opera = function() {};
Opera.prototype.REVISION = '1';
Opera.prototype.version = function() {
return this.REVISION;
};
Opera.prototype.buildNumber = function() {
return this.REVISION;
};
Opera.prototype.postError = function( str ) {
console.log( str );
};
var opera = global.opera || new Opera();
var manifest = chrome.app.getDetails(); // null in injected scripts / popups
navigator.browserLanguage=navigator.language; //Opera defines both, some extensions use the former
var isReady = false;
var _delayedExecuteEvents = [
// Example:
// { 'target': opera.extension, 'methodName': 'message', 'args': event }
];
function addDelayedEvent(target, methodName, args) {
if(isReady) {
target[methodName].apply(target, args);
} else {
_delayedExecuteEvents.push({
"target": target,
"methodName": methodName,
"args": args
});
}
};
|
!(function( global ) {
var Opera = function() {};
Opera.prototype.REVISION = '1';
Opera.prototype.version = function() {
return this.REVISION;
};
Opera.prototype.buildNumber = function() {
return this.REVISION;
};
Opera.prototype.postError = function( str ) {
console.log( str );
};
var opera = global.opera || new Opera();
var manifest = chrome.app.getDetails(); // null in injected scripts / popups
navigator.browserLanguage=navigator.language; //Opera defines both, some extensions use the former
var isReady = false;
var _delayedExecuteEvents = [
// Example:
// { 'target': opera.extension, 'methodName': 'message', 'args': event }
];
function addDelayedEvent(target, methodName, args) {
if(isReady) {
target[methodName].apply(target, args);
} else {
_delayedExecuteEvents.push({
"target": target,
"methodName": methodName,
"args": args
});
}
};
|
Fix dithering right-click color inversion on FF/IE
Record pressed mouse button type only at mousedown time.
On IE/FF, the button type is not available during mousemove.
Did a round of testing on both FF and Chrome.
|
/**
* @provide pskl.tools.drawing.DitheringTool
*
* @require pskl.utils
*/
(function() {
var ns = $.namespace('pskl.tools.drawing');
ns.DitheringTool = function() {
ns.SimplePen.call(this);
this.toolId = 'tool-dithering';
this.helpText = 'Dithering tool';
};
pskl.utils.inherit(ns.DitheringTool, ns.SimplePen);
/**
* @override
*/
ns.DitheringTool.prototype.applyToolAt = function(col, row, color, frame, overlay, event) {
// On Firefox/IE, the clicked button type is not part of the mousemove event.
// Ensure we record the pressed button on the initial mousedown only.
if (event.type == 'mousedown') {
this.invertColors_ = event.button === Constants.RIGHT_BUTTON;
}
// Use primary selected color on cell with either an odd col or row.
// Use secondary color otherwise.
// When using the right mouse button, invert the above behavior to allow quick corrections.
var usePrimaryColor = (col + row) % 2;
usePrimaryColor = this.invertColors_ ? !usePrimaryColor : usePrimaryColor;
var selectedColors = pskl.app.selectedColorsService.getColors();
var ditheringColor = usePrimaryColor ? selectedColors[0] : selectedColors[1];
this.superclass.applyToolAt.call(this, col, row, ditheringColor, frame, overlay, event);
};
})();
|
/**
* @provide pskl.tools.drawing.DitheringTool
*
* @require pskl.utils
*/
(function() {
var ns = $.namespace('pskl.tools.drawing');
ns.DitheringTool = function() {
ns.SimplePen.call(this);
this.toolId = 'tool-dithering';
this.helpText = 'Dithering tool';
};
pskl.utils.inherit(ns.DitheringTool, ns.SimplePen);
/**
* @override
*/
ns.DitheringTool.prototype.applyToolAt = function(col, row, color, frame, overlay, event) {
// Use primary selected color on cell with either an odd col or row.
// Use secondary color otherwise.
// When using the right mouse button, invert the above behavior to allow quick corrections.
var usePrimaryColor = (col + row) % 2;
var invertColors = event.button === Constants.RIGHT_BUTTON;
usePrimaryColor = invertColors ? !usePrimaryColor : usePrimaryColor;
var selectedColors = pskl.app.selectedColorsService.getColors();
var ditheringColor = usePrimaryColor ? selectedColors[0] : selectedColors[1];
this.superclass.applyToolAt.call(this, col, row, ditheringColor, frame, overlay, event);
};
})();
|
Add comment for strongly connected graphs
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def dfs_recur():
pass
def traverse_dfs_recur():
pass
def transpose_graph():
pass
def strongly_connected_graph():
"""Find strongly connected graphs by Kosaraju's Algorithm."""
def main():
# 3 strongly connected graphs: {A, B, D, E, G}, {C}, {F, H, I}.
adjacency_dict = {
'A': {'B'},
'B': {'C', 'E'},
'C': {'C', 'F'},
'D': {'B', 'G'},
'E': {'A', 'D'},
'F': {'H'},
'G': {'E'},
'H': {'I'},
'I': {'F'}
}
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def dfs_recur():
pass
def traverse_dfs_recur():
pass
def transpose_graph():
pass
def strongly_connected_graph():
"""Find strongly connected graphs by Kosaraju's Algorithm."""
def main():
adjacency_dict = {
'A': {'B'},
'B': {'C', 'E'},
'C': {'C', 'F'},
'D': {'B', 'G'},
'E': {'A', 'D'},
'F': {'H'},
'G': {'E'},
'H': {'I'},
'I': {'F'}
}
if __name__ == '__main__':
main()
|
Remove title w and h params in popupCenter
|
// https://github.com/kni-labs/rrssb
var popupCenter = function(url) {
var w = 580;
var h = 470;
// Fixes dual-screen position Most browsers Firefox
var dualScreenLeft =
window.screenLeft !== undefined ? window.screenLeft : screen.left;
var dualScreenTop =
window.screenTop !== undefined ? window.screenTop : screen.top;
var width = window.innerWidth
? window.innerWidth
: document.documentElement.clientWidth
? document.documentElement.clientWidth
: screen.width;
var height = window.innerHeight
? window.innerHeight
: document.documentElement.clientHeight
? document.documentElement.clientHeight
: screen.height;
var left = width / 2 - w / 2 + dualScreenLeft;
var top = height / 3 - h / 3 + dualScreenTop;
var newWindow = window.open(
url,
"share-popup",
"scrollbars=yes, width=" +
w +
", height=" +
h +
", top=" +
top +
", left=" +
left
);
// Puts focus on the newWindow
if (newWindow && newWindow.focus) {
newWindow.focus();
}
};
document.querySelectorAll(".popup").forEach(function(el) {
el.addEventListener("click", function(e) {
popupCenter(el.getAttribute("href"));
e.preventDefault();
});
});
|
// https://github.com/kni-labs/rrssb
var popupCenter = function(url, title, w, h) {
// Fixes dual-screen position Most browsers Firefox
var dualScreenLeft =
window.screenLeft !== undefined ? window.screenLeft : screen.left;
var dualScreenTop =
window.screenTop !== undefined ? window.screenTop : screen.top;
var width = window.innerWidth
? window.innerWidth
: document.documentElement.clientWidth
? document.documentElement.clientWidth
: screen.width;
var height = window.innerHeight
? window.innerHeight
: document.documentElement.clientHeight
? document.documentElement.clientHeight
: screen.height;
var left = width / 2 - w / 2 + dualScreenLeft;
var top = height / 3 - h / 3 + dualScreenTop;
var newWindow = window.open(
url,
title,
"scrollbars=yes, width=" +
w +
", height=" +
h +
", top=" +
top +
", left=" +
left
);
// Puts focus on the newWindow
if (newWindow && newWindow.focus) {
newWindow.focus();
}
};
document.querySelectorAll(".popup").forEach(function(el) {
el.addEventListener("click", function(e) {
popupCenter(el.getAttribute("href"), "TODO", 580, 470);
e.preventDefault();
});
});
|
Fix issue when API wasn't returning correct service dialog results
|
(function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'marketplace.details': {
url: '/:serviceTemplateId',
templateUrl: 'app/states/marketplace/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Service Template Details',
resolve: {
dialogs: resolveDialogs,
serviceTemplate: resolveServiceTemplate
}
}
};
}
/** @ngInject */
function resolveServiceTemplate($stateParams, CollectionsApi) {
var options = {attributes: ['picture', 'picture.image_href']};
return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId, options);
}
/** @ngInject */
function resolveDialogs($stateParams, CollectionsApi) {
var options = {expand: 'resources', attributes: 'content'};
return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options);
}
/** @ngInject */
function StateController(dialogs, serviceTemplate) {
var vm = this;
vm.title = 'Service Template Details';
vm.dialogs = dialogs.resources[0].content;
vm.serviceTemplate = serviceTemplate;
}
})();
|
(function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'marketplace.details': {
url: '/:serviceTemplateId',
templateUrl: 'app/states/marketplace/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Service Template Details',
resolve: {
dialogs: resolveDialogs,
serviceTemplate: resolveServiceTemplate
}
}
};
}
/** @ngInject */
function resolveServiceTemplate($stateParams, CollectionsApi) {
var options = {attributes: ['picture', 'picture.image_href']};
return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId, options);
}
/** @ngInject */
function resolveDialogs($stateParams, CollectionsApi) {
var options = {expand: true, attributes: 'content'};
return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options);
}
/** @ngInject */
function StateController(dialogs, serviceTemplate) {
var vm = this;
vm.title = 'Service Template Details';
vm.dialogs = dialogs.resources[0].content;
vm.serviceTemplate = serviceTemplate;
}
})();
|
Send ID and avatar URL with each Message
|
package main
import (
"log"
"github.com/gorilla/websocket"
"github.com/markbates/goth"
)
// Message emitted by a client and broadcasted to the channel
type Message struct {
UserID string `json:"id"`
UserName string `json:"user"`
UserAvatar string `json:"avatar"`
Content string `json:"content"`
}
// Client is a middleman between the WebSocket connection and the Hub
type Client struct {
hub *Hub
conn *websocket.Conn
send chan Message
user goth.User
}
// read pumps messages from the WebSocket to the Hub
func (c *Client) read() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
for {
var msg Message
err := c.conn.ReadJSON(&msg)
if err != nil {
log.Printf("Error: %v", err)
break
}
msg.UserID = c.user.UserID
msg.UserName = c.user.Name
msg.UserAvatar = c.user.AvatarURL
c.hub.broadcast <- msg
}
}
// write pumps messages from the Hub to the WebSocket
func (c *Client) write() {
defer func() {
c.conn.Close()
}()
for {
msg := <- c.send
err := c.conn.WriteJSON(msg)
if err != nil {
log.Printf("Error: %v", err)
return
}
}
}
|
package main
import (
"log"
"github.com/gorilla/websocket"
"github.com/markbates/goth"
)
// Message emitted by a client and broadcasted to the channel
type Message struct {
User string `json:"user"`
Content string `json:"content"`
}
// Client is a middleman between the WebSocket connection and the Hub
type Client struct {
hub *Hub
conn *websocket.Conn
send chan Message
user goth.User
}
// read pumps messages from the WebSocket to the Hub
func (c *Client) read() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
for {
var msg Message
err := c.conn.ReadJSON(&msg)
if err != nil {
log.Printf("Error: %v", err)
break
}
msg.User = c.user.Name
c.hub.broadcast <- msg
}
}
// write pumps messages from the Hub to the WebSocket
func (c *Client) write() {
defer func() {
c.conn.Close()
}()
for {
msg := <- c.send
err := c.conn.WriteJSON(msg)
if err != nil {
log.Printf("Error: %v", err)
return
}
}
}
|
Remove deleted places from place index
|
from haystack import indexes
from .models import Event, Place, PublicationStatus
from django.utils.html import strip_tags
class EventIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
start_time = indexes.DateTimeField(model_attr='start_time')
end_time = indexes.DateTimeField(model_attr='end_time')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Event
def prepare(self, obj):
#obj.lang_keywords = obj.keywords.filter(language=get_language())
if obj.description:
obj.description = strip_tags(obj.description)
return super(EventIndex, self).prepare(obj)
def index_queryset(self, using=None):
return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC)
class PlaceIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Place
def index_queryset(self, using=None):
return self.get_model().objects.filter(deleted=False)
|
from haystack import indexes
from .models import Event, Place, PublicationStatus
from django.utils.html import strip_tags
class EventIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
start_time = indexes.DateTimeField(model_attr='start_time')
end_time = indexes.DateTimeField(model_attr='end_time')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Event
def prepare(self, obj):
#obj.lang_keywords = obj.keywords.filter(language=get_language())
if obj.description:
obj.description = strip_tags(obj.description)
return super(EventIndex, self).prepare(obj)
def index_queryset(self, using=None):
return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC)
class PlaceIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Place
|
Clean up asset minification script
|
const compressor = require('node-minify');
const { readdirSync } = require('fs');
const { basename, join } = require('path');
const resources = (...dir) => join(...[__dirname, 'src', 'resources'].concat(dir));
const Logger = require(resources('js', 'Logger'));
function minifyAssets() {
const cssPath = resources('css');
const cssFiles = readdirSync(cssPath).filter(f => !f.endsWith('.min.css'));
const jsPath = resources('js');
const jsFiles = readdirSync(jsPath).filter(f => !f.endsWith('.min.js'));
jsFiles.splice(0, 1); // Remove eslintrc
cssFiles.forEach(fileName => {
compressor.minify({
compressor: 'clean-css',
input: `${cssPath}${fileName}`,
output: `${cssPath}${basename(fileName, '.css')}.min.css`
});
});
Logger.info('CSS minification complete.');
jsFiles.forEach(fileName => {
compressor.minify({
compressor: 'uglify-es',
input: `${jsPath}${fileName}`,
output: `${jsPath}${basename(fileName, '.js')}.min.js`
});
});
Logger.info('JS minification complete.');
}
module.exports = minifyAssets;
|
function minifyAssets() {
const compressor = require('node-minify');
const { readdirSync } = require('fs');
const { join } = require('path');
const Logger = require(join(__dirname, './src/resources/js/Logger'));
const cssFiles = readdirSync(join(__dirname, './src/resources/css'))
.filter(f => !f.endsWith('.min.css'));
const cssPath = join(__dirname, './src/resources/css/');
const jsFiles = readdirSync(join(__dirname, './src/resources/js'))
.filter(f => !f.endsWith('.min.js'));
jsFiles.splice(0, 1); // Remove eslintrc
const jsPath = join(__dirname, './src/resources/js/');
cssFiles.forEach(fullFilename => {
const noExtFilename = fullFilename.substr(0, fullFilename.indexOf('.css'));
compressor.minify({
compressor: 'clean-css',
input: `${cssPath}${fullFilename}`,
output: `${cssPath}${noExtFilename}.min.css`
});
});
Logger.info('CSS minification complete.');
jsFiles.forEach(fullFilename => {
const noExtFilename = fullFilename.substr(0, fullFilename.indexOf('.js'));
compressor.minify({
compressor: 'uglify-es',
input: `${jsPath}${fullFilename}`,
output: `${jsPath}${noExtFilename}.min.js`
});
});
Logger.info('JS minification complete.');
}
module.exports = minifyAssets;
|
Fix the count comparison of the routes
|
<?php
/**
* @author Joas Schilling <nickvergessen@owncloud.com>
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Notifications\Tests;
class RoutesTest extends TestCase {
public function testRoutes() {
$routes = include(__DIR__ . '/../../appinfo/routes.php');
$this->assertInternalType('array', $routes);
$this->assertCount(1, $routes);
$this->assertArrayHasKey('routes', $routes);
$this->assertInternalType('array', $routes['routes']);
$this->assertCount(2, $routes['routes']);
}
}
|
<?php
/**
* @author Joas Schilling <nickvergessen@owncloud.com>
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Notifications\Tests;
class RoutesTest extends TestCase {
public function testRoutes() {
$routes = include(__DIR__ . '/../../appinfo/routes.php');
$this->assertInternalType('array', $routes);
$this->assertCount(1, $routes);
$this->assertArrayHasKey('routes', $routes);
$this->assertInternalType('array', $routes['routes']);
$this->assertGreaterThanOrEqual(1, sizeof($routes['routes']));
}
}
|
Add the ObjectId to a job request that is missing it
|
var express = require('express');
var router = express.Router();
// var mongoose = require('../models/mongoose');
const config = require('../config');
// Redis
const Redis = require('ioredis');
var redis_client = new Redis(config.redis_connection);
// routes that end with jobs
// ----------------------------------------------------
// These are redis-based queries
// route to return all current requests (GET http://localhost:3000/api/requests)
router.route('/jobs/submit')
// add a request for a process to launch (accessed at PUT api/requests)
.put(function(req, res) {
let request = req.body.request;
// Add _id to process is not present
if (! request.process._id) {
request.process._id = new mongoose.mongo.ObjectId();
}
console.log(request);
redis_client.lpush('RAPD_JOBS', JSON.stringify(request), function(err, queue_length) {
if (err) {
console.error(err);
res.status(500).json({
success: false,
error: err
});
} else {
console.log('Job added to RAPD_JOBS queue length:', queue_length);
res.status(200).json({
success: true,
queue_length: queue_length
});
}
});
}); // End .put(function(req,res) {
module.exports = router;
|
var express = require('express');
var router = express.Router();
// var mongoose = require('../models/mongoose');
const config = require('../config');
// Redis
const Redis = require('ioredis');
var redis_client = new Redis(config.redis_connection);
// routes that end with jobs
// ----------------------------------------------------
// These are redis-based queries
// route to return all current requests (GET http://localhost:3000/api/requests)
router.route('/jobs/submit')
// add a request for a process to launch (accessed at PUT api/requests)
.put(function(req, res) {
let request = req.body.request;
console.log(request);
redis_client.lpush('RAPD_JOBS', JSON.stringify(request), function(err, queue_length) {
if (err) {
console.error(err);
res.status(500).json({
success: false,
error: err
});
} else {
console.log('Job added to RAPD_JOBS queue length:', queue_length);
res.status(200).json({
success: true,
queue_length: queue_length
});
}
});
}); // End .put(function(req,res) {
module.exports = router;
|
Allow other trees to be returned.
If you override `treeFor` but do not return anything for
`treeFor('addon')` or `treeFor('app')` no code will be shipped to the
browser.
|
/* jshint node: true */
'use strict';
var pickFiles = require('broccoli-static-compiler');
var merge = require('lodash.merge');
module.exports = {
name: 'ember-cli-chosen',
included: function(app) {
this._super.included(app);
// Setup default options for ember-cli-chosen
var options = merge({
'jQuery': true,
'importChosenCSS': true
}, app.options['ember-cli-chosen'] || {});
options.chosenJSType = options.jQuery ? 'jquery' : 'proto';
// Update `ember-cli-chosen` options on our `app` with updated hash
app.options['ember-cli-chosen'] = options;
// Import the correct JS for chosen
app.import(app.bowerDirectory + '/chosen/chosen.' + options.chosenJSType + '.js');
// Import Chosen CSS (done by default)
if(options.importChosenCSS) { app.import(app.bowerDirectory + '/chosen/chosen.css'); }
},
treeForPublic: function(treeName) {
var tree;
// Only include the Chosen sprites if we're including Chosen CSS in the build
if(this.app.options['ember-cli-chosen'].importChosenCSS) {
tree = pickFiles(this.app.bowerDirectory + '/chosen', {
srcDir: '/',
files: ['*.png'],
destDir: '/assets'
});
}
return tree;
}
};
|
/* jshint node: true */
'use strict';
var pickFiles = require('broccoli-static-compiler');
var merge = require('lodash.merge');
module.exports = {
name: 'ember-cli-chosen',
included: function(app) {
this._super.included(app);
// Setup default options for ember-cli-chosen
var options = merge({
'jQuery': true,
'importChosenCSS': true
}, app.options['ember-cli-chosen'] || {});
options.chosenJSType = options.jQuery ? 'jquery' : 'proto';
// Update `ember-cli-chosen` options on our `app` with updated hash
app.options['ember-cli-chosen'] = options;
// Import the correct JS for chosen
app.import(app.bowerDirectory + '/chosen/chosen.' + options.chosenJSType + '.js');
// Import Chosen CSS (done by default)
if(options.importChosenCSS) { app.import(app.bowerDirectory + '/chosen/chosen.css'); }
},
treeFor: function(treeName) {
var tree;
// Only include the Chosen sprites if we're including Chosen CSS in the build
if(treeName === 'public' && this.app.options['ember-cli-chosen'].importChosenCSS) {
tree = pickFiles(this.app.bowerDirectory + '/chosen', {
srcDir: '/',
files: ['*.png'],
destDir: '/assets'
});
}
return tree;
}
};
|
Solve the issue of the power got disconnected during the ride
|
import numpy as np
from fitparse import FitFile
def load_power_from_fit(filename):
""" Method to open the power data from FIT file into a numpy array.
Parameters
----------
filename: str,
Path to the FIT file.
"""
# Check that the filename has the good extension
if filename.endswith('.fit') is not True:
raise ValueError('The file does not have the right extension. Expected *.fit.')
# Create an object to open the activity
activity = FitFile(filename)
activity.parse()
# Get only the power records
records = list(activity.get_messages(name='record'))
# Append the different values inside a list which will be later
# converted to numpy array
power_rec = np.zeros((len(records), ))
# Go through each record
for idx_rec, rec in enumerate(records):
# Extract only the value regarding the power
p = rec.get_value('power')
if p is not None:
power_rec[idx_rec] = float(p)
else:
# raise ValueError('There record without power values. Check what is happening.')
# We put the value to 0 since that it will not influence
# the computation of the RPP
power_rec[idx_rec] = 0.
return power_rec
|
import numpy as np
from fitparse import FitFile
def load_power_from_fit(filename):
""" Method to open the power data from FIT file into a numpy array.
Parameters
----------
filename: str,
Path to the FIT file.
"""
# Check that the filename has the good extension
if filename.endswith('.fit') is not True:
raise ValueError('The file does not have the right extension. Expected *.fit.')
# Create an object to open the activity
activity = FitFile(filename)
activity.parse()
# Get only the power records
records = list(activity.get_messages(name='record'))
# Append the different values inside a list which will be later
# converted to numpy array
power_rec = np.zeros((len(records), ))
# Go through each record
for idx_rec, rec in enumerate(records):
# Extract only the value regarding the power
p = rec.get_value('power')
if p is not None:
power_rec[idx_rec] = float(p)
else:
raise ValueError('There record without power values. Check what is happening.')
return power_rec
|
Fix issue with TLV frame decoder
|
/*
* Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.protocol;
import org.traccar.BaseProtocol;
import org.traccar.CharacterDelimiterFrameDecoder;
import org.traccar.PipelineBuilder;
import org.traccar.TrackerServer;
import java.util.List;
public class TlvProtocol extends BaseProtocol {
public TlvProtocol() {
super("tlv");
}
@Override
public void initTrackerServers(List<TrackerServer> serverList) {
serverList.add(new TrackerServer(false, getName()) {
@Override
protected void addProtocolHandlers(PipelineBuilder pipeline) {
pipeline.addLast("frameDecoder", new CharacterDelimiterFrameDecoder(1024, '\0'));
pipeline.addLast("objectDecoder", new TlvProtocolDecoder(TlvProtocol.this));
}
});
}
}
|
/*
* Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.protocol;
import org.traccar.BaseProtocol;
import org.traccar.CharacterDelimiterFrameDecoder;
import org.traccar.PipelineBuilder;
import org.traccar.TrackerServer;
import java.util.List;
public class TlvProtocol extends BaseProtocol {
public TlvProtocol() {
super("tlv");
}
@Override
public void initTrackerServers(List<TrackerServer> serverList) {
serverList.add(new TrackerServer(false, getName()) {
@Override
protected void addProtocolHandlers(PipelineBuilder pipeline) {
pipeline.addLast("frameDecoder", new CharacterDelimiterFrameDecoder('\0'));
pipeline.addLast("objectDecoder", new TlvProtocolDecoder(TlvProtocol.this));
}
});
}
}
|
Hide message form on success
|
/**
* @class Denkmal_Component_MessageAdd
* @extends Denkmal_Component_Abstract
*/
var Denkmal_Component_MessageAdd = Denkmal_Component_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_MessageAdd',
events: {
'click .showForm': function() {
this.toggleActive(true);
},
'click .hideForm': function() {
this.toggleActive(false);
}
},
childrenEvents: {
'Denkmal_FormField_Tags toggleText': function(view, state) {
this.toggleText(state);
},
'Denkmal_Form_Message success': function(form) {
this.toggleActive(false);
}
},
/**
* @param {Boolean} state
*/
toggleActive: function(state) {
this.$el.toggleClass('state-active', state);
if (!state) {
this.findChild('Denkmal_Form_Message').reset();
}
},
/**
* @param {Boolean} state
*/
toggleText: function(state) {
this.$('.form').toggleClass('state-text', state);
}
});
|
/**
* @class Denkmal_Component_MessageAdd
* @extends Denkmal_Component_Abstract
*/
var Denkmal_Component_MessageAdd = Denkmal_Component_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_MessageAdd',
events: {
'click .showForm': function() {
this.toggleActive(true);
},
'click .hideForm': function() {
this.toggleActive(false);
}
},
childrenEvents: {
'Denkmal_FormField_Tags toggleText': function(view, state) {
this.toggleText(state);
}
},
/**
* @param {Boolean} state
*/
toggleActive: function(state) {
this.$el.toggleClass('state-active', state);
if (!state) {
this.findChild('Denkmal_Form_Message').reset();
}
},
/**
* @param {Boolean} state
*/
toggleText: function(state) {
this.$('.form').toggleClass('state-text', state);
}
});
|
Fix a bug on linux with the requires
|
<?php
require_once("inc/functions.php");
writeHeader("register");
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (isset($_POST["userRegister"]) && isset($_POST["mailRegister"]) && isset($_POST["mailRegisterAgain"]) && isset($_POST["passRegister"])) {
require_once("inc/databaseController.php");
$db = new DatabaseController();
$bool = $db->registerUser($_POST["userRegister"], $_POST["passRegister"], $_POST["mailRegister"]);
$bool = true;
if ($bool) {
$id = $db->getUserID($_POST["userRegister"]);
if ($id) {
$filename = "user_$id.xml";
$default = "default.xml";
$folder = "userSettings/";
if (file_exists($folder.$filename)) {
unlink($folder.$filename);
}
$file = simplexml_load_file($folder.$default);
$file->attributes()->user_id = $id;
$file->asXML($folder.$filename);
header("Location:/login.php");
}
} else {
print "<h3>Ha ocurrido un error</h3>";
print "<a href=/login.php>Pulse aqui</a> para reintentar";
}
}
}
?>
|
<?php
require_once("/inc/functions.php");
writeHeader("register");
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (isset($_POST["userRegister"]) && isset($_POST["mailRegister"]) && isset($_POST["mailRegisterAgain"]) && isset($_POST["passRegister"])) {
require_once("/inc/databaseController.php");
$db = new DatabaseController();
$bool = $db->registerUser($_POST["userRegister"], $_POST["passRegister"], $_POST["mailRegister"]);
$bool = true;
if ($bool) {
$id = $db->getUserID($_POST["userRegister"]);
if ($id) {
$filename = "user_$id.xml";
$default = "default.xml";
$folder = "userSettings/";
if (file_exists($folder.$filename)) {
unlink($folder.$filename);
}
$file = simplexml_load_file($folder.$default);
$file->attributes()->user_id = $id;
$file->asXML($folder.$filename);
header("Location:/login.php");
}
} else {
print "<h3>Ha ocurrido un error</h3>";
print "<a href=/login.php>Pulse aqui</a> para reintentar";
}
}
}
?>
|
Add a method to set the duration
|
package com.kolinkrewinkel.BitLimitTweaks;
import java.util.*;
import com.google.common.base.Joiner;
import org.bukkit.ChatColor;
import org.bukkit.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.block.*;
public class TweaksCommandExecutor implements CommandExecutor {
private final BitLimitTweaks plugin;
public TweaksCommandExecutor(BitLimitTweaks plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender.hasPermission("BitLimitTweaks")) {
if (args.length > 1) {
if (args.equals("weatherDuration")) {
if (sender instanceof Player) {
Player player = (Player)sender;
player.getWorld().setWeatherDuration(args[1]);
}
}
}
} else {
sender.sendMessage(ChatColor.RED + "You don't have permission to execute this command.");
}
return false;
}
}
|
package com.kolinkrewinkel.BitLimitTweaks;
import java.util.*;
import com.google.common.base.Joiner;
import org.bukkit.ChatColor;
import org.bukkit.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.block.*;
public class TweaksCommandExecutor implements CommandExecutor {
private final BitLimitTweaks plugin;
public TweaksCommandExecutor(BitLimitTweaks plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender.hasPermission("BitLimitTweaks")) {
} else {
sender.sendMessage(ChatColor.RED + "You don't have permission to execute this command.");
}
return false;
}
}
|
Set Content item as name of the UI element
|
<?php
namespace Opifer\ContentBundle\ValueProvider;
use Symfony\Component\Form\FormBuilderInterface;
use Opifer\EavBundle\ValueProvider\AbstractValueProvider;
use Opifer\EavBundle\ValueProvider\ValueProviderInterface;
class ContentValueProvider extends AbstractValueProvider implements ValueProviderInterface
{
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('content', 'contentpicker', [
'label' => false,
]);
}
/**
* {@inheritDoc}
*/
public function getEntity()
{
return 'Opifer\ContentBundle\Entity\ContentValue';
}
/**
* {@inheritDoc}
*/
public function getLabel()
{
return 'Content item';
}
}
|
<?php
namespace Opifer\ContentBundle\ValueProvider;
use Symfony\Component\Form\FormBuilderInterface;
use Opifer\EavBundle\ValueProvider\AbstractValueProvider;
use Opifer\EavBundle\ValueProvider\ValueProviderInterface;
class ContentValueProvider extends AbstractValueProvider implements ValueProviderInterface
{
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('content', 'contentpicker', [
'label' => false,
]);
}
/**
* {@inheritDoc}
*/
public function getEntity()
{
return 'Opifer\ContentBundle\Entity\ContentValue';
}
/**
* {@inheritDoc}
*/
public function getLabel()
{
return 'Content picker';
}
}
|
Fix online phones auth filter for user
|
<?php
class OnlinePhonesController extends \BaseController {
/**
* Instantiate a new OnlinePhonesController instance.
*/
public function __construct() {
$this->beforeFilter('auth');
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function getIndex()
{
$status = Auth::user()->status;
if($status == 2){
$online_phone = OnlinePhone::all();
}elseif($status == 3){
$domain = Domain::whereUserId(Auth::user()->id)->get(array('sip_server'));
$sip_server = array();
foreach ($domain as $row) {
$sip_server[] = $row['sip_server'];
}
$online_phone = OnlinePhone::whereIn('sip_server', $sip_server)->get();
}else{
$sip_server = Domain::find(Cookie::get('domain_hash'))->sip_server;
$online_phone = OnlinePhone::whereSipServer($sip_server)->get();
}
return View::make('online_phone.index')->with('online_phones', $online_phone);
}
}
|
<?php
class OnlinePhonesController extends \BaseController {
/**
* Instantiate a new OnlinePhonesController instance.
*/
public function __construct() {
$this->beforeFilter('auth');
$this->beforeFilter('auth.manager');
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function getIndex()
{
$status = Auth::user()->status;
if($status == 2){
$online_phone = OnlinePhone::all();
}elseif($status == 3){
$domain = Domain::whereUserId(Auth::user()->id)->get(array('sip_server'));
$sip_server = array();
foreach ($domain as $row) {
$sip_server[] = $row['sip_server'];
}
$online_phone = OnlinePhone::whereIn('sip_server', $sip_server)->get();
}else{
$sip_server = Domain::find(Cookie::get('domain_hash'))->sip_server;
$online_phone = OnlinePhone::whereSipServer($sip_server)->get();
}
return View::make('online_phone.index')->with('online_phones', $online_phone);
}
}
|
Adjust to new reference handling
|
from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, slug = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
iobj = InformationObject.objects.get(campaign=campaign, slug=slug)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
|
from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if reference is None:
return
if 'campaign' not in reference:
return
try:
campaign, slug = reference['campaign'].split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
iobj = InformationObject.objects.get(campaign=campaign, slug=slug)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
|
Switch from development to actual data.
|
#!/usr/bin/env python
import json, os, requests
from awsauth import S3Auth
from datetime import datetime
from pytz import timezone
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route("/")
def renderMenu():
nowWaterloo = datetime.now(timezone('America/Toronto'))
currentDatetime = nowWaterloo.strftime('%I:%M %p on %A, %B %d, %Y')
ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID')
SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
MIXPANEL_TOKEN = os.environ.get('MIXPANEL_TOKEN')
r = requests.get('http://s3.amazonaws.com/uwfoodmenu/response.txt', auth=S3Auth(ACCESS_KEY, SECRET_KEY))
menu = r.json()['response']['data']
return render_template('index.html', menu=menu, nowWaterloo=nowWaterloo, currentDatetime=currentDatetime, mixpanelToken=MIXPANEL_TOKEN)
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
#!/usr/bin/env python
import json, os, requests
from awsauth import S3Auth
from datetime import datetime
from pytz import timezone
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route("/")
def renderMenu():
nowWaterloo = datetime.now(timezone('America/Toronto'))
currentDatetime = nowWaterloo.strftime('%I:%M %p on %A, %B %d, %Y')
ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID')
SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
MIXPANEL_TOKEN = os.environ.get('MIXPANEL_TOKEN')
r = requests.get('http://s3.amazonaws.com/uwfoodmenu/multi.txt', auth=S3Auth(ACCESS_KEY, SECRET_KEY))
menu = r.json()['response']['data']
return render_template('index.html', menu=menu, nowWaterloo=nowWaterloo, currentDatetime=currentDatetime, mixpanelToken=MIXPANEL_TOKEN)
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Change addError() and resetErrors() return type to void
|
<?php
declare(strict_types=1);
namespace Brick\Form;
/**
* Base class for Form & Component.
*/
abstract class Base
{
/**
* @var string[]
*/
private $errors = [];
/**
* @param string $errorMessage
*
* @return void
*/
public function addError(string $errorMessage) : void
{
$this->errors[] = $errorMessage;
}
/**
* @return void
*/
public function resetErrors() : void
{
$this->errors = [];
}
/**
* @return bool
*/
public function hasErrors() : bool
{
return count($this->errors) !== 0;
}
/**
* @return string[]
*/
public function getErrors() : array
{
return $this->errors;
}
}
|
<?php
declare(strict_types=1);
namespace Brick\Form;
/**
* Base class for Form & Component.
*/
abstract class Base
{
/**
* @var string[]
*/
private $errors = [];
/**
* @param string $errorMessage
*
* @return static
*/
public function addError(string $errorMessage) : Base
{
$this->errors[] = $errorMessage;
return $this;
}
/**
* @return static
*/
public function resetErrors() : Base
{
$this->errors = [];
return $this;
}
/**
* @return bool
*/
public function hasErrors() : bool
{
return count($this->errors) !== 0;
}
/**
* @return string[]
*/
public function getErrors() : array
{
return $this->errors;
}
}
|
Add prefix to debug logs to make clearer when not colourised
|
import chalk from 'chalk';
import { map } from 'lodash/fp';
const logger = {
// default log level is silent!
level: 0,
init({ level, colour }) {
if (this.isInitialised) return;
this.colour = !!colour;
const levelMap = { debug: 4, log: 3, warn: 2, error: 1, silent: 0 };
this.level = levelMap[level] || 0;
this.isInitialised = true;
},
debug(...args) {
if (this.level < 4) return;
// add prefix:
args = [ '[DEBUG]', ...args ];
if (this.colour) args = map(chalk.gray, args);
console.log(...args);
},
log(...args) {
if (this.level < 3) return;
console.log(...args);
},
warn(...args) {
if (this.level < 2) return;
if (this.colour) args = map(chalk.yellow, args);
console.log(...args);
},
error(...args) {
if (this.level < 1) return;
if (this.colour) args = map(chalk.red.bold, args);
console.log(...args);
}
};
export default logger;
|
import chalk from 'chalk';
import { map } from 'lodash/fp';
const logger = {
// default log level is silent!
level: 0,
init({ level, colour }) {
if (this.isInitialised) return;
this.colour = !!colour;
const levelMap = { debug: 4, log: 3, warn: 2, error: 1, silent: 0 };
this.level = levelMap[level] || 0;
this.isInitialised = true;
},
debug(...args) {
if (this.level < 4) return;
if (this.colour) args = map(chalk.gray, args);
console.log(...args);
},
log(...args) {
if (this.level < 3) return;
console.log(...args);
},
warn(...args) {
if (this.level < 2) return;
if (this.colour) args = map(chalk.yellow, args);
console.log(...args);
},
error(...args) {
if (this.level < 1) return;
if (this.colour) args = map(chalk.red.bold, args);
console.log(...args);
}
};
export default logger;
|
Add whitespace to export statement
|
import { Map } from 'immutable';
import { Query } from 'sajari';
import { ChangeEmitter } from '../utils/ChangeEmitter.js';
import AppDispatcher from '../dispatcher/AppDispatcher.js';
import SearchConstants from '../constants/SearchConstants.js';
let data = Map();
function setQuery(namespace, query) {
data = data.set(namespace || 'default', query)
}
function getQuery(namespace) {
return data.get(namespace || 'default')
}
class QueryDataStore extends ChangeEmitter {
get(namespace) {
return getQuery(namespace);
}
}
const queryDataStore = new QueryDataStore();
function AddTrackingResetListener(fn) {
queryDataStore.addChangeListener(fn);
}
function RemoveTrackingResetListener(fn) {
queryDataStore.removeChangeListener(fn);
}
queryDataStore.dispatchToken = AppDispatcher.register(payload => {
const action = payload.action
const source = payload.source
if (source === 'SEARCH_ACTION') {
if (action.actionType === SearchConstants.QUERY_DATA) {
setQuery(action.namespace, action.data)
} else if (action.actionType === SearchConstants.TRACKING_RESET) {
const q = getQuery(action.namespace)
if (q) {
q.resetID()
setQuery(action.namespace, q)
}
}
}
})
export { queryDataStore, AddTrackingResetListener, RemoveTrackingResetListener }
|
import { Map } from 'immutable';
import { Query } from 'sajari';
import { ChangeEmitter } from '../utils/ChangeEmitter.js';
import AppDispatcher from '../dispatcher/AppDispatcher.js';
import SearchConstants from '../constants/SearchConstants.js';
let data = Map();
function setQuery(namespace, query) {
data = data.set(namespace || 'default', query)
}
function getQuery(namespace) {
return data.get(namespace || 'default')
}
class QueryDataStore extends ChangeEmitter {
get(namespace) {
return getQuery(namespace);
}
}
const queryDataStore = new QueryDataStore();
function AddTrackingResetListener(fn) {
queryDataStore.addChangeListener(fn);
}
function RemoveTrackingResetListener(fn) {
queryDataStore.removeChangeListener(fn);
}
queryDataStore.dispatchToken = AppDispatcher.register(payload => {
const action = payload.action
const source = payload.source
if (source === 'SEARCH_ACTION') {
if (action.actionType === SearchConstants.QUERY_DATA) {
setQuery(action.namespace, action.data)
} else if (action.actionType === SearchConstants.TRACKING_RESET) {
const q = getQuery(action.namespace)
if (q) {
q.resetID()
setQuery(action.namespace, q)
}
}
}
})
export {queryDataStore, AddTrackingResetListener, RemoveTrackingResetListener}
|
Update GR API to handle Expat Error
|
#!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_details_by_id(goodreads_id):
api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}'
r = requests.get(api_url.format(goodreads_id, goodreads_api_key))
try:
book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book']
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
'num_pages']
book = {}
for k in keys:
book[k] = book_data[k]
if type(book_data['authors']['author']) == list:
authors = [author['name'] for author in book_data['authors']['author']]
authors = ', '.join(authors)
else:
authors = book_data['authors']['author']['name']
book['authors'] = authors
return book
|
#!/usr/bin/env python
import re
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_details_by_id(goodreads_id):
api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}'
r = requests.get(api_url.format(goodreads_id, goodreads_api_key))
try:
book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book']
except (TypeError, KeyError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
'num_pages']
book = {}
for k in keys:
book[k] = book_data[k]
if type(book_data['authors']['author']) == list:
authors = [author['name'] for author in book_data['authors']['author']]
authors = ', '.join(authors)
else:
authors = book_data['authors']['author']['name']
book['authors'] = authors
return book
|
Add purchase functionality in back-end.
|
<?php
namespace App\Http\Controllers;
use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;
class Purchases extends Controller
{
/**
* Purchase book and generate invoice.
*
* @param Request $request
* @return Response
*/
public function index(Request $request) {
$invoice = null;
$purchaseService = new Purchase();
$purchaseQty = $request->input('qty');
$book = Book::find($request->input('book_id'));
$purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);
if($purchasePrice !== null) {
$invoice = new Invoice();
$invoice->book_id = $book->id;
$invoice->amount = $purchasePrice;
$invoice->qty = $purchaseQty;
$invoice->created_at = date('Y-m-d H:i:s');
$invoice->updated_at = date('Y-m-d H:i:s');
$invoice->save();
}
return $invoice;
}
}
|
<?php
namespace App\Http\Controllers;
use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;
class Purchases extends Controller
{
/**
* Purchase book and generate invoice.
*
* @param Request $request
* @return Response
*/
public function index(Request $request) {
$invoice = null;
$purchaseService = new Purchase();
$purchaseQty = $request->input('qty');
$book = Invoice::find($request->input('book_id'));
$purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);
if($purchasePrice !== null) {
$invoice = new Invoice();
$invoice->book_id = $book->id;
$invoice->amount = $purchasePrice;
$invoice->qty = $purchaseQty;
$invoice->created_at = date('Y-m-d H:i:s');
$invoice->updated_at = date('Y-m-d H:i:s');
$invoice->save();
}
return $invoice;
}
}
|
Change date formatting in `/upcoming` to a relative format
|
const MySql = require("./MySql.js");
const entities = require("entities");
const moment = require("moment");
class Meet{
constructor(obj){
Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k]));
}
asMarkdown(){
return `[${this.post_title}](${this.guid}) _${moment(this.meet_start_time).calendar()}_`;
}
}
Meet.fromObjArray = function(objArray){
return objArray.map(o=>new Meet(o));
};
function getAllMeets(){
return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`)
.then(results=>Meet.fromObjArray(results.results));
}
function getUpcomingMeets(){
return MySql.query(`
SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.*
FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID
WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE()
`).then(results=>Meet.fromObjArray(results.results));
}
module.exports = {getAllMeets,getUpcomingMeets};
|
const MySql = require("./MySql.js");
const entities = require("entities");
class Meet{
constructor(obj){
Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k]));
}
asMarkdown(){
return `[${this.post_title}](${this.guid}) _${this.meet_start_time}_`;
}
}
Meet.fromObjArray = function(objArray){
return objArray.map(o=>new Meet(o));
};
function getAllMeets(){
return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`)
.then(results=>Meet.fromObjArray(results.results));
}
function getUpcomingMeets(){
return MySql.query(`
SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.*
FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID
WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE()
`).then(results=>Meet.fromObjArray(results.results));
}
module.exports = {getAllMeets,getUpcomingMeets};
|
Update the version number in preparation for release.
|
from setuptools import setup, find_packages
try:
import pypandoc
def long_description():
return pypandoc.convert_file('README.md', 'rst')
except ImportError:
def long_description():
return ''
setup(
name='rq-retry-scheduler',
version='0.1.1b1',
url='https://github.com/mikemill/rq_retry_scheduler',
description='RQ Retry and Scheduler',
long_description=long_description(),
author='Michael Miller',
author_email='mikemill@gmail.com',
packages=find_packages(exclude=['*tests*']),
license='MIT',
install_requires=['rq>=0.6.0'],
zip_safe=False,
platforms='any',
entry_points={
'console_scripts': [
'rqscheduler = rq_retry_scheduler.cli:main',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
]
)
|
from setuptools import setup, find_packages
try:
import pypandoc
def long_description():
return pypandoc.convert_file('README.md', 'rst')
except ImportError:
def long_description():
return ''
setup(
name='rq-retry-scheduler',
version='0.1.0b6',
url='https://github.com/mikemill/rq_retry_scheduler',
description='RQ Retry and Scheduler',
long_description=long_description(),
author='Michael Miller',
author_email='mikemill@gmail.com',
packages=find_packages(exclude=['*tests*']),
license='MIT',
install_requires=['rq>=0.6.0'],
zip_safe=False,
platforms='any',
entry_points={
'console_scripts': [
'rqscheduler = rq_retry_scheduler.cli:main',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
]
)
|
Change title to 'Popular Posts'
|
<?php
class com_meego_planet_controllers_top
{
public function __construct(midgardmvc_core_request $request)
{
$this->request = $request;
}
public function get_items(array $args)
{
$this->data['title'] = 'MeeGo Planet: Popular Posts';
midgardmvc_core::get_instance()->head->set_title($this->data['title']);
// FIXME: Query for top items instead
$q = new midgard_query_select
(
new midgard_query_storage('com_meego_planet_item')
);
$q->add_order(new midgard_query_property('metadata.score'), SORT_DESC);
$q->execute();
$this->data['items'] = array_map
(
function($item)
{
// TODO: Get author and avatar
return $item;
},
$q->list_objects()
);
}
}
|
<?php
class com_meego_planet_controllers_top
{
public function __construct(midgardmvc_core_request $request)
{
$this->request = $request;
}
public function get_items(array $args)
{
$this->data['title'] = 'MeeGo Planet: Top Voted Posts';
midgardmvc_core::get_instance()->head->set_title($this->data['title']);
// FIXME: Query for top items instead
$q = new midgard_query_select
(
new midgard_query_storage('com_meego_planet_item')
);
$q->add_order(new midgard_query_property('metadata.score'), SORT_DESC);
$q->execute();
$this->data['items'] = array_map
(
function($item)
{
// TODO: Get author and avatar
return $item;
},
$q->list_objects()
);
}
}
|
Add end_time as editable on the slot list view to make tweaking times easier
|
from django.contrib import admin
from django import forms
from wafer.schedule.models import Venue, Slot, ScheduleItem
from wafer.talks.models import Talk, ACCEPTED
class ScheduleItemAdminForm(forms.ModelForm):
class Meta:
model = ScheduleItem
def __init__(self, *args, **kwargs):
super(ScheduleItemAdminForm, self).__init__(*args, **kwargs)
self.fields['talk'].queryset = Talk.objects.filter(status=ACCEPTED)
class ScheduleItemAdmin(admin.ModelAdmin):
form = ScheduleItemAdminForm
change_list_template = 'admin/scheduleitem_list.html'
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
return super(ScheduleItemAdmin, self).changelist_view(request,
extra_context)
class SlotAdminForm(forms.ModelForm):
class Meta:
model = Slot
class Media:
js = ('js/scheduledatetime.js',)
class SlotAdmin(admin.ModelAdmin):
form = SlotAdminForm
list_display = ('__unicode__', 'end_time')
list_editable = ('end_time',)
admin.site.register(Slot, SlotAdmin)
admin.site.register(Venue)
admin.site.register(ScheduleItem, ScheduleItemAdmin)
|
from django.contrib import admin
from django import forms
from wafer.schedule.models import Venue, Slot, ScheduleItem
from wafer.talks.models import Talk, ACCEPTED
class ScheduleItemAdminForm(forms.ModelForm):
class Meta:
model = ScheduleItem
def __init__(self, *args, **kwargs):
super(ScheduleItemAdminForm, self).__init__(*args, **kwargs)
self.fields['talk'].queryset = Talk.objects.filter(status=ACCEPTED)
class ScheduleItemAdmin(admin.ModelAdmin):
form = ScheduleItemAdminForm
change_list_template = 'admin/scheduleitem_list.html'
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
return super(ScheduleItemAdmin, self).changelist_view(request,
extra_context)
class SlotAdminForm(forms.ModelForm):
class Meta:
model = Slot
class Media:
js = ('js/scheduledatetime.js',)
class SlotAdmin(admin.ModelAdmin):
form = SlotAdminForm
admin.site.register(Slot, SlotAdmin)
admin.site.register(Venue)
admin.site.register(ScheduleItem, ScheduleItemAdmin)
|
Use pypandoc to convert README from md to rst
|
from parsable import parsable
from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='treecat',
version='0.0.1',
description='A tree-of-mixtures nonparametric Bayesian model',
long_description=long_description,
author='Fritz Obermeyer',
author_email='fritz.obermeyer@gmail.com',
packages=['treecat'],
entry_points=parsable.find_entry_points('treecat'),
install_requires=['numpy', 'six', 'parsable'],
extras_require={
'tensorflow': ['tensorflow>=1.1.0'],
'tensorflow with gpu': ['tensorflow-gpu>=1.1.0']
},
tests_require=['pytest', 'flake8', 'goftests'],
license='Apache License 2.0')
|
from parsable import parsable
from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='treecat',
version='0.0.1',
description='A tree-of-mixtures nonparametric Bayesian model',
long_description=long_description,
author='Fritz Obermeyer',
author_email='fritz.obermeyer@gmail.com',
packages=['treecat'],
entry_points=parsable.find_entry_points('treecat'),
install_requires=['numpy', 'six', 'parsable'],
extras_require={
'tensorflow': ['tensorflow>=1.1.0'],
'tensorflow with gpu': ['tensorflow-gpu>=1.1.0']
},
tests_require=['pytest', 'flake8', 'goftests'],
license='Apache License 2.0')
|
BAP-11787: Update monolog/monolog package version at least to 1.17
- added todo about upgrade akeneo batch bundle
|
<?php
namespace Oro\Bundle\BatchBundle\Monolog\Handler;
use Akeneo\Bundle\BatchBundle\Monolog\Handler\BatchLogHandler as AkeneoBatchLogHandler;
use Monolog\Logger;
/**
* Write the log into a separate log file
*/
class BatchLogHandler extends AkeneoBatchLogHandler
{
/** @var bool */
protected $isActive = false;
/**
* {@inheritDoc}
*
* todo: Remove after update AkeneoBatchBundle to version without call of Monolog\Handler\StreamHandler constructor
*/
public function __construct($logDir)
{
$this->logDir = $logDir;
$this->filePermission = null;
$this->useLocking = false;
$this->setLevel(Logger::DEBUG);
$this->bubble = true;
}
/**
* @param boolean $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @return boolean
*/
public function isActive()
{
return $this->isActive;
}
/**
* {@inheritdoc}
*/
public function write(array $record)
{
if ($this->isActive()) {
parent::write($record);
}
}
}
|
<?php
namespace Oro\Bundle\BatchBundle\Monolog\Handler;
use Akeneo\Bundle\BatchBundle\Monolog\Handler\BatchLogHandler as AkeneoBatchLogHandler;
use Monolog\Logger;
/**
* Write the log into a separate log file
*/
class BatchLogHandler extends AkeneoBatchLogHandler
{
/** @var bool */
protected $isActive = false;
/**
* {@inheritDoc}
*/
public function __construct($logDir)
{
$this->logDir = $logDir;
$this->filePermission = null;
$this->useLocking = false;
$this->setLevel(Logger::DEBUG);
$this->bubble = true;
}
/**
* @param boolean $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @return boolean
*/
public function isActive()
{
return $this->isActive;
}
/**
* {@inheritdoc}
*/
public function write(array $record)
{
if ($this->isActive()) {
parent::write($record);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.