text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix preflights for all rules | package ch.heigvd.quaris.config;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Fabien Salathe on 26.01.17.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {
/**
* Enable CORS
*
* @param request
* @param response
* @param filterChain
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
if (!request.getMethod().equals("OPTIONS")) {
filterChain.doFilter(request, response);
}
}
}
| package ch.heigvd.quaris.config;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Fabien Salathe on 26.01.17.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {
/**
* Enable CORS
*
* @param request
* @param response
* @param filterChain
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
filterChain.doFilter(request, response);
}
}
|
Fix minor issues in package class | package com.gitrekt.resort.model.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "resort.packages")
public class Package {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "price_per_person")
private double pricePerPerson;
public Package(String name, double pricePerPerson){
this.name = name;
this.pricePerPerson = pricePerPerson;
}
public String getName(){
return name;
}
//Returns the price rate per person for the package
public double getPricePerPerson(){
return pricePerPerson;
}
}
| package com.gitrekt.resort.model.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "resort.guest_packages")
//Class for a guest's package
public class Package {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "price_per_person")
private double pricePerPerson;
//The constructor for this class
public Package(String name, double pricePerPerson){
this.name = name;
this.pricePerPerson = pricePerPerson;
}
//Returns the name assocociated with the package
public String getName(){
return name;
}
//Returns the price rate per person for the package
public double getPricePerPerson(){
return pricePerPerson;
}
}
|
Fix a bug in the reducer | import moment from 'moment';
import getServerList from './../../utils/getServerList';
function getInitialState() {
return {
time: undefined,
servers: getServerList().map(server => Object.assign(server, {state: 'loading', delay: 0}))
};
}
export default function serverReducer(state = getInitialState(), action) {
switch (action.type) {
case "server.current.time":
return setCurrentTime(state);
case "server.online":
return modifyServerState(state, action, 'online');
case "server.offline":
return modifyServerState(state, action, 'offline');
default:
return state;
}
}
function setCurrentTime(state) {
return {
...state,
time: moment().unix()
};
}
function modifyServerState(state, {server, responseTime}, newStateValue) {
return {
...state,
servers: state.servers.map(stateServer => {
if (server.name === stateServer.name) {
return {
...stateServer,
state: newStateValue,
delay: moment().unix() - state.time
};
}
return stateServer;
})
};
}
| import moment from 'moment';
import getServerList from './../../utils/getServerList';
function getInitialState() {
return {
time: undefined,
servers: getServerList().map(server => Object.assign(server, {state: 'loading', delay: 0}))
};
}
export default function serverReducer(state = getInitialState(), action) {
switch (action.type) {
case "server.current.time":
return setCurrentTime(state);
case "server.online":
return modifyServerState(state, action, 'online');
case "server.offline":
return modifyServerState(state, action, 'offline');
default:
return state;
}
}
function setCurrentTime(state) {
return {
...state,
time: moment().unix()
};
}
function modifyServerState(state, {server, responseTime}, newStateValue) {
return {
...state,
servers: state.servers.map(server => {
if (server.name === server.name) {
server.state = newStateValue;
server.delay = moment().unix() - state.time;
}
return server;
})
};
}
|
Fix wrong namespace for unit test | <?php
declare(strict_types=1);
namespace SignatureTest\Hasher;
use Signature\Hasher\Md5Hasher;
/**
* Tests for {@see Signature\Hasher\Md5Hasher}.
*
* @group Unitary
* @author Jefersson Nathan <malukenho@phpse.net>
* @license MIT
*
* @covers \Signature\Hasher\Md5Hasher
*/
final class Md5HasherTest extends \PHPUnit_Framework_TestCase
{
public function testHash()
{
$hasher = new Md5Hasher();
self::assertSame('40cd750bba9870f18aada2478b24840a', $hasher->hash([]));
self::assertSame('38017a839aaeb8ff1a658fce9af6edd3', $hasher->hash([null]));
self::assertSame('262bbc0aa0dc62a93e350f1f7df792b9', $hasher->hash([1, 2, 3]));
self::assertSame('aa565c66cb423c77379a37dd2d17bb2b', $hasher->hash(['params' => ['one' => [], 'two' => 123]]));
}
}
| <?php
declare(strict_types=1);
namespace unit\src\Hasher;
use Signature\Hasher\Md5Hasher;
/**
* Tests for {@see Signature\Hasher\Md5Hasher}.
*
* @group Unitary
* @author Jefersson Nathan <malukenho@phpse.net>
* @license MIT
*
* @covers \Signature\Hasher\Md5Hasher
*/
final class Md5HasherTest extends \PHPUnit_Framework_TestCase
{
public function testHash()
{
$hasher = new Md5Hasher();
self::assertSame('40cd750bba9870f18aada2478b24840a', $hasher->hash([]));
self::assertSame('38017a839aaeb8ff1a658fce9af6edd3', $hasher->hash([null]));
self::assertSame('262bbc0aa0dc62a93e350f1f7df792b9', $hasher->hash([1, 2, 3]));
self::assertSame('aa565c66cb423c77379a37dd2d17bb2b', $hasher->hash(['params' => ['one' => [], 'two' => 123]]));
}
}
|
Support fabrik internal services with the postfix
The fabrik internal services have the postfix -fabrik-internal | 'use strict';
const _ = require('lodash');
const config = require('../config');
const errors = require('../errors');
const Service = require('./Service');
const ServiceNotFound = errors.ServiceNotFound;
const ServicePlanNotFound = errors.ServicePlanNotFound;
class Catalog {
constructor() {
this.services = _.map(config.services, service => new Service(service));
this.plans = _.flatMap(this.services, service => service.plans);
}
getPlan(id) {
const plan = _.find(this.plans, plan => plan.id === id);
if (!plan) {
throw new ServicePlanNotFound(id);
}
return plan;
}
getService(id) {
const service = _.find(this.services, ['id', id]);
if (!service) {
throw new ServiceNotFound(id);
}
return service;
}
toJSON() {
return {
services: _.filter(this.services, service => service.name.indexOf('-fabrik-internal') === -1)
};
}
}
module.exports = new Catalog(); | 'use strict';
const _ = require('lodash');
const config = require('../config');
const errors = require('../errors');
const Service = require('./Service');
const ServiceNotFound = errors.ServiceNotFound;
const ServicePlanNotFound = errors.ServicePlanNotFound;
class Catalog {
constructor() {
this.services = _.map(config.services, service => new Service(service));
this.plans = _.flatMap(this.services, service => service.plans);
}
getPlan(id) {
const plan = _.find(this.plans, plan => plan.id === id);
if (!plan) {
throw new ServicePlanNotFound(id);
}
return plan;
}
getService(id) {
const service = _.find(this.services, ['id', id]);
if (!service) {
throw new ServiceNotFound(id);
}
return service;
}
toJSON() {
return {
services: this.services
};
}
}
module.exports = new Catalog(); |
Update router to default to slide control | /* jslint node: true */
'use strict';
var AUTHORIZED_URLS = [
'/index.html'
];
var HOST = '0.0.0.0';
var PORT = 9917;
function handleIo(socket) {
socket.on('slide-update', function(msg) {
socket.broadcast.emit("slide-update", msg);
});
}
function handleHTTP(req, res) {
var path = url.parse(req.url).pathname;
switch(path) {
case '/':
fs.readFile(__dirname + '/index.html', function(error, data) {
if (error) {
res.writeHeader(404);
res.end('foo oops, this doesn\'t exist - 404');
} else {
res.writeHeader(200, {'Content-Type': 'text/html'});
res.end(data, 'utf8');
}
});
break;
default:
res.writeHeader(404);
res.end('oops, this doesn\'t exist - 404');
break;
}
}
var http = require('http');
var url = require('url');
var fs = require('fs');
var server = http.createServer(handleHTTP);
server.listen(PORT, HOST);
var io = require('socket.io')(server);
io.on('connection', handleIo);
| /* jslint node: true */
'use strict';
var AUTHORIZED_URLS = [
'/index.html'
];
var HOST = '0.0.0.0';
var PORT = 9917;
function handleIo(socket) {
socket.on('slide-update', function(msg) {
socket.broadcast.emit("slide-update", msg);
});
}
function handleHTTP(req, res) {
var path = url.parse(req.url).pathname;
switch(path) {
case '/':
res.writeHeader(200, {'Content-Type': 'text/html'});
res.end('Hello');
break;
case '/index.html':
fs.readFile(__dirname + path, function(error, data) {
if (error) {
res.writeHeader(404);
res.end('foo oops, this doesn\'t exist - 404');
} else {
res.writeHeader(200, {'Content-Type': 'text/html'});
res.end(data, 'utf8');
}
});
break;
default:
res.writeHeader(404);
res.end('oops, this doesn\'t exist - 404');
break;
}
}
var http = require('http');
var url = require('url');
var fs = require('fs');
var server = http.createServer(handleHTTP);
server.listen(PORT, HOST);
var io = require('socket.io')(server);
io.on('connection', handleIo);
|
Return project ordered by date | import sys
from flask import Flask, render_template
from flask_flatpages import FlatPages, flatpages
from flask_frozen import Freezer
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FREEZER_DESTINATION = 'dist'
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
freezer = Freezer(app)
@app.route('/')
@app.route('/bio/')
def index():
return render_template('bio.html', pages=pages)
@app.route('/portfolio/')
def portfolio():
projects = (p for p in pages if 'date' in p.meta)
projects = sorted(projects, reverse=True, key=lambda p: p.meta['date'])
return render_template('portfolio.html', pages=projects)
@app.route('/portfolio/<path:path>/')
def page(path):
page = pages.get_or_404(path)
return render_template('project.html', page=page)
@app.route('/contatti/')
def contatti():
page = pages.get_or_404("contatti")
return render_template('page.html', page=page)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == "build":
freezer.freeze()
else:
app.run(port=8080) | import sys
from flask import Flask, render_template
from flask_flatpages import FlatPages
from flask_frozen import Freezer
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FREEZER_DESTINATION = 'dist'
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
freezer = Freezer(app)
@app.route('/')
@app.route('/bio/')
def index():
return render_template('bio.html', pages=pages)
@app.route('/portfolio/')
def portfolio():
return render_template('portfolio.html', pages=pages)
@app.route('/portfolio/<path:path>/')
def page(path):
page = pages.get_or_404(path)
return render_template('page.html', page=page)
@app.route('/contatti/')
def contatti():
page = pages.get_or_404("contatti")
return render_template('page.html', page=page)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == "build":
freezer.freeze()
else:
app.run(port=8080)
|
Set quality precision at 2 digits and handle no weight case | /**
* Dataset page specific features
*/
(function($, swig){
"use strict";
var QUALITY_PRECISION = 2,
COW_URL = $('link[rel="cow"]').attr('href'),
COW_API_URL = COW_URL + '/api/1/datasets/{name}/ranking';
$(function() {
var name = $('meta[name="dataset-name"]').attr('content'),
url = COW_API_URL.replace('{name}', name);
// Fetch ranking
$.get(url, function(data) {
var weight = data.value.weight,
tpl = swig.compile($('#quality-template').text());
if (weight) {
$('#infos-list').append(tpl({
weight: weight.toFixed(QUALITY_PRECISION)
}));
}
});
});
}(window.jQuery, window.swig));
| /**
* Dataset page specific features
*/
(function($, swig){
"use strict";
var COW_URL = $('link[rel="cow"]').attr('href'),
COW_API_URL = COW_URL + '/api/1/datasets/{name}/ranking';
$(function() {
var name = $('meta[name="dataset-name"]').attr('content'),
url = COW_API_URL.replace('{name}', name);
// Fetch ranking
$.get(url, function(data) {
var weight = data.value.weight.toFixed(3),
tpl = swig.compile($('#quality-template').text());
$('#infos-list').append(tpl({ weight: weight}));
});
});
}(window.jQuery, window.swig));
|
Adjust game size to fit parent element | import 'pixi';
import 'p2';
import Phaser from 'phaser';
import BootState from './states/Boot';
import SplashState from './states/Splash';
import GameState from './states/Game';
import config from './config';
class Game extends Phaser.Game {
constructor () {
const parentEl = document.getElementById('game-target');
let width, height;
if (parentEl.clientWidth > config.gameWidth) {
// parent element has plenty of room for game
width = config.gameWidth;
height = config.gameHeight;
} else {
// can't fit game into parent element
width = parentEl.clientWidth - 25;
// make height half screen size to make room for other ui
height = window.innerHeight / 2;
}
const gameConfig = {
width,
height,
renderer: Phaser.AUTO,
parent: 'game-target',
state: null,
antialias: false,
enableDebug: false,
};
super(gameConfig);
this.state.add('Boot', BootState, false);
this.state.add('Splash', SplashState, false);
this.state.add('Game', GameState, false);
this.state.start('Boot');
}
}
window.game = new Game();
| import 'pixi';
import 'p2';
import Phaser from 'phaser';
import BootState from './states/Boot';
import SplashState from './states/Splash';
import GameState from './states/Game';
import config from './config';
class Game extends Phaser.Game {
constructor () {
const docElement = document.documentElement;
const width = docElement.clientWidth > config.gameWidth ? config.gameWidth : docElement.clientWidth;
const height = docElement.clientHeight > config.gameHeight ? config.gameHeight : docElement.clientHeight;
const gameConfig = {
width,
height,
renderer: Phaser.AUTO,
parent: 'game-target',
state: null,
antialias: false,
enableDebug: false,
};
super(gameConfig);
this.state.add('Boot', BootState, false);
this.state.add('Splash', SplashState, false);
this.state.add('Game', GameState, false);
this.state.start('Boot');
}
}
window.game = new Game();
|
Add ability to get SHA256 on bytes | /*
* matrix-java-sdk - Matrix Client SDK for Java
* Copyright (C) 2017 Maxime Dor
*
* https://max.kamax.io/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.kamax.matrix.codec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MxSha256 {
private MessageDigest md;
public MxSha256() {
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public String hash(byte[] data) {
return MxBase64.encode(md.digest(data));
}
public String hash(String data) {
return hash(data.getBytes(StandardCharsets.UTF_8));
}
}
| /*
* matrix-java-sdk - Matrix Client SDK for Java
* Copyright (C) 2017 Maxime Dor
*
* https://max.kamax.io/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.kamax.matrix.codec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MxSha256 {
private MessageDigest md;
public MxSha256() {
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public String hash(String data) {
return MxBase64.encode(md.digest(data.getBytes(StandardCharsets.UTF_8)));
}
}
|
Undo using gopkg.in for examples. | package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/wolfeidau/go-buildkite/buildkite"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
apiToken = kingpin.Flag("token", "API token").Required().String()
org = kingpin.Flag("org", "Orginization slug").Required().String()
debug = kingpin.Flag("debug", "Enable debugging").Bool()
)
func main() {
kingpin.Parse()
config, err := buildkite.NewTokenConfig(*apiToken, *debug)
if err != nil {
log.Fatalf("client config failed: %s", err)
}
client := buildkite.NewClient(config.Client())
projects, _, err := client.Projects.List(*org, nil)
if err != nil {
log.Fatalf("list projects failed: %s", err)
}
data, err := json.MarshalIndent(projects, "", "\t")
if err != nil {
log.Fatalf("json encode failed: %s", err)
}
fmt.Fprintf(os.Stdout, "%s", string(data))
}
| package main
import (
"encoding/json"
"fmt"
"log"
"os"
"gopkg.in/wolfeidau/go-buildkite.v1"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
apiToken = kingpin.Flag("token", "API token").Required().String()
org = kingpin.Flag("org", "Orginization slug").Required().String()
debug = kingpin.Flag("debug", "Enable debugging").Bool()
)
func main() {
kingpin.Parse()
config, err := buildkite.NewTokenConfig(*apiToken, *debug)
if err != nil {
log.Fatalf("client config failed: %s", err)
}
client := buildkite.NewClient(config.Client())
projects, _, err := client.Projects.List(*org, nil)
if err != nil {
log.Fatalf("list projects failed: %s", err)
}
data, err := json.MarshalIndent(projects, "", "\t")
if err != nil {
log.Fatalf("json encode failed: %s", err)
}
fmt.Fprintf(os.Stdout, "%s", string(data))
}
|
Add key to sidebar links | // @flow
import React, { Component } from 'react'
import { Link } from 'react-router'
import s from './Sidebar.scss'
export default class Sidebar extends Component {
constructor (props) {
super(props)
this.state = {
links: [
{ text: 'Dashboard', to: '/admin/dashboard' },
{ text: 'Entries', to: '/admin/entries' },
{ text: 'Globals', to: '/admin/globals' },
{ text: 'Categories', to: '/admin/categories' },
{ text: 'Assets', to: '/admin/assets' },
{ text: 'Settings', to: '/admin/settings' }
]
}
}
renderLink (link, index) {
return (
<li key={index}>
<Link className={s.link}
activeClassName={s.activeLink}
to={link.to}>
{link.text}
</Link>
</li>
)
}
render () {
return (
<header className={s.root}>
<nav className={s.nav}>
<ul>
{this.state.links.map(this.renderLink)}
</ul>
</nav>
</header>
)
}
}
| // @flow
import React, { Component } from 'react'
import { Link } from 'react-router'
import s from './Sidebar.scss'
export default class Sidebar extends Component {
constructor (props) {
super(props)
this.state = {
links: [
{ text: 'Dashboard', to: '/admin/dashboard' },
{ text: 'Entries', to: '/admin/entries' },
{ text: 'Globals', to: '/admin/globals' },
{ text: 'Categories', to: '/admin/categories' },
{ text: 'Assets', to: '/admin/assets' },
{ text: 'Settings', to: '/admin/settings' }
]
}
}
renderLink (link) {
return (
<li>
<Link className={s.link}
activeClassName={s.activeLink}
to={link.to}>
{link.text}
</Link>
</li>
)
}
render () {
return (
<header className={s.root}>
<nav className={s.nav}>
<ul>
{this.state.links.map(this.renderLink)}
</ul>
</nav>
</header>
)
}
}
|
Revert "corrected database settings merge again"
This reverts commit 8d04d1c731aaed33c586993002f5e713c3fa1408. | from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydata',
'USER': 'postgreuser',
'PASSWORD': 'postgre',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
| from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacs',
'USER': 'timetable',
'PASSWORD': 'thereisn0sp00n',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
|
Allow other characters in placeholder name | from django.template import loader, Context, TemplateDoesNotExist
from django.template.loader_tags import ExtendsNode
from cms.utils import get_template_from_request
import re
# must be imported like this for isinstance
from django.templatetags.cms_tags import PlaceholderNode #do not remove
def get_placeholders(request, template_name):
"""
Return a list of PlaceholderNode found in the given template
"""
try:
temp = loader.get_template(template_name)
except TemplateDoesNotExist:
return []
context = Context()#RequestContext(request)#details(request, no404=True, only_context=True)
template = get_template_from_request(request)
request.current_page = "dummy"
context.update({'template':template,
'request':request,
'display_placeholder_names_only': True,
})
# lacks - it requests context in admin and eats user messages,
# standard context will be hopefully enough here
# temp.render(RequestContext(request, context))
output = temp.render(context)
return re.findall("<!-- PlaceholderNode: (.*?) -->", output)
| from django.template import loader, Context, TemplateDoesNotExist
from django.template.loader_tags import ExtendsNode
from cms.utils import get_template_from_request
import re
# must be imported like this for isinstance
from django.templatetags.cms_tags import PlaceholderNode #do not remove
def get_placeholders(request, template_name):
"""
Return a list of PlaceholderNode found in the given template
"""
try:
temp = loader.get_template(template_name)
except TemplateDoesNotExist:
return []
context = Context()#RequestContext(request)#details(request, no404=True, only_context=True)
template = get_template_from_request(request)
request.current_page = "dummy"
context.update({'template':template,
'request':request,
'display_placeholder_names_only': True,
})
# lacks - it requests context in admin and eats user messages,
# standard context will be hopefully enough here
# temp.render(RequestContext(request, context))
output = temp.render(context)
return re.findall("<!-- PlaceholderNode: (\w+?) -->", output)
|
Update the pipeline to take into account the outlier rejection method to compute the RPP | import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
for file in files:
if file.endswith('.fit'):
filenames.append(os.path.join(root, file))
max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
# Open the file
power_ride = load_power_from_fit(filename)
# Reject the outliers using thresholding method
power_ride = denoise.outliers_rejection(power_ride)
# Fit the ride
rpp_rider.fit(power_ride)
# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
os.makedirs(storage_path)
# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
| import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
for file in files:
if file.endswith('.fit'):
filenames.append(os.path.join(root, file))
max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
# Open the file
power_ride = load_power_from_fit(filename)
# Fit the ride
rpp_rider.fit(power_ride)
# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
os.makedirs(storage_path)
# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
|
Remove the use of deprecated method | <?php
/**
* Este archivo contiene toda la logica de negocio asociada a la ropa que se le entrega
* a cada trabajador de una relacion laboral.
*
* PHP versions 5
*
* @filesource
* @copyright Copyright 2007-2009, Pragmatia
* @link http://www.pragmatia.com
* @package pragtico
* @subpackage app.controllers
* @since Pragtico v 1.0.0
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @author Martin Radosta <mradosta@pragmatia.com>
*/
/**
* La clase encapsula la logica de negocio asociada a la ropa que se le entrega
* a cada trabajador de una relacion laboral.
*
* @package pragtico
* @subpackage app.controllers
*/
class RopasController extends AppController {
/**
* Prendas.
* Muestra via desglose las prendas entregadas.
*/
function prendas($id) {
$this->Ropa->contain("RopasDetalle");
$this->data = $this->Ropa->read(null, $id);
}
}
?>
| <?php
/**
* Este archivo contiene toda la logica de negocio asociada a la ropa que se le entrega
* a cada trabajador de una relacion laboral.
*
* PHP versions 5
*
* @filesource
* @copyright Copyright 2007-2009, Pragmatia
* @link http://www.pragmatia.com
* @package pragtico
* @subpackage app.controllers
* @since Pragtico v 1.0.0
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @author Martin Radosta <mradosta@pragmatia.com>
*/
/**
* La clase encapsula la logica de negocio asociada a la ropa que se le entrega
* a cada trabajador de una relacion laboral.
*
* @package pragtico
* @subpackage app.controllers
*/
class RopasController extends AppController {
/**
* Prendas.
* Muestra via desglose las prendas entregadas.
*/
function prendas($id) {
$this->Ropa->contain("RopasDetalle");
$this->data = $this->Ropa->read(null, $id);
}
/**
* imprimirOrden.
* Genera una orden que el empleado pueda retirar la ropa.
*/
function imprimirOrden($id) {
$this->layout = 'pdf';
$this->data = $this->Ropa->read(null, $id);
}
}
?>
|
Remove serialize interface from raderror | <?php
/*
* The MIT License
*
* Copyright 2017 guillaume.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace Rad\Errors;
use ErrorException;
use JsonSerializable;
/**
* Description of DefaultError
*
* @author guillaume
*/
abstract class RadError extends ErrorException implements JsonSerializable {
public function __toString() {
return $this->message;
}
public function jsonSerialize() {
return json_encode((array) $this);
}
}
| <?php
/*
* The MIT License
*
* Copyright 2017 guillaume.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace Rad\Errors;
use ErrorException;
use JsonSerializable;
use Serializable;
/**
* Description of DefaultError
*
* @author guillaume
*/
abstract class RadError extends ErrorException implements JsonSerializable, Serializable {
public function __toString() {
return $this->message;
}
public function serialize(): string {
return null;
}
public function unserialize($serialized) {
}
public function jsonSerialize() {
return json_encode((array) $this);
}
}
|
Remove global reference intended only for debugging. | import { assert } from 'chai';
import ShadowTemplate from '../src/ShadowTemplate';
class MyElement extends HTMLElement {
greet() {
return `Hello!`;
}
}
customElements.define('my-element', MyElement);
/* Element with a simple template */
class ElementWithStringTemplate extends ShadowTemplate(HTMLElement) {
get template() {
return "Hello";
}
}
customElements.define('element-with-string-template', ElementWithStringTemplate);
/* Element with a real template */
let template = document.createElement('template');
template.content.textContent = "Hello";
class ElementWithRealTemplate extends ShadowTemplate(HTMLElement) {
get template() {
return template;
}
}
customElements.define('element-with-real-template', ElementWithRealTemplate);
describe("ShadowTemplate mixin", () => {
it("stamps string template into root", () => {
let element = document.createElement('element-with-string-template');
assert(element.shadowRoot);
assert.equal(element.shadowRoot.textContent.trim(), "Hello");
});
it("stamps real template into root", () => {
let element = document.createElement('element-with-real-template');
assert(element.shadowRoot);
assert.equal(element.shadowRoot.textContent.trim(), "Hello");
});
});
| import { assert } from 'chai';
import ShadowTemplate from '../src/ShadowTemplate';
window.MyElement = class MyElement extends HTMLElement {
greet() {
return `Hello!`;
}
};
customElements.define('my-element', MyElement);
/* Element with a simple template */
class ElementWithStringTemplate extends ShadowTemplate(HTMLElement) {
get template() {
return "Hello";
}
}
customElements.define('element-with-string-template', ElementWithStringTemplate);
/* Element with a real template */
let template = document.createElement('template');
template.content.textContent = "Hello";
class ElementWithRealTemplate extends ShadowTemplate(HTMLElement) {
get template() {
return template;
}
}
customElements.define('element-with-real-template', ElementWithRealTemplate);
describe("ShadowTemplate mixin", () => {
it("stamps string template into root", () => {
let element = document.createElement('element-with-string-template');
assert(element.shadowRoot);
assert.equal(element.shadowRoot.textContent.trim(), "Hello");
});
it("stamps real template into root", () => {
let element = document.createElement('element-with-real-template');
assert(element.shadowRoot);
assert.equal(element.shadowRoot.textContent.trim(), "Hello");
});
});
|
Mark HTML generated by custom template filter as safe if auto-escaping is enabled. | # -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from jinja2 import evalcontextfilter, Markup
from . import dateformat, money
@evalcontextfilter
def dim(eval_ctx, value):
"""Render value in a way so that it looks dimmed."""
dimmed = '<span class="dimmed">{}</span>'.format(value)
return Markup(dimmed) if eval_ctx.autoescape else dimmed
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
| # -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from . import dateformat, money
def dim(value):
"""Render value in a way so that it looks dimmed."""
return '<span class="dimmed">{}</span>'.format(value)
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
|
Add tests for parsing options | <?php
namespace DexBarrett\ClockworkSms\Test;
use DexBarrett\ClockworkSms\Client;
use DexBarrett\ClockworkSms\Exception\ClockworkSmsException;
class ClientTest extends \PHPUnit_Framework_TestCase
{
public function test_it_fails_if_no_apikey_is_provided()
{
$this->expectException(ClockworkSmsException::class);
$client = new Client();
}
public function test_it_overrides_provided_options()
{
$client = new Client('APIKEY', ['ssl' => true, 'log' => true]);
$this->assertEquals($client->getOptionValue('ssl'), true);
$this->assertEquals($client->getOptionValue('log'), true);
}
public function test_throws_error_when_trying_to_get_invalid_option()
{
$this->expectException(ClockworkSmsException::class);
$client = new Client('APIKEY');
$client->getOptionValue('foo');
}
public function test_ignores_invalid_options_provided()
{
$this->expectException(ClockworkSmsException::class);
$client = new Client('APIKEY', ['log' => true, 'foo' => 'bar']);
$client->getOptionValue('foo');
}
} | <?php
namespace DexBarrett\ClockworkSms\Test;
use DexBarrett\ClockworkSms\Client;
use DexBarrett\ClockworkSms\Exception\ClockworkSmsException;
class ClientTest extends \PHPUnit_Framework_TestCase
{
public function test_it_fails_if_no_apikey_is_provided()
{
$this->expectException(ClockworkSmsException::class);
$client = new Client();
}
public function test_it_parses_options()
{
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
public function test_throws_error_when_trying_to_get_invalid_option()
{
$this->expectException(ClockworkSmsException::class);
$client = new Client('APIKEY');
$client->getOptionValue('foo');
}
} |
Allow window size override on command line. | //
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.demo;
import java.util.List;
import com.google.common.collect.Lists;
import playn.core.PlayN;
import playn.java.JavaPlatform;
import tripleplay.platform.JavaTPPlatform;
public class TripleDemoJava
{
public static void main (String[] args) {
JavaPlatform.Config config = new JavaPlatform.Config();
List<String> mainArgs = Lists.newArrayList();
for (int ii = 0; ii < args.length; ii++) {
String size = "--size=";
if (args[ii].startsWith(size)) {
String[] wh = args[ii].substring(size.length()).split("x");
config.width = Integer.parseInt(wh[0]);
config.height = Integer.parseInt(wh[1]);
continue;
}
mainArgs.add(args[ii]);
}
JavaPlatform platform = JavaPlatform.register(config);
TripleDemo.mainArgs = mainArgs.toArray(new String[0]);
JavaTPPlatform.register(platform, config);
PlayN.run(new TripleDemo());
}
}
| //
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.demo;
import playn.core.PlayN;
import playn.java.JavaPlatform;
import tripleplay.platform.JavaTPPlatform;
public class TripleDemoJava
{
public static void main (String[] args) {
JavaPlatform.Config config = new JavaPlatform.Config();
JavaPlatform platform = JavaPlatform.register(config);
TripleDemo.mainArgs = args;
// TODO: upgrade to include other systems
if (System.getProperty("os.name").contains("Linux")) {
JavaTPPlatform.register(platform, config);
}
PlayN.run(new TripleDemo());
}
}
|
Enable statup_with_url.cold benchmark on android.
The benchmark works locally, and collects an important datapoint for our
current optimization work.
Review URL: https://codereview.chromium.org/508303004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#298526} | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from measurements import startup
import page_sets
from telemetry import benchmark
@benchmark.Enabled('android', 'has tabs')
class StartWithUrlCold(benchmark.Benchmark):
"""Measure time to start Chrome cold with startup URLs"""
tag = 'cold'
test = startup.StartWithUrl
page_set = page_sets.StartupPagesPageSet
options = {'cold': True,
'pageset_repeat': 5}
@benchmark.Enabled('android', 'has tabs')
class StartWithUrlWarm(benchmark.Benchmark):
"""Measure time to start Chrome warm with startup URLs"""
tag = 'warm'
test = startup.StartWithUrl
page_set = page_sets.StartupPagesPageSet
options = {'warm': True,
'pageset_repeat': 10}
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from measurements import startup
import page_sets
from telemetry import benchmark
@benchmark.Disabled
class StartWithUrlCold(benchmark.Benchmark):
"""Measure time to start Chrome cold with startup URLs"""
tag = 'cold'
test = startup.StartWithUrl
page_set = page_sets.StartupPagesPageSet
options = {'cold': True,
'pageset_repeat': 5}
@benchmark.Enabled('android', 'has tabs')
class StartWithUrlWarm(benchmark.Benchmark):
"""Measure time to start Chrome warm with startup URLs"""
tag = 'warm'
test = startup.StartWithUrl
page_set = page_sets.StartupPagesPageSet
options = {'warm': True,
'pageset_repeat': 10}
|
Use absolute path in mocha acceptance test blueprints | import { describe, it, beforeEach, afterEach } from 'mocha';
import { expect } from 'chai';
import startApp from '<%= dasherizedPackageName %>/helpers/start-app';
<% if (destroyAppExists) { %>import destroyApp from '<%= dasherizedPackageName %>/helpers/destroy-app';<% } else { %>import Ember from 'ember';<% } %>
describe('<%= friendlyTestName %>', function() {
let application;
beforeEach(function() {
application = startApp();
});
afterEach(function() {
<% if (destroyAppExists) { %>destroyApp(application);<% } else { %>Ember.run(application, 'destroy');<% } %>
});
it('can visit /<%= dasherizedModuleName %>', function() {
visit('/<%= dasherizedModuleName %>');
andThen(function() {
expect(currentURL()).to.equal('/<%= dasherizedModuleName %>');
});
});
});
| import { describe, it, beforeEach, afterEach } from 'mocha';
import { expect } from 'chai';
import startApp from '../helpers/start-app';
<% if (destroyAppExists) { %>import destroyApp from '../helpers/destroy-app';<% } else { %>import Ember from 'ember';<% } %>
describe('<%= friendlyTestName %>', function() {
let application;
beforeEach(function() {
application = startApp();
});
afterEach(function() {
<% if (destroyAppExists) { %>destroyApp(application);<% } else { %>Ember.run(application, 'destroy');<% } %>
});
it('can visit /<%= dasherizedModuleName %>', function() {
visit('/<%= dasherizedModuleName %>');
andThen(function() {
expect(currentURL()).to.equal('/<%= dasherizedModuleName %>');
});
});
});
|
Fix path to be cross-platform | package main
import (
"fmt"
"github.com/go-martini/martini"
"html/template"
"io/ioutil"
"net/http"
"os"
)
type Human struct {
Name string
Age string
}
func main() {
f, err := os.Open("src/html/SimpleTemplate.html")
defer f.Close()
if err != nil {
fmt.Println(err)
}
data, err := ioutil.ReadAll(f)
if err != nil {
fmt.Println(err)
}
//tmpl, err := template.New("test").Parse("Hello {{.Name}} aged {{.Age}}. Nice to meet you!!!")
tmpl, err := template.New("test").Parse(string(data))
if err != nil {
fmt.Println(err)
}
m := martini.Classic()
m.Get("/:name/:age", func(params martini.Params, res http.ResponseWriter, req *http.Request) {
testSubject := Human{params["name"], params["age"]}
err = tmpl.Execute(res, testSubject)
if err != nil {
fmt.Println(err)
}
})
m.Run()
}
| package main
import (
"fmt"
"github.com/go-martini/martini"
"html/template"
"io/ioutil"
"net/http"
"os"
)
type Human struct {
Name string
Age string
}
func main() {
f, err := os.Open("/home/user/GoCode/src/html/SimpleTemplate.html")
defer f.Close()
if err != nil {
fmt.Println(err)
}
data, err := ioutil.ReadAll(f)
if err != nil {
fmt.Println(err)
}
//tmpl, err := template.New("test").Parse("Hello {{.Name}} aged {{.Age}}. Nice to meet you!!!")
tmpl, err := template.New("test").Parse(string(data))
if err != nil {
fmt.Println(err)
}
m := martini.Classic()
m.Get("/:name/:age", func(params martini.Params, res http.ResponseWriter, req *http.Request) {
testSubject := Human{params["name"], params["age"]}
err = tmpl.Execute(res, testSubject)
if err != nil {
fmt.Println(err)
}
})
m.Run()
}
|
Make diagnostics warning color more visible | angular.module("app").controller("DiagnosticsDialogController",
function($scope, $mdDialog, roslib) {
var OK = 0;
var WARN = 1;
var ERROR = 2;
var STALE = 3;
var diagnostics_callback = function(diagnostics) {
$scope.diagnostics = diagnostics;
console.log(diagnostics);
};
var diagnostics_sub = roslib.subscribe("/diagnostics_agg", "diagnostic_msgs/DiagnosticArray", diagnostics_callback);
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
$scope.statusLevelToColor = function(level) {
if(level === OK) {
return "green";
}
else if(level === WARN) {
return "orange";
}
else if(level === STALE) {
return "blue";
}
else {
return "red";
}
};
$scope.statusLevelToSymbol = function(level) {
if(level === OK) {
return "\u2714";
}
else if(level === WARN) {
return "\u2757";
}
else if(level === STALE) {
return "\u2753";
}
else {
return "\u2716";
}
};
});
| angular.module("app").controller("DiagnosticsDialogController",
function($scope, $mdDialog, roslib) {
var OK = 0;
var WARN = 1;
var ERROR = 2;
var STALE = 3;
var diagnostics_callback = function(diagnostics) {
$scope.diagnostics = diagnostics;
console.log(diagnostics);
};
var diagnostics_sub = roslib.subscribe("/diagnostics_agg", "diagnostic_msgs/DiagnosticArray", diagnostics_callback);
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
$scope.statusLevelToColor = function(level) {
if(level === OK) {
return "green";
}
else if(level === WARN) {
return "yellow";
}
else if(level === STALE) {
return "blue";
}
else {
return "red";
}
};
$scope.statusLevelToSymbol = function(level) {
if(level === OK) {
return "\u2714";
}
else if(level === WARN) {
return "\u2757";
}
else if(level === STALE) {
return "\u2753";
}
else {
return "\u2716";
}
};
});
|
Print usage if argument count != 1 | package at.fhtw.mcs;
import java.util.Scanner;
import at.fhtw.mcs.model.Track;
import at.fhtw.mcs.model.TrackFactory;
class Main {
public static void main(String[] args) throws InterruptedException {
if (args.length != 1) {
System.err.println("Usage: ./mcs AUDIO_FILE");
}
String filename = args[0];
System.out.println("Loading " + filename);
Track track = TrackFactory.loadTrack(filename);
track.play();
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
switch (scanner.nextLine()) {
case "p":
track.togglePlayPause();
break;
case "s":
track.stop();
break;
case "q":
return;
}
}
}
}
}
| package at.fhtw.mcs;
import java.util.Scanner;
import at.fhtw.mcs.model.Track;
import at.fhtw.mcs.model.TrackFactory;
class Main {
public static void main(String[] args) throws InterruptedException {
String filename = args[0];
System.out.println("Loading " + filename);
Track track = TrackFactory.loadTrack(filename);
track.play();
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
switch (scanner.nextLine()) {
case "p":
track.togglePlayPause();
break;
case "s":
track.stop();
break;
case "q":
return;
}
}
}
}
}
|
Reposition the graph while printing
Related to
https://github.com/gaearon/redux-devtools/issues/318#issuecomment-254039
542 | import React, { Component, PropTypes } from 'react';
import PrintIcon from 'react-icons/lib/md/print';
import Button from '../Button';
export default class PrintButton extends Component {
shouldComponentUpdate() {
return false;
}
handlePrint() {
const d3svg = document.getElementById('d3svg');
if (!d3svg) {
window.print();
return;
}
const initHeight = d3svg.style.height;
const initWidth = d3svg.style.width;
const box = d3svg.getBBox();
d3svg.style.height = box.height;
d3svg.style.width = box.width;
const g = d3svg.firstChild;
const initTransform = g.getAttribute('transform');
g.setAttribute('transform', initTransform.replace(/.+scale\(/, 'translate(57, 10) scale('));
window.print();
d3svg.style.height = initHeight;
d3svg.style.width = initWidth;
g.setAttribute('transform', initTransform);
}
render() {
return (
<Button Icon={PrintIcon} onClick={this.handlePrint}>Print</Button>
);
}
}
| import React, { Component, PropTypes } from 'react';
import PrintIcon from 'react-icons/lib/md/print';
import Button from '../Button';
export default class PrintButton extends Component {
shouldComponentUpdate() {
return false;
}
handlePrint() {
const d3svg = document.getElementById('d3svg');
if (!d3svg) {
window.print();
return;
}
const initHeight = d3svg.style.height;
const initWidth = d3svg.style.width;
const box = d3svg.getBBox();
d3svg.style.height = box.height;
d3svg.style.width = box.width;
window.print();
d3svg.style.height = initHeight;
d3svg.style.width = initWidth;
}
render() {
return (
<Button Icon={PrintIcon} onClick={this.handlePrint}>Print</Button>
);
}
}
|
Add test data to suppress warning. | /* eslint-env mocha */
import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import ReactDOM from 'react-dom'
import { IntlProvider } from 'react-intl'
import Genres from '../../src/frontend/components/Genres'
function setup (propOverrides) {
const props = {
genres: [
{ name: 'genre_1', key: 'relativeUri_1' },
{ name: 'genre_2', key: 'relativeUri_2' },
{ name: 'genre_3', key: 'relativeUri_3' }
], ...propOverrides
}
const output = TestUtils.renderIntoDocument(
<IntlProvider locale='en'>
<Genres {...props} />
</IntlProvider>
)
return {
props: props,
output: output,
node: ReactDOM.findDOMNode(output)
}
}
describe('components', () => {
describe('Genres', () => {
it('should render spans for every genre', () => {
const { node } = setup()
expect(node.querySelectorAll("[data-automation-id='work_genre']").length).toBe(3)
})
})
})
| /* eslint-env mocha */
import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import ReactDOM from 'react-dom'
import { IntlProvider } from 'react-intl'
import Genres from '../../src/frontend/components/Genres'
function setup (propOverrides) {
const props = {
genres: [
{ name: 'genre_1' }, { name: 'genre_2' }, { name: 'genre_3' }
], ...propOverrides
}
const output = TestUtils.renderIntoDocument(
<IntlProvider locale='en'>
<Genres {...props} />
</IntlProvider>
)
return {
props: props,
output: output,
node: ReactDOM.findDOMNode(output)
}
}
describe('components', () => {
describe('Genres', () => {
it('should render spans for every genre', () => {
const { node } = setup()
expect(node.querySelectorAll("[data-automation-id='work_genre']").length).toBe(3)
})
})
})
|
Fix a bug in updater config | #!/usr/bin/env node
'use strict';
var program = require('commander'),
colors = require('colors'),
pkg = require('./package.json'),
fs = require('fs');
program
.version(pkg.version)
.option('-t, --title [string]', 'specified the title')
.option('-c, --check', 'check if there are an update')
.parse(process.argv);
if (typeof program.title == 'undefined') {
console.log('Please set a title with -t.'.red);
program.title = 'Photos';
}
if (program.check) {
require('check-update')({packageName: pkg.name, packageVersion: pkg.version, isCLI: true}, function(err, latestVersion, defaultMessage){
if(!err){
console.log(defaultMessage);
}
});
}
require('./lib/template')(program.title, function(content){
var time = Date.now();
fs.writeFile(process.cwd() + '/' + time + '.html', content, function (err) {
if (err) {
console.log('There was an error.'.red);
process.exit(1);
}
console.log(colors.green('Done! Generated in ' + time + '.html'));
});
}); | #!/usr/bin/env node
'use strict';
var program = require('commander'),
colors = require('colors'),
pkg = require('./package.json'),
fs = require('fs');
program
.version(pkg.version)
.option('-t, --title [string]', 'specified the title')
.option('-c, --check', 'check if there are an update')
.parse(process.argv);
if (typeof program.title == 'undefined') {
console.log('Please set a title with -t.'.red);
program.title = 'Photos';
}
if (program.check) {
require('check-update')({packageName: 'check-update-tester', packageVersion: pkg.version, isCLI: true}, function(err, latestVersion, defaultMessage){
if(!err){
console.log(defaultMessage);
}
});
}
require('./lib/template')(program.title, function(content){
var time = Date.now();
fs.writeFile(process.cwd() + '/' + time + '.html', content, function (err) {
if (err) {
console.log('There was an error.'.red);
process.exit(1);
}
console.log(colors.green('Done! Generated in ' + time + '.html'));
});
}); |
Update PR regarding hook accepted by Odoo | # -*- coding: utf-8 -*-
# © 2016 Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import api, models
class StockChangeProductQty(models.TransientModel):
_inherit = "stock.change.product.qty"
@api.model
def _prepare_inventory_line(self, inventory_id, data):
line_data = super(StockChangeProductQty,
self)._prepare_inventory_line(inventory_id, data)
Company = self.env['res.company']
location = data.location_id
line_data['partner_id'] = (
location.partner_id.id or
location.company_id.partner_id.id or
Company.browse(
Company._company_default_get('stock.quant')
).partner_id.id
)
return line_data
| # -*- coding: utf-8 -*-
# © 2016 Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import api, models
class StockChangeProductQty(models.TransientModel):
_inherit = "stock.change.product.qty"
@api.model
def _finalize_inventory_line(self, data):
line_data = super(StockChangeProductQty,
self)._finalize_inventory_line(data)
Company = self.env['res.company']
location = data.location_id
line_data['partner_id'] = (
location.partner_id.id or
location.company_id.partner_id.id or
Company.browse(
Company._company_default_get('stock.quant')
).partner_id.id
)
return line_data
|
Add missing implementation in `UserFollowUserNotificationObject`
Fixes 82ba990ddcd929e45c952a312340f86a56eecb19 | <?php
namespace wcf\system\user\notification\object;
use wcf\data\user\follow\UserFollow;
use wcf\data\DatabaseObjectDecorator;
/**
* Represents a following user as a notification object.
*
* @author Alexander Ebert
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\User\Notification\Object
*
* @method UserFollow getDecoratedObject()
* @mixin UserFollow
*/
class UserFollowUserNotificationObject extends DatabaseObjectDecorator implements IUserNotificationObject {
/**
* @inheritDoc
*/
protected static $baseClass = UserFollow::class;
/**
* @inheritDoc
*/
public function getTitle() {
return '';
}
/**
* @inheritDoc
*/
public function getURL() {
return '';
}
/**
* @inheritDoc
*/
public function getAuthorID() {
return $this->userID;
}
}
| <?php
namespace wcf\system\user\notification\object;
use wcf\data\user\follow\UserFollow;
use wcf\data\DatabaseObjectDecorator;
/**
* Represents a following user as a notification object.
*
* @author Alexander Ebert
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\User\Notification\Object
*
* @method UserFollow getDecoratedObject()
* @mixin UserFollow
*/
class UserFollowUserNotificationObject extends DatabaseObjectDecorator {
/**
* @inheritDoc
*/
protected static $baseClass = UserFollow::class;
/**
* @inheritDoc
*/
public function getTitle() {
return '';
}
/**
* @inheritDoc
*/
public function getURL() {
return '';
}
/**
* @inheritDoc
*/
public function getAuthorID() {
return $this->userID;
}
}
|
Copy core .htaccess file to dist | var gulp = require('gulp');
var clean = require('gulp-clean');
var zip = require('gulp-zip');
var bases = {
root: 'dist/'
};
var paths = [
'core/actions/*',
'core/common/**',
'admin/**',
'!admin/config/*',
'boxoffice/**',
'!boxoffice/config/*',
'customer/**',
'!customer/config/*',
'scanner/**',
'!scanner/config/*',
'printer/**',
'!printer/config/*',
'core/model/*',
'core/services/*',
'vendor/**',
'composer.lock',
'core/dependencies.php',
'core/.htaccess'
];
gulp.task('clean', function() {
return gulp.src(bases.root)
.pipe(clean({}));
});
gulp.task('collect', function() {
return gulp.src(paths, { base: './', dot: true })
.pipe(gulp.dest(bases.root));
});
gulp.task('zip', function() {
return gulp.src(bases.root + '**')
.pipe(zip('ticketbox-server-php.zip'))
.pipe(gulp.dest(bases.root));
});
gulp.task('default', gulp.series('clean', 'collect', 'zip'));
| var gulp = require('gulp');
var clean = require('gulp-clean');
var zip = require('gulp-zip');
var bases = {
root: 'dist/'
};
var paths = [
'core/actions/*',
'core/common/**',
'admin/**',
'!admin/config/*',
'boxoffice/**',
'!boxoffice/config/*',
'customer/**',
'!customer/config/*',
'scanner/**',
'!scanner/config/*',
'printer/**',
'!printer/config/*',
'core/model/*',
'core/services/*',
'vendor/**',
'composer.lock',
'core/dependencies.php'
];
gulp.task('clean', function() {
return gulp.src(bases.root)
.pipe(clean({}));
});
gulp.task('collect', function() {
return gulp.src(paths, { base: './', dot: true })
.pipe(gulp.dest(bases.root));
});
gulp.task('zip', function() {
return gulp.src(bases.root + '**')
.pipe(zip('ticketbox-server-php.zip'))
.pipe(gulp.dest(bases.root));
});
gulp.task('default', gulp.series('clean', 'collect', 'zip'));
|
Fix deprecation message from zend-mvc 2.7 | <?php
namespace Zf1Module\Controller;
use Zend\Mvc\Controller\AbstractController;
use Zend\Mvc\MvcEvent;
class DispatchController extends AbstractController
{
/**
* Execute the request
*
* @param \Zend\Mvc\MvcEvent $event
* @return \Zend_Controller_Response_Abstract|null
*/
public function onDispatch(MvcEvent $event)
{
/** @var $bootstrap \Zend_Application_Bootstrap_Bootstrap */
$bootstrap = $event->getApplication()->getServiceManager()->get('Zf1Module\Application')->getBootstrap();
$bootstrap->bootstrap();
/** @var $front \Zend_Controller_Front */
$front = $bootstrap->getResource('FrontController');
$front->returnResponse(true);
/** @var $response \Zend_Controller_Response_Abstract */
$response = $bootstrap->run();
if (!$response instanceof \Zend_Controller_Response_Abstract) {
// looks like ZF1 already sent response, so there is nothing more to do
$event->stopPropagation();
return;
}
$event->setResult($response);
}
}
| <?php
namespace Zf1Module\Controller;
use Zend\Mvc\Controller\AbstractController;
use Zend\Mvc\MvcEvent;
class DispatchController extends AbstractController
{
/**
* Execute the request
*
* @param \Zend\Mvc\MvcEvent $event
* @return \Zend_Controller_Response_Abstract|null
*/
public function onDispatch(MvcEvent $event)
{
/** @var $bootstrap \Zend_Application_Bootstrap_Bootstrap */
$bootstrap = $this->getServiceLocator()->get('Zf1Module\Application')->getBootstrap();
$bootstrap->bootstrap();
/** @var $front \Zend_Controller_Front */
$front = $bootstrap->getResource('FrontController');
$front->returnResponse(true);
/** @var $response \Zend_Controller_Response_Abstract */
$response = $bootstrap->run();
if (!$response instanceof \Zend_Controller_Response_Abstract) {
// looks like ZF1 already sent response, so there is nothing more to do
$event->stopPropagation();
return;
}
$event->setResult($response);
}
}
|
Allow specifying jumpkind with creating a Path via PathGenerator.blank_path() | import logging
l = logging.getLogger('angr.states')
class PathGenerator(object):
def __init__(self, project):
self._project = project
def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s, jumpkind=jumpkind)
def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
| import logging
l = logging.getLogger('angr.states')
class PathGenerator(object):
def __init__(self, project):
self._project = project
def blank_path(self, state=None, *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s)
def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
|
Use float in session fields | from tyk.decorators import *
from gateway import TykGateway as tyk
@CustomKeyCheck
def MyKeyCheck(request, session, metadata, spec):
print("Running MyKeyCheck?")
print("request:", request)
print("session:", session)
print("spec:", spec)
valid_token = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d'
request_token = request.get_header('Authorization')
print("(python) request_token =", request_token)
if request_token == valid_token:
print("Token is OK")
session.rate = 1000.0
session.per = 1.0
metadata['token'] = "mytoken"
else:
print("Token is WRONG")
request.return_overrides = { 'response_code': 401, 'response_error': 'Not authorized (by the Python middleware)' }
return request, session, metadata
| from tyk.decorators import *
from gateway import TykGateway as tyk
@CustomKeyCheck
def MyKeyCheck(request, session, metadata, spec):
print("Running MyKeyCheck?")
print("request:", request)
print("session:", session)
print("spec:", spec)
valid_token = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d'
request_token = request.get_header('Authorization')
if request_token == valid_token:
print("Token is OK")
session.rate = 1000
session.per = 1
metadata['token'] = "mytoken"
else:
print("Token is WRONG")
request.return_overrides = { 'response_code': 401, 'response_error': 'Not authorized (by the Python middleware)' }
return request, session, metadata
|
Fix failing tests with recent versions of pytest-flake8 | import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if alpha is not None else '', hue,
trim(str(saturation / 10.)), trim(str(light / 10.)),
', %s' % alpha if alpha is not None else '') +
tuple(trim(str(round(v, 10)))
for v in colorsys.hls_to_rgb(
hue / 360., light / 1000., saturation / 1000.)) +
(alpha if alpha is not None else 1,)
)
for alpha in [None, 1, .2, 0]
for light in range(0, 1001, 125)
for saturation in range(0, 1001, 125)
for hue in range(0, 360, 30)
))
print(']')
| import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if a is not None else '', h,
trim(str(s / 10.)), trim(str(l / 10.)),
', %s' % a if a is not None else '') +
tuple(trim(str(round(v, 10)))
for v in colorsys.hls_to_rgb(h / 360., l / 1000., s / 1000.)) +
(a if a is not None else 1,)
)
for a in [None, 1, .2, 0]
for l in range(0, 1001, 125)
for s in range(0, 1001, 125)
for h in range(0, 360, 30)
))
print(']')
|
[FIX] Test broken after introduction of numeric type
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@53335 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
// (c) Copyright 2002-2014 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
class Search_Index_TypeAnalysisDecorator extends Search_Index_AbstractIndexDecorator
{
private $identifierClass;
private $numericClass;
private $mapping = array();
function __construct(Search_Index_Interface $index)
{
parent::__construct($index);
$this->identifierClass = get_class($index->getTypeFactory()->identifier(1));
$this->numericClass = get_class($index->getTypeFactory()->numeric(1));
}
function addDocument(array $document)
{
$new = array_diff_key($document, $this->mapping);
foreach ($new as $key => $value) {
$this->mapping[$key] = $value instanceof $this->identifierClass || $value instanceof $this->numericClass;
}
return $this->parent->addDocument($document);
}
function getIdentifierFields()
{
return array_keys(array_filter($this->mapping));
}
}
| <?php
// (c) Copyright 2002-2014 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
class Search_Index_TypeAnalysisDecorator extends Search_Index_AbstractIndexDecorator
{
private $identifierClass;
private $mapping = array();
function __construct(Search_Index_Interface $index)
{
parent::__construct($index);
$this->identifierClass = get_class($index->getTypeFactory()->identifier(1));
}
function addDocument(array $document)
{
$new = array_diff_key($document, $this->mapping);
foreach ($new as $key => $value) {
$this->mapping[$key] = $value instanceof $this->identifierClass;
}
return $this->parent->addDocument($document);
}
function getIdentifierFields()
{
return array_keys(array_filter($this->mapping));
}
}
|
[Form] Add option "prototype" defaulting to true. | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Type;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\EventListener\ResizeFormListener;
class CollectionType extends AbstractType
{
public function configure(FormBuilder $builder, array $options)
{
if ($options['modifiable'] && $options['prototype']) {
$builder->add('$$name$$', $options['type'], array(
'property_path' => null,
'required' => false,
));
}
$listener = new ResizeFormListener($builder->getFormFactory(),
$options['type'], $options['modifiable']);
$builder->addEventSubscriber($listener);
}
public function getDefaultOptions(array $options)
{
return array(
'template' => 'collection',
'modifiable' => false,
'prototype' => false,
'type' => 'text',
);
}
public function getName()
{
return 'collection';
}
} | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Type;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\EventListener\ResizeFormListener;
class CollectionType extends AbstractType
{
public function configure(FormBuilder $builder, array $options)
{
if ($options['modifiable']) {
$builder->add('$$name$$', $options['type'], array(
'property_path' => null,
'required' => false,
));
}
$listener = new ResizeFormListener($builder->getFormFactory(),
$options['type'], $options['modifiable']);
$builder->addEventSubscriber($listener);
}
public function getDefaultOptions(array $options)
{
return array(
'template' => 'collection',
'modifiable' => false,
'type' => 'text',
);
}
public function getName()
{
return 'collection';
}
} |
Add check for `creep.my` in `isPlayerHazard` | 'use strict'
Room.prototype.getPlayerHostiles = function () {
if (!this.__playerHostiles) {
const hostiles = this.find(FIND_HOSTILE_CREEPS)
this.__playerHostiles = _.filter(hostiles, Room.isPlayerHazard)
}
return this.__playerHostiles
}
Room.prototype.getHostilesByPlayer = function () {
if (!this.__hostilesByPlayer) {
const hostiles = this.getPlayerHostiles()
this.__hostilesByPlayer = {}
for (const hostile of hostiles) {
const owner = hostile.owner.username
if (!this.__hostilesByPlayer[owner]) {
this.__hostilesByPlayer[owner] = []
}
this.__hostilesByPlayer[owner].push(hostile)
}
}
return this.__hostilesByPlayer
}
Room.isPlayerHazard = function (creep) {
if (creep.owner.username === 'Invader' || creep.owner.username === 'Screeps') {
return false
}
if (creep.my) {
return false
}
return this.isPotentialHazard(creep)
}
Room.isPotentialHazard = function (creep) {
const hazardTypes = [ATTACK, RANGED_ATTACK, HEAL, WORK, CLAIM]
return _.some(creep.body, b => _.include(hazardTypes, b.type))
}
| 'use strict'
Room.prototype.getPlayerHostiles = function () {
if (!this.__playerHostiles) {
const hostiles = this.find(FIND_HOSTILE_CREEPS)
this.__playerHostiles = _.filter(hostiles, Room.isPlayerHazard)
}
return this.__playerHostiles
}
Room.prototype.getHostilesByPlayer = function () {
if (!this.__hostilesByPlayer) {
const hostiles = this.getPlayerHostiles()
this.__hostilesByPlayer = {}
for (const hostile of hostiles) {
const owner = hostile.owner.username
if (!this.__hostilesByPlayer[owner]) {
this.__hostilesByPlayer[owner] = []
}
this.__hostilesByPlayer[owner].push(hostile)
}
}
return this.__hostilesByPlayer
}
Room.isPlayerHazard = function (creep) {
if (creep.owner.username === 'Invader' || creep.owner.username === 'Screeps') {
return false
}
return this.isPotentialHazard(creep)
}
Room.isPotentialHazard = function (creep) {
const hazardTypes = [ATTACK, RANGED_ATTACK, HEAL, WORK, CLAIM]
return _.some(creep.body, b => _.include(hazardTypes, b.type))
}
|
Make Components enumerable in CommonJS export | /* jshint node:true */
'use strict';
// Expose `React` as a global, because the ReactIntlMixin assumes it's global.
var oldReact = global.React;
global.React = require('react');
// Require the lib and add all locale data to `ReactIntl`. This module will be
// ignored when bundling for the browser with Browserify/Webpack.
var ReactIntl = require('./lib/react-intl');
require('./lib/locales');
// Export the Mixin as the default export for back-compat with v1.0.0. This will
// be changed to simply re-exporting `ReactIntl` as the default export in v2.0.
exports = module.exports = ReactIntl.Mixin;
// Define non-enumerable expandos for each named export on the default export --
// which is the Mixin for back-compat with v1.0.0.
Object.keys(ReactIntl).forEach(function (namedExport) {
Object.defineProperty(exports, namedExport, {
enumerable: true,
value : ReactIntl[namedExport]
});
});
// Put back `global.React` to how it was.
if (oldReact) {
global.React = oldReact;
} else {
delete global.React;
}
| /* jshint node:true */
'use strict';
// Expose `React` as a global, because the ReactIntlMixin assumes it's global.
var oldReact = global.React;
global.React = require('react');
// Require the lib and add all locale data to `ReactIntl`. This module will be
// ignored when bundling for the browser with Browserify/Webpack.
var ReactIntl = require('./lib/react-intl');
require('./lib/locales');
// Export the Mixin as the default export for back-compat with v1.0.0. This will
// be changed to simply re-exporting `ReactIntl` as the default export in v2.0.
exports = module.exports = ReactIntl.Mixin;
// Define non-enumerable expandos for each named export on the default export --
// which is the Mixin for back-compat with v1.0.0.
Object.keys(ReactIntl).forEach(function (namedExport) {
Object.defineProperty(exports, namedExport, {
value: ReactIntl[namedExport]
});
});
// Put back `global.React` to how it was.
if (oldReact) {
global.React = oldReact;
} else {
delete global.React;
}
|
Add 'cjsTranslate' config option to build profile | ({
mainConfigFile: './requirejs.conf.js',
paths: {
jquery: 'lib/jquery/jquery.min',
almond: 'lib/almond/almond'
},
baseUrl: '.',
name: "streamhub-map",
exclude: ['streamhub-sdk', 'almond'],
stubModules: ['text', 'hgn', 'json'],
out: "./dist/streamhub-map.min.js",
namespace: 'Livefyre',
pragmasOnSave: {
excludeHogan: true
},
cjsTranslate: true,
optimize: "uglify2",
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
onBuildRead: function(moduleName, path, contents) {
if (moduleName == "jquery") {
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
| ({
mainConfigFile: './requirejs.conf.js',
paths: {
jquery: 'lib/jquery/jquery.min',
almond: 'lib/almond/almond'
},
baseUrl: '.',
name: "streamhub-map",
exclude: ['streamhub-sdk', 'almond'],
stubModules: ['text', 'hgn', 'json'],
out: "./dist/streamhub-map.min.js",
namespace: 'Livefyre',
pragmasOnSave: {
excludeHogan: true
},
optimize: "uglify2",
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
onBuildRead: function(moduleName, path, contents) {
if (moduleName == "jquery") {
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
|
Update testing to better fit | /*
#
# i2mx.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = i2mx || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divId = "i2mx-checkup";
this.activate = function() {
// @TODO: Use HTML generator
// Initial values
var div = document.getElementById(this.divId);
var EOL = "<br>"
var checkupText = EOL;
// Start testing
checkupText += "Starting tests... " + EOL;
if(window.File && window.FileReader && window.FileList && window.Blob) {
checkupText += "File and Blob APIs - OK " + EOL;
}
// Update DOM
div.innerHTML = checkupText;
}
}
var jsCheckup = new JsCheckup();
// @TODO: Use event listener instead of onload
window.onload = function() {
jsCheckup.activate();
}
| /*
#
# i2mx.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = i2mx || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divId = "i2mx-checkup";
this.activate = function() {
// @TODO: Use HTML generator
// Initial values
var div = document.getElementById(this.divId);
var EOL = "<br>"
var checkupText = "";
// Start testing
checkupText += "Starting tests... " + EOL;
if(window.File && window.FileReader && window.FileList && window.Blob) {
checkupText += "File and Blob APIs -> OK " + EOL;
}
// Update DOM
div.innerHTML = checkupText;
}
}
var jsCheckup = new JsCheckup();
// @TODO: Use event listener instead of onload
window.onload = function() {
jsCheckup.activate();
}
|
Use IP instead of hostname in connection settings | /*
Copyright (C) 2010, Oleg Efimov <efimovov@gmail.com>
See license text in LICENSE file
*/
/*
> mysql -u root
CREATE DATABASE test DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
GRANT ALL ON test.* TO test@localhost IDENTIFIED BY "";
*/
exports.getConfig = function (factor) {
var cfg = {
// Database connection settings
host: "127.0.0.1",
user: "test",
password: "",
database: "test",
test_table: "test_table",
// Benchmarks parameters
escape_count: 1000000 * factor,
string_to_escape: "str\\str\"str\'str\x00str",
reconnect_count: 10000 * factor,
insert_rows_count: 100000 * factor,
// Delay before assertion check (ms)
delay_before_select: 1 * 1000,
// Run sync functions if async exists?
do_not_run_sync_if_async_exists: true
};
cfg.create_table_query = "CREATE TABLE " + cfg.test_table +
" (alpha INTEGER, beta VARCHAR(128), pi FLOAT) " +
"TYPE=MEMORY;";
cfg.insert_query = "INSERT INTO " + cfg.test_table +
" VALUES (1, 'hello', 3.141);";
cfg.selected_row_example = {alpha: 1, beta: 'hello', pi: 3.141};
return cfg;
};
| /*
Copyright (C) 2010, Oleg Efimov <efimovov@gmail.com>
See license text in LICENSE file
*/
/*
> mysql -u root
CREATE DATABASE test DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
GRANT ALL ON test.* TO test@localhost IDENTIFIED BY "";
*/
exports.getConfig = function (factor) {
var cfg = {
// Database connection settings
host: "localhost",
user: "test",
password: "",
database: "test",
test_table: "test_table",
// Benchmarks parameters
escape_count: 1000000 * factor,
string_to_escape: "str\\str\"str\'str\x00str",
reconnect_count: 10000 * factor,
insert_rows_count: 100000 * factor,
// Delay before assertion check (ms)
delay_before_select: 1 * 1000,
// Run sync functions if async exists?
do_not_run_sync_if_async_exists: true
};
cfg.create_table_query = "CREATE TABLE " + cfg.test_table +
" (alpha INTEGER, beta VARCHAR(128), pi FLOAT) " +
"TYPE=MEMORY;";
cfg.insert_query = "INSERT INTO " + cfg.test_table +
" VALUES (1, 'hello', 3.141);";
cfg.selected_row_example = {alpha: 1, beta: 'hello', pi: 3.141};
return cfg;
};
|
Add vue.js release build option | const path = require('path');
const webpack = require("webpack");
const DEBUG = process.argv.includes('--debug'); // `webpack --debug` or NOT
const plugins = [
new webpack.optimize.OccurrenceOrderPlugin(),
];
if (!DEBUG) {
plugins.push(
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: '"production"' }
})
);
}
module.exports = {
entry: "./src/js/ipcalc.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "public/js")
},
plugins: plugins,
devtool: DEBUG ? "#cheap-module-eval-source-map" : "#cheap-module-source-map",
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
}
| const path = require('path');
const webpack = require("webpack");
const DEBUG = process.argv.includes('--debug'); // `webpack --debug` or NOT
const plugins = [
new webpack.optimize.OccurrenceOrderPlugin(),
];
if (!DEBUG) {
plugins.push(
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
);
}
module.exports = {
entry: "./src/js/ipcalc.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "public/js")
},
plugins: plugins,
devtool: DEBUG ? "#cheap-module-eval-source-map" : "#cheap-module-source-map",
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
}
|
Add i18n to home screen | /* @flow */
import React, { Component } from 'react';
import {
Text,
View,
Image
} from 'react-native';
import Button from '../../components/Button';
import images from '../../config/images';
import styles from './styles'
import I18n from 'react-native-i18n'
export class Home extends Component {
static navigationOptions = {
header: {visible: false},
};
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Image source={images.logo} style={styles.logo}/>
<View style={styles.buttons}>
<Button text={I18n.t('newGame')} onPress={() => navigate("NewGame")}></Button>
<Button text={I18n.t('continueGame')} onPress={() => console.log("Continue Game button pressed!")}></Button>
<Button text={I18n.t('settings')} onPress={() => console.log("Settings button pressed!")}></Button>
</View>
</View>
);
}
};
I18n.fallbacks = true
I18n.translations = {
en: {
newGame: "New Game",
continueGame: "Continue Game",
settings: "Settings"
},
de: {
newGame: "Neues Spiel",
continueGame: "Spiel fortsetzen",
settings: "Einstellungen"
}
}
| /* @flow */
import React, { Component } from 'react';
import {
Text,
View,
Image
} from 'react-native';
import Button from '../../components/Button';
import images from '../../config/images';
import styles from './styles'
export class Home extends Component {
static navigationOptions = {
header: {visible: false},
};
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Image source={images.logo} style={styles.logo}/>
<View style={styles.buttons}>
<Button text="New Game" onPress={() => navigate("NewGame")}></Button>
<Button text="Continue Game" onPress={() => console.log("Continue Game button pressed!")}></Button>
<Button text="Settings" onPress={() => console.log("Settings button pressed!")}></Button>
</View>
</View>
);
}
};
|
Repair php's giving error from BoradInfoController | <?php
class BoardInfoController extends Controller {
public function execute($request) {
try {
parent::execute($request);
$id = $request[1];
$boardinfo = new InformationAccess();
if ($id != null && is_numeric($id)) {
$oneBoardInfo = $boardinfo->getBoardInfoById($id);
$_REQUEST["boardInfo"] = serialize($oneBoardInfo);
// Update read count
if(@$_SESSION["read"] <> "paitsio#".$id) {
$readCount = $boardinfo->updatePaitsioReadCount($id);
$_SESSION["read"] = "paitsio#".$id;
}
} else {
$allBoardInfos = $boardinfo->getAllBoardInfos();
$_REQUEST["allBoardInfos"] = serialize($allBoardInfos);
}
$return = "boardInfoPage";
} catch (Exception $e) {
throw $e;
}
return $return;
}
}
?> | <?php
class BoardInfoController extends Controller {
public function execute($request) {
try {
parent::execute($request);
$id = $request[1];
$boardinfo = new InformationAccess();
if ($id != null && is_numeric($id)) {
$oneBoardInfo = $boardinfo->getBoardInfoById($id);
$_REQUEST["boardInfo"] = serialize($oneBoardInfo);
// Update read count
if($_SESSION["read"] <> "paitsio#".$id) {
$readCount = $boardinfo->updatePaitsioReadCount($id);
$_SESSION["read"] = "paitsio#".$id;
}
} else {
$allBoardInfos = $boardinfo->getAllBoardInfos();
$_REQUEST["allBoardInfos"] = serialize($allBoardInfos);
}
$return = "boardInfoPage";
} catch (Exception $e) {
throw $e;
}
return $return;
}
}
?> |
Fix z-index failure caused by Notifications being below SideNav in DOM
Signed-off-by: Jared Scheib <06bd14d569e7a29ad7c0a1b3adcce8579ff36322@gmail.com> | import React, {PropTypes} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import SideNav from 'src/side_nav'
import Notifications from 'shared/components/Notifications'
import {publishNotification} from 'shared/actions/notifications'
const {func, node} = PropTypes
const App = React.createClass({
propTypes: {
children: node.isRequired,
notify: func.isRequired,
},
handleAddFlashMessage({type, text}) {
const {notify} = this.props
notify(type, text)
},
render() {
return (
<div className="chronograf-root">
<Notifications />
<SideNav />
{this.props.children &&
React.cloneElement(this.props.children, {
addFlashMessage: this.handleAddFlashMessage,
})}
</div>
)
},
})
const mapDispatchToProps = dispatch => ({
notify: bindActionCreators(publishNotification, dispatch),
})
export default connect(null, mapDispatchToProps)(App)
| import React, {PropTypes} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import SideNav from 'src/side_nav'
import Notifications from 'shared/components/Notifications'
import {publishNotification} from 'shared/actions/notifications'
const {func, node} = PropTypes
const App = React.createClass({
propTypes: {
children: node.isRequired,
notify: func.isRequired,
},
handleAddFlashMessage({type, text}) {
const {notify} = this.props
notify(type, text)
},
render() {
return (
<div className="chronograf-root">
<SideNav />
<Notifications />
{this.props.children &&
React.cloneElement(this.props.children, {
addFlashMessage: this.handleAddFlashMessage,
})}
</div>
)
},
})
const mapDispatchToProps = dispatch => ({
notify: bindActionCreators(publishNotification, dispatch),
})
export default connect(null, mapDispatchToProps)(App)
|
Fix 'd' problem on translation
Since in spanish you use 'de' to say 'of' it gets mistaken for a d in the date format. An easy way to fix this is to use 'De' with capital D so it doesn't get mistaken. It's better to have a misplaced capital letter to a useless date name (the dates get rendered as "Domingo 22 22e Junio 22e 2013" instead of "Domingo 22 de Junio de 2013" | // Spanish
$.extend( $.fn.pickadate.defaults, {
monthsFull: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
weekdaysFull: [ 'domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado' ],
weekdaysShort: [ 'dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sab' ],
today: 'hoy',
clear: 'borrar',
firstDay: 1,
format: 'dddd d De mmmm De yyyy',
formatSubmit: 'yyyy/mm/dd'
});
| // Spanish
$.extend( $.fn.pickadate.defaults, {
monthsFull: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
weekdaysFull: [ 'domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado' ],
weekdaysShort: [ 'dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sab' ],
today: 'hoy',
clear: 'borrar',
firstDay: 1,
format: 'dddd d de mmmm de yyyy',
formatSubmit: 'yyyy/mm/dd'
}); |
Update mini_installer test wrapper script.
This tracks changes made to the script in r286837.
BUG=264859,399511
R=robertshield@chromium.org
Review URL: https://codereview.chromium.org/437593008
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@286999 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
'-v',
'--config', mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
| #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
|
Copy listeners array since it might be changed in one of the listeners, especially in Safari | 'use strict'
function signal(options) {
var listeners = []
var api = {
push: function(listener) {
if (listeners.indexOf(listener) < 0) {
listeners.push(listener)
}
return api
},
pull: function(listener) {
var index = listeners.indexOf(listener);
if (index > -1) {
listeners.splice(index, 1)
}
return api
},
trigger: function() {
var args = arguments;
[].concat(listeners).map(function(listener) {
try {
listener.apply(null, args)
} catch(e) {
if (options && options.logExceptions) {
console.error(e)
}
}
})
return api
},
clear: function() {
listeners = []
}
}
return api
}
module.exports = signal
| 'use strict'
function signal(options) {
var listeners = []
var api = {
push: function(listener) {
if (listeners.indexOf(listener) < 0) {
listeners.push(listener)
}
return api
},
pull: function(listener) {
var index = listeners.indexOf(listener);
if (index > -1) {
listeners.splice(index, 1)
}
return api
},
trigger: function() {
var args = arguments
listeners.map(function(listener) {
try {
listener.apply(null, args)
} catch(e) {
if (options && options.logExceptions) {
console.error(e)
}
}
})
return api
},
clear: function() {
listeners = []
}
}
return api
}
module.exports = signal
|
Choose set background method by API | package edu.rutgers.css.Rutgers.fragments;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import edu.rutgers.css.Rutgers2.R;
public class MainScreen extends Fragment {
public MainScreen() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main_screen, container, false);
getActivity().setTitle(R.string.app_name);
int bgResource;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) bgResource = R.drawable.bgland;
else bgResource = R.drawable.bgportrait;
Bitmap bg = BitmapFactory.decodeResource(getResources(), bgResource, new BitmapFactory.Options());
Drawable bgDraw = new BitmapDrawable(bg);
if(android.os.Build.VERSION.SDK_INT >= 16) {
v.setBackground(bgDraw);
}
else {
v.setBackgroundDrawable(bgDraw);
}
return v;
}
}
| package edu.rutgers.css.Rutgers.fragments;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import edu.rutgers.css.Rutgers2.R;
public class MainScreen extends Fragment {
public MainScreen() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main_screen, container, false);
getActivity().setTitle(R.string.app_name);
int bgResource;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) bgResource = R.drawable.bgland;
else bgResource = R.drawable.bgportrait;
Bitmap bg = BitmapFactory.decodeResource(getResources(), bgResource, new BitmapFactory.Options());
Drawable bgDraw = new BitmapDrawable(bg);
v.setBackground(bgDraw);
return v;
}
}
|
Update angular+jasmine externs to have the module function accept an Object value map.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=195101380 | /*
* Copyright 2015 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Extra externs for Jasmine when using Angular.
*
* Depends on both the angular-1.x-mocks.js and Jasmine 2.0 externs.
*
* @externs
*/
/**
* Provided by angular-mocks.js.
* @type {angular.$injector}
*/
jasmine.Spec.prototype.$injector;
/**
* Provided by angular-mocks.js.
* @param {...(Function|Array<string|Function>)} var_args
*/
function inject(var_args) {}
/**
* Provided by angular-mocks.js.
* @param {...(string|Function|Array<string|Function>|Object<string, *>)}
* var_args
* @suppress {checkTypes}
*/
function module(var_args) {}
| /*
* Copyright 2015 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Extra externs for Jasmine when using Angular.
*
* Depends on both the angular-1.x-mocks.js and Jasmine 2.0 externs.
*
* @externs
*/
/**
* Provided by angular-mocks.js.
* @type {angular.$injector}
*/
jasmine.Spec.prototype.$injector;
/**
* Provided by angular-mocks.js.
* @param {...(Function|Array<string|Function>)} var_args
*/
function inject(var_args) {}
/**
* Provided by angular-mocks.js.
* @param {...(string|Function|Array<string|Function>)} var_args
* @suppress {checkTypes}
*/
function module(var_args) {}
|
Check ajaxOptions options argument presence | import Ember from 'ember';
export default Ember.Mixin.create({
// Overwrite to change the request types on which Form Data is sent
formDataTypes: ['POST', 'PUT', 'PATCH'],
ajaxOptions: function(url, type, options) {
var data;
if (options && 'data' in options) { data = options.data; }
var hash = this._super.apply(this, arguments);
if (typeof FormData === 'function' && data && this.formDataTypes.contains(type)) {
var formData = new FormData();
var root = Ember.keys(data)[0];
Ember.keys(data[root]).forEach(function(key) {
if (data[root][key]) {
formData.append(root + "[" + key + "]", data[root][key]);
}
});
hash.processData = false;
hash.contentType = false;
hash.data = formData;
}
return hash;
},
});
| import Ember from 'ember';
export default Ember.Mixin.create({
// Overwrite to change the request types on which Form Data is sent
formDataTypes: ['POST', 'PUT', 'PATCH'],
ajaxOptions: function(url, type, options) {
var data;
if ('data' in options) { data = options.data; }
var hash = this._super.apply(this, arguments);
if (typeof FormData === 'function' && data && this.formDataTypes.contains(type)) {
var formData = new FormData();
var root = Ember.keys(data)[0];
Ember.keys(data[root]).forEach(function(key) {
if (data[root][key]) {
formData.append(root + "[" + key + "]", data[root][key]);
}
});
hash.processData = false;
hash.contentType = false;
hash.data = formData;
}
return hash;
},
});
|
Convert remaining merge to extend | 'use strict';
var extend = require('extend');
var rump = require('rump');
var webpack = require('./webpack');
exports.rebuild = function() {
rump.configs.main.globs = extend(true, {
build: {
scripts: '*.js'
},
watch: {
scripts: '**/*.js'
},
test: {
scripts: '**/*_test.js'
}
}, rump.configs.main.globs);
rump.configs.main.paths = extend(true, {
source: {
scripts: 'scripts'
},
destination: {
scripts: 'scripts'
}
}, rump.configs.main.paths);
rump.configs.main.scripts = extend(true, {
aliases: {},
common: false,
library: false,
uglify: {
dropDebugger: true,
dropConsole: true
},
webpack: {}
}, rump.configs.main.scripts);
exports.webpack = webpack();
};
exports.rebuild();
| 'use strict';
var merge = require('merge');
var rump = require('rump');
var webpack = require('./webpack');
exports.rebuild = function() {
rump.configs.main.globs = merge.recursive({
build: {
scripts: '*.js'
},
watch: {
scripts: '**/*.js'
},
test: {
scripts: '**/*_test.js'
}
}, rump.configs.main.globs);
rump.configs.main.paths = merge.recursive({
source: {
scripts: 'scripts'
},
destination: {
scripts: 'scripts'
}
}, rump.configs.main.paths);
rump.configs.main.scripts = merge.recursive({
aliases: {},
common: false,
library: false,
uglify: {
dropDebugger: true,
dropConsole: true
},
webpack: {}
}, rump.configs.main.scripts);
exports.webpack = webpack();
};
exports.rebuild();
|
Add dev option to version string | """
Camoco Library - CoAnalysis of Molecular Components
CacheMoneyCorn
"""
__license__ = """
Creative Commons Non-Commercial 4.0 Generic
http://creativecommons.org/licenses/by-nc/4.0/
"""
__version__ = '0.3.0-dev'
import sys
import os
import numpy
import pyximport
pyximport.install(setup_args={
"include_dirs":numpy.get_include()
})
import matplotlib
matplotlib.use('Agg')
from .Config import cf
from .Camoco import Camoco
from .Expr import Expr
from .COB import COB
from .RefGen import RefGen
from .RefGenDist import *
from .PCCUP import *
from .Ontology import Ontology,Term
from .GWAS import GWAS
from .HapMap import HapMap
from .Locus import Locus
from .Tools import available_datasets,del_dataset
from .Tools import mv_dataset,redescribe_dataset
from .GEO import Family
from .GOnt import GOnt
from .Annotation import GWASData
# Create yourself
Camoco.create('Camoco','Mother Database')
| """
Camoco Library - CoAnalysis of Molecular Components
CacheMoneyCorn
"""
__license__ = """
Creative Commons Non-Commercial 4.0 Generic
http://creativecommons.org/licenses/by-nc/4.0/
"""
__version__ = '0.3.0'
import sys
import os
import numpy
import pyximport
pyximport.install(setup_args={
"include_dirs":numpy.get_include()
})
import matplotlib
matplotlib.use('Agg')
from .Config import cf
from .Camoco import Camoco
from .Expr import Expr
from .COB import COB
from .RefGen import RefGen
from .RefGenDist import *
from .PCCUP import *
from .Ontology import Ontology,Term
from .GWAS import GWAS
from .HapMap import HapMap
from .Locus import Locus
from .Tools import available_datasets,del_dataset
from .Tools import mv_dataset,redescribe_dataset
from .GEO import Family
from .GOnt import GOnt
from .Annotation import GWASData
# Create yourself
Camoco.create('Camoco','Mother Database')
|
Rename the OpenStack AWS resource to avoid name clash with native
OpenStack ships a native ASG resource type with the same name. We
rename this to AWSAutoScalingGroup to avoid the clash and make way
to the native type to come. | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# Copyright (c) 2014, Andy Botting <andy.botting@theguardian.com>
# All rights reserved.
#
# See LICENSE file for full license.
from troposphere import AWSObject
from troposphere.validators import integer
# Due to the strange nature of the OpenStack compatability layer, some values
# that should be integers fail to validate and need to be represented as
# strings. For this reason, we duplicate the AWS::AutoScaling::AutoScalingGroup
# and change these types.
class AWSAutoScalingGroup(AWSObject):
type = "AWS::AutoScaling::AutoScalingGroup"
props = {
'AvailabilityZones': (list, True),
'Cooldown': (integer, False),
'DesiredCapacity': (basestring, False),
'HealthCheckGracePeriod': (int, False),
'HealthCheckType': (basestring, False),
'LaunchConfigurationName': (basestring, True),
'LoadBalancerNames': (list, False),
'MaxSize': (basestring, True),
'MinSize': (basestring, True),
'Tags': (list, False),
'VPCZoneIdentifier': (list, False),
}
| # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# Copyright (c) 2014, Andy Botting <andy.botting@theguardian.com>
# All rights reserved.
#
# See LICENSE file for full license.
from troposphere import AWSObject
from troposphere.validators import integer
# Due to the strange nature of the OpenStack compatability layer, some values
# that should be integers fail to validate and need to be represented as
# strings. For this reason, we duplicate the AWS::AutoScaling::AutoScalingGroup
# and change these types.
class AutoScalingGroup(AWSObject):
type = "AWS::AutoScaling::AutoScalingGroup"
props = {
'AvailabilityZones': (list, True),
'Cooldown': (integer, False),
'DesiredCapacity': (basestring, False),
'HealthCheckGracePeriod': (int, False),
'HealthCheckType': (basestring, False),
'LaunchConfigurationName': (basestring, True),
'LoadBalancerNames': (list, False),
'MaxSize': (basestring, True),
'MinSize': (basestring, True),
'Tags': (list, False),
'VPCZoneIdentifier': (list, False),
}
|
Use createForm instead of the form factory | <?php
namespace Knp\IpsumBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Knp\IpsumBundle\Form\Type\ContactType;
use Knp\IpsumBundle\Form\Model\Contact;
class FormController extends Controller
{
public function contactAction()
{
$contact = new Contact();
$form = $this->createForm(new ContactType(), $contact);
$request = $this->container->get('request');
if ('POST' === $request->getMethod()) {
$form->bindRequest($request);
if ($form->isValid()) {
$ret = $contact->dummySend();
$this->get('session')->setFlash('notice', $ret);
return new RedirectResponse($this->generateUrl('knp_ipsum'));
}
}
return $this->render('KnpIpsumBundle:Form:contact.html.twig', array(
'form' => $form->createView(),
));
}
}
| <?php
namespace Knp\IpsumBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Knp\IpsumBundle\Form\Type\ContactType;
use Knp\IpsumBundle\Form\Model\Contact;
class FormController extends Controller
{
public function contactAction()
{
$contact = new Contact();
$form = $this->get('form.factory')->create(new ContactType(), $contact);
$request = $this->container->get('request');
if ('POST' === $request->getMethod()) {
$form->bindRequest($request);
if ($form->isValid()) {
$ret = $contact->dummySend();
$this->get('session')->setFlash('notice', $ret);
return new RedirectResponse($this->generateUrl('knp_ipsum'));
}
}
return $this->render('KnpIpsumBundle:Form:contact.html.twig', array(
'form' => $form->createView(),
));
}
}
|
feat: Add support for configuration through env variables
Fixes #23 | // @flow
import _ from 'lodash'
import program from 'commander'
import info from '../package.json'
export type Options = {
command: ?string,
files: Array<string>,
format: string,
branch: string,
linter: string,
warning: boolean,
hash?: string,
}
export function parseOptions(): Options {
program
.version(info.version)
.usage('[options] <subcommand|file ...>')
.option('-f, --format [format]', 'The output format.', 'text')
.option('-b, --branch [branch]', 'The branch to diff against.')
.option('-l, --linter [linter]', 'The linter that is used in the project.', 'eslint')
.option('-w, --warning', 'Make all errors that make it through the filter a warning')
.parse(process.argv)
let [command] = program.args
if (!_.includes(command, ['generate-config', 'list-files'])) {
command = undefined
}
return {
command,
files: program.args,
format: process.env.LINT_FILTER_FORMAT || program.format,
branch: process.env.LINT_FILTER_BRANCH || program.branch,
linter: process.env.LINT_FILTER_LINTER || program.linter,
warning: process.env.LINT_FILTER_WARNING
? JSON.parse(process.env.LINT_FILTER_WARNING)
: !!program.warning,
}
}
| // @flow
import _ from 'lodash'
import program from 'commander'
import info from '../package.json'
export type Options = {
command: ?string,
files: Array<string>,
format: string,
branch: string,
linter: string,
warning: boolean,
hash?: string,
}
export function parseOptions(): Options {
program
.version(info.version)
.usage('[options] <subcommand|file ...>')
.option('-f, --format [format]', 'The output format.', 'text')
.option('-b, --branch [branch]', 'The branch to diff against.')
.option('-l, --linter [linter]', 'The linter that is used in the project.', 'eslint')
.option('-w, --warning', 'Make all errors that make it through the filter a warning')
.parse(process.argv)
let [command] = program.args
if (!_.includes(command, ['generate-config', 'list-files'])) {
command = undefined
}
return {
command,
files: program.args,
format: program.format,
branch: program.branch,
linter: program.linter,
warning: !!program.warning,
}
}
|
Rename the first parameter for the compile mthod | <?php
abstract class Media_Compiler {
/**
* Add contents to the file specified, while
* also recursively creating the directory the
* file should be located in if it doesn't exist
*
* @param string $filepath The file location
* @param string $contents The file contents
*/
public function put_contents($filepath, $contents)
{
// Genearte the directory tree
$this->make_missing_directories($filepath);
// Create the file with the contents
file_put_contents($filepath, $contents);
}
/**
* Recursively create a directory path in the
* filesysystem if the path doesn't exist
*
* @param string $filepath The file path to create
*/
public function make_missing_directories($filepath)
{
// Get the real directory path
$directory = pathinfo($filepath, PATHINFO_DIRNAME);
// Create missing directories recursively
if ( ! is_dir($directory))
{
mkdir($directory, 0777, TRUE);
}
}
/**
* Compile a type of media source and place
* the compiled file(s) into the configured
* location in the applications media directory
*
* @param array $paths Associative array of source => compiled file
* @param array $options Compiler options
*/
abstract public function compile(array $paths, array $options);
} | <?php
abstract class Media_Compiler {
/**
* Add contents to the file specified, while
* also recursively creating the directory the
* file should be located in if it doesn't exist
*
* @param string $filepath The file location
* @param string $contents The file contents
*/
public function put_contents($filepath, $contents)
{
// Genearte the directory tree
$this->make_missing_directories($filepath);
// Create the file with the contents
file_put_contents($filepath, $contents);
}
/**
* Recursively create a directory path in the
* filesysystem if the path doesn't exist
*
* @param string $filepath The file path to create
*/
public function make_missing_directories($filepath)
{
// Get the real directory path
$directory = pathinfo($filepath, PATHINFO_DIRNAME);
// Create missing directories recursively
if ( ! is_dir($directory))
{
mkdir($directory, 0777, TRUE);
}
}
/**
* Compile a type of media source and place
* the compiled file(s) into the configured
* location in the applications media directory
*
* @param array $filepaths Files to compile
* @param array $options Compiler options
*/
abstract public function compile(array $filepaths, array $options);
} |
Add missing comma in classifier list | #!/usr/bin/env python3
from setuptools import setup
from ipyrmd import __version__
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
author="Gordon Ball",
author_email="gordon@chronitis.net",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Lanuage :: R",
"Environment :: Console",
"Framework :: IPython",
"Framework :: Jupyter",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
| #!/usr/bin/env python3
from setuptools import setup
from ipyrmd import __version__
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
author="Gordon Ball",
author_email="gordon@chronitis.net",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research"
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Lanuage :: R",
"Environment :: Console",
"Framework :: IPython",
"Framework :: Jupyter",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
|
Add callbacks to matchzoo root scope. | from pathlib import Path
USER_DIR = Path.expanduser(Path('~')).joinpath('.matchzoo')
if not USER_DIR.exists():
USER_DIR.mkdir()
USER_DATA_DIR = USER_DIR.joinpath('datasets')
if not USER_DATA_DIR.exists():
USER_DATA_DIR.mkdir()
from .logger import logger
from .version import __version__
from .utils import *
from . import processor_units
from .processor_units import chain_transform, ProcessorUnit
from .data_pack import DataPack
from .data_pack import pack
from .data_pack import load_data_pack
from .data_pack import build_unit_from_data_pack
from .data_pack import build_vocab_unit
from .data_generator import DataGenerator
from .data_generator import PairDataGenerator
from .data_generator import DynamicDataGenerator
from . import tasks
from . import metrics
from . import losses
from . import engine
from . import preprocessors
from . import models
from . import embedding
from . import datasets
from . import auto
from .engine import load_model
from .engine import load_preprocessor
from .engine import callbacks
| from pathlib import Path
USER_DIR = Path.expanduser(Path('~')).joinpath('.matchzoo')
if not USER_DIR.exists():
USER_DIR.mkdir()
USER_DATA_DIR = USER_DIR.joinpath('datasets')
if not USER_DATA_DIR.exists():
USER_DATA_DIR.mkdir()
from .logger import logger
from .version import __version__
from .utils import *
from . import processor_units
from .processor_units import chain_transform, ProcessorUnit
from .data_pack import DataPack
from .data_pack import pack
from .data_pack import load_data_pack
from .data_pack import build_unit_from_data_pack
from .data_pack import build_vocab_unit
from .data_generator import DataGenerator
from .data_generator import PairDataGenerator
from .data_generator import DynamicDataGenerator
from . import tasks
from . import metrics
from . import losses
from . import engine
from . import preprocessors
from . import models
from . import embedding
from . import datasets
from . import auto
from .engine import load_model
from .engine import load_preprocessor
|
Remove duplicate 'context': context in GitHub renderer. | from flask import abort, json
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
if context:
data['context'] = context
data = json.dumps(data)
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/plain'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
| from flask import abort, json
import requests
def render_content(text, gfm=False, context=None, username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm', 'context': context}
if context:
data['context'] = context
data = json.dumps(data)
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/plain'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
|
Fix the django debug toolbar not appearing and the user echo thing slowing my loadings in development. | # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# gurney.licorn.org
'109.190.93.141',
# my LAN
'192.168.111.23',
'192.168.111.111',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.logger.LoggingPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.version.VersionDebugPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'ENABLE_STACKTRACES' : True,
#'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
#'EXTRA_SIGNALS': ['myproject.signals.MySignal'],
#'HIDE_DJANGO_SQL': False,
#'TAG': 'div',
}
| # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# leto.licorn.org
'82.236.133.193',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.logger.LoggingPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.version.VersionDebugPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'ENABLE_STACKTRACES' : True,
#'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
#'EXTRA_SIGNALS': ['myproject.signals.MySignal'],
#'HIDE_DJANGO_SQL': False,
#'TAG': 'div',
}
|
Return error message on HTTP 500 | var express = require('express');
module.exports = exports = function (options) {
var BasicAuth = require('./middleware/auth/basic');
var TradesRouter = require('./routers/trades');
var UserRouter = require('./routers/user');
var UsersRouter = require('./routers/users');
var LabelsRouter = require('./routers/labels');
var app = express();
app.use(BasicAuth({ users: options.users }));
app.use(UserRouter({ users: options.users }));
app.use(UsersRouter({ users: options.users }));
app.use(TradesRouter({ trades: options.trades }));
app.use(LabelsRouter({ labels: options.labels }));
app.all('*', function (req, res, next) {
next(new Error('not_found'));
});
app.use(function(err, req, res, next) {
res.send(500, { error: err.message });
});
return app;
};
| var express = require('express');
module.exports = exports = function (options) {
var BasicAuth = require('./middleware/auth/basic');
var TradesRouter = require('./routers/trades');
var UserRouter = require('./routers/user');
var UsersRouter = require('./routers/users');
var LabelsRouter = require('./routers/labels');
var app = express();
app.use(BasicAuth({ users: options.users }));
app.use(UserRouter({ users: options.users }));
app.use(UsersRouter({ users: options.users }));
app.use(TradesRouter({ trades: options.trades }));
app.use(LabelsRouter({ labels: options.labels }));
app.all('*', function (req, res, next) {
next(new Error('not_found'));
});
app.use(function(err, req, res, next) {
res.send(500, { error: 'something' });
});
return app;
};
|
Add stream uri for wappuradio | var util = require('../src/util/seeds');
exports.seed = function(knex, Promise) {
const cities = {};
return knex('cities').select('*')
.then(rows => {
rows.forEach(city => {
cities[city.name] = city.id;
});
})
.then(() => util.insertOrUpdate(knex, 'radios', {
id: 1,
name: 'Rakkauden Wappuradio',
city_id: cities['Tampere'],
stream: 'http://stream.wappuradio.fi/wappuradio.mp3',
website: 'https://wappuradio.fi/',
}))
.then(() => util.insertOrUpdate(knex, 'radios', {
id: 2,
name: 'Radiodiodi',
city_id: cities['Otaniemi'],
stream: null, // TODO
website: 'https://radiodiodi.fi/',
}));
}
| var util = require('../src/util/seeds');
exports.seed = function(knex, Promise) {
const cities = {};
return knex('cities').select('*')
.then(rows => {
rows.forEach(city => {
cities[city.name] = city.id;
});
})
.then(() => util.insertOrUpdate(knex, 'radios', {
id: 1,
name: 'Rakkauden Wappuradio',
city_id: cities['Tampere'],
stream: null, // TODO
website: 'https://wappuradio.fi/',
}))
.then(() => util.insertOrUpdate(knex, 'radios', {
id: 2,
name: 'Radiodiodi',
city_id: cities['Otaniemi'],
stream: null, // TODO
website: 'https://radiodiodi.fi/',
}));
}
|
Remove to send to watson | const tjbot = require('./tjbotlib');
const config = require('./config/configs');
const credentials = config.credentials;
const WORKSPACEID = config.conversationWorkspaceId;
const hardware = ['microphone', 'speaker'];
const configuration = {
listen: {
microphoneDeviceId: 'plughw:1,0',
inactivityTimeout: 60,
language: 'pt-BR'
},
wave: {
servoPin: 7
},
speak: {
language: 'pt-BR'
},
verboseLogging: true
};
const tj = new tjbot(hardware, configuration, credentials);
tj.listen((msg) => {
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
console.log('Message logger', msg);
// check to see if they are talking to TJBot
const name = msg.split(' ')[0].match(/(sara|vara|sarah|rara)/i)[0];
if (name) {
// send to the conversation service
tj.converse(WORKSPACEID, msg, (response) => {
// speak the result
tj.speak(response.description);
});
}
})
| const tjbot = require('./tjbotlib');
const config = require('./config/configs');
const credentials = config.credentials;
const WORKSPACEID = config.conversationWorkspaceId;
const hardware = ['microphone', 'speaker'];
const configuration = {
listen: {
microphoneDeviceId: 'plughw:1,0',
inactivityTimeout: 60,
language: 'pt-BR'
},
wave: {
servoPin: 7
},
speak: {
language: 'pt-BR'
},
verboseLogging: true
};
const tj = new tjbot(hardware, configuration, credentials);
tj.listen((msg) => {
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
console.log('Message logger', msg);
// check to see if they are talking to TJBot
const name = msg.split(' ')[0].match(/(sara|vara|sarah)/i)[0];
if (name) {
// remove our name from the message
const turn = msg.replace(/(sara|vara|sarah)/i, '');
console.log('Turn logger', turn);
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
}
})
|
Use yield_fixture for app fixture | import pytest
import django_webtest
from django.core.urlresolvers import reverse
from ideasbox.tests.factories import UserFactory
@pytest.fixture()
def user():
return UserFactory(short_name="Hello", password='password')
@pytest.fixture()
def staffuser():
return UserFactory(short_name="Hello", password='password', is_staff=True)
@pytest.yield_fixture()
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
yield django_webtest.DjangoTestApp()
wtm._unpatch_settings()
@pytest.fixture()
def loggedapp(app, user):
"""Return an app with an already logged in user."""
form = app.get(reverse('login')).forms['login']
form['username'] = user.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
@pytest.fixture()
def staffapp(app, staffuser):
"""Return an app with an already logged in staff user."""
form = app.get(reverse('login')).forms['login']
form['username'] = staffuser.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
| import pytest
import django_webtest
from django.core.urlresolvers import reverse
from ideasbox.tests.factories import UserFactory
@pytest.fixture()
def user():
return UserFactory(short_name="Hello", password='password')
@pytest.fixture()
def staffuser():
return UserFactory(short_name="Hello", password='password', is_staff=True)
@pytest.fixture()
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
request.addfinalizer(wtm._unpatch_settings)
return django_webtest.DjangoTestApp()
@pytest.fixture()
def loggedapp(app, user):
"""Return an app with an already logged in user."""
form = app.get(reverse('login')).forms['login']
form['username'] = user.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
@pytest.fixture()
def staffapp(app, staffuser):
"""Return an app with an already logged in staff user."""
form = app.get(reverse('login')).forms['login']
form['username'] = staffuser.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
|
Change urls for scripts and css for webpack | <?php
define('ENVIRONMENT_DEVELOPMENT', 0);
define('ENVIRONMENT_HNEWS_CO', 2);
define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');
require_once(INC_PATH.'environment.php');
define('BASE_URL','/');
define('STYLES_URL', BASE_URL.'assets/');
define('SCRIPTS_URL', BASE_URL.'assets/');
define('HOME_URL', BASE_URL);
define('SHOW_URL', BASE_URL.'show/');
define('ASK_URL', BASE_URL.'ask/');
define('SETTINGS_URL', BASE_URL.'settings/');
define('COMMENTS_QUERY_URL', BASE_URL.'comments/');
define('ASK_COMMENTS_QUERY_URL', ASK_URL.'comments/');
define('SHOW_COMMENTS_QUERY_URL', SHOW_URL.'comments/');
define('PAGE_TITLE_DEFAULT', 'H News');
| <?php
define('ENVIRONMENT_DEVELOPMENT', 0);
define('ENVIRONMENT_HNEWS_CO', 2);
define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');
require_once(INC_PATH.'environment.php');
if(ENVIRONMENT_CURRENT === ENVIRONMENT_HNEWS_CO){
define('BASE_URL','http://www.hnews.co/');
}
else{
error_reporting(E_ALL);
define('BASE_URL','/h-news/public_html/');
}
define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');
define('HOME_URL', BASE_URL);
define('SHOW_URL', BASE_URL.'show/');
define('ASK_URL', BASE_URL.'ask/');
define('SETTINGS_URL', BASE_URL.'settings/');
define('COMMENTS_QUERY_URL', BASE_URL.'comments/');
define('ASK_COMMENTS_QUERY_URL', ASK_URL.'comments/');
define('SHOW_COMMENTS_QUERY_URL', SHOW_URL.'comments/');
define('PAGE_TITLE_DEFAULT', 'H News');
|
Add some docstring and the saveConfiguration method | package config
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
)
type Configuration struct {
Username string `json:"username"`
Password string
RememberMe bool `json:"remember_me"`
}
// Starts the wizard config
func configWizard() *Configuration {
configuration := new(Configuration)
fmt.Println("Welcome to gotify !\nThis wizard will help you set up gotify, follow it carefully !")
StartWizard(configuration)
err := saveConfig(configuration)
if err != nil {
log.Fatal(err)
}
return configuration
}
// Save the configuration in the config.json file
func saveConfig(configuration *Configuration) error {
config, err := json.Marshal(configuration)
if err != nil {
return err
}
err = ioutil.WriteFile("config.json", config, 0644)
return err
}
// Load the configuration from config.json or launch the wizard if it does not exists
func LoadConfig() *Configuration {
if _, err := os.Stat("config.json"); os.IsNotExist(err) {
configuration := configWizard()
return configuration
}
file, err := ioutil.ReadFile("config.json")
if err != nil {
log.Fatal(err)
}
configuration := new(Configuration)
err = json.Unmarshal(file, &configuration)
if err != nil {
log.Fatal(err)
}
return configuration
}
| package config
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
)
type Configuration struct {
Username string `json:"username"`
Password string
RememberMe bool `json:"remember_me"`
}
func configWizard() *Configuration {
configuration := new(Configuration)
fmt.Println("Welcome to gotify !\nThis wizard will help you set up gotify, follow it carefully !")
StartWizard(configuration)
return configuration
}
func LoadConfig() *Configuration {
if _, err := os.Stat("config.json"); os.IsNotExist(err) {
configuration := configWizard()
return configuration
}
file, err := ioutil.ReadFile("config.json")
if err != nil {
log.Fatal(err)
}
configuration := new(Configuration)
err = json.Unmarshal(file, &configuration)
if err != nil {
log.Fatal(err)
}
return configuration
}
|
Include a timestamp of when the data was requested from wunderground (roughly) | package com.wwsean08.WeatherReport.pojo;
import com.google.gson.annotations.SerializedName;
import com.sun.glass.ui.SystemClipboard;
/**
* Created by wwsea_000 on 12/30/2015.
*/
public class RabbitMQJson
{
@SerializedName("location")
private String location;
@SerializedName("temperature")
private float temp;
@SerializedName("icon")
private String icon;
@SerializedName("timestamp")
private long timestamp = System.currentTimeMillis();
public String getLocation()
{
return location;
}
public void setLocation(String location)
{
this.location = location;
}
public float getTemp()
{
return temp;
}
public void setTemp(float temp)
{
this.temp = temp;
}
public String getIcon()
{
return icon;
}
public void setIcon(String icon)
{
this.icon = icon;
}
}
| package com.wwsean08.WeatherReport.pojo;
import com.google.gson.annotations.SerializedName;
/**
* Created by wwsea_000 on 12/30/2015.
*/
public class RabbitMQJson
{
@SerializedName("location")
private String location;
@SerializedName("temperature")
private float temp;
@SerializedName("icon")
private String icon;
public String getLocation()
{
return location;
}
public void setLocation(String location)
{
this.location = location;
}
public float getTemp()
{
return temp;
}
public void setTemp(float temp)
{
this.temp = temp;
}
public String getIcon()
{
return icon;
}
public void setIcon(String icon)
{
this.icon = icon;
}
}
|
Correct test to provide generic type | package org.pacey.dropwizardpebble;
import com.mitchellbosecke.pebble.PebbleEngine;
import io.dropwizard.Configuration;
import io.dropwizard.lifecycle.setup.LifecycleEnvironment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class)
public class SimplePebbleEngineConfigurableTest {
@Mock
private PebbleEngine.Builder builder;
@Mock
private LifecycleEnvironment lifecycleEnvironment;
@Mock
private Configuration configuration;
@Mock
private PebbleEngine pebbleEngine;
private SimplePebbleEngineConfigurable<Configuration> simplePebbleEngineConfigurable;
@Before
public void createClassUnderTest() throws Exception {
this.simplePebbleEngineConfigurable = new SimplePebbleEngineConfigurable<>();
}
@Test
public void shouldUseTheBuilderToCreateAPebbleEngine() throws Exception {
given(builder.build()).willReturn(pebbleEngine);
PebbleEngine actual = simplePebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder);
assertThat(actual).isEqualTo(pebbleEngine);
}
}
| package org.pacey.dropwizardpebble;
import com.mitchellbosecke.pebble.PebbleEngine;
import io.dropwizard.Configuration;
import io.dropwizard.lifecycle.setup.LifecycleEnvironment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class)
public class SimplePebbleEngineConfigurableTest {
@Mock
private PebbleEngine.Builder builder;
@Mock
private LifecycleEnvironment lifecycleEnvironment;
@Mock
private Configuration configuration;
@Mock
private PebbleEngine pebbleEngine;
private SimplePebbleEngineConfigurable simplePebbleEngineConfigurable;
@Before
public void createClassUnderTest() throws Exception {
this.simplePebbleEngineConfigurable = new SimplePebbleEngineConfigurable();
}
@Test
public void shouldUseTheBuilderToCreateAPebbleEngine() throws Exception {
given(builder.build()).willReturn(pebbleEngine);
PebbleEngine actual = simplePebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder);
assertThat(actual).isEqualTo(pebbleEngine);
}
}
|
:new: Use ES6 Map as Database |
"use strict";
var
OS = require('os'),
Net = require('net'),
CPP = require('childprocess-promise');
class Main{
constructor(Port){
this.Port = Port;
this.Server = null;
this.Children = [];
this.DataBase = new Map();
}
Run(){
let NumCPUs = OS.cpus().length;
let SupportedEvents = [];
for(let Name in Main){
if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
SupportedEvents.push(Name.substr(6));
}
for(var i = 0; i < NumCPUs; ++i){
let Child = new CPP(__dirname + '/../Main.js');
SupportedEvents.forEach(function(Event){
Child.on(Event, Main['Action' + Event].bind(this, Child));
}.bind(this));
Child.Send('SupportedEvents', SupportedEvents);
this.Children.push(Child);
}
let Server = this.Server = Net.createServer();
this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
Child.Target.send('Server', Server);
}));
}
}
var Inst = new Main(9004, 4);
Inst.Run(); |
"use strict";
var
OS = require('os'),
Net = require('net'),
CPP = require('childprocess-promise');
class Main{
constructor(Port){
this.Port = Port;
this.Server = null;
this.Children = [];
}
Run(){
let NumCPUs = OS.cpus().length;
let SupportedEvents = [];
for(let Name in Main){
if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
SupportedEvents.push(Name.substr(6));
}
for(var i = 0; i < NumCPUs; ++i){
let Child = new CPP(__dirname + '/../Main.js');
SupportedEvents.forEach(function(Event){
Child.on(Event, Main['Action' + Event].bind(this, Child));
}.bind(this));
Child.Send('SupportedEvents', SupportedEvents);
this.Children.push(Child);
}
let Server = this.Server = Net.createServer();
this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
Child.Target.send('Server', Server);
}));
}
}
var Inst = new Main(9004, 4);
Inst.Run(); |
Fix for resurrect_count default value in latest migration. | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddResurrectCountToItems extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('items', function($table) {
$table->integer('resurrect_count')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('items', function($table) {
$table->dropColumn('resurrect_count');
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddResurrectCountToItems extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('items', function($table) {
$table->integer('resurrect_count');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('items', function($table) {
$table->dropColumn('resurrect_count');
});
}
}
|
Move model to this.model in constructor | 'use strict';
import backbone from 'backbone';
import _ from 'underscore';
class Person extends backbone.Model {
getFullName() {
return this.get('firstName') + ' ' + this.get('lastName');
}
}
// Using benmccormick's suggestion
// for decorators to apply properties to class
// before instantiation
// https://github.com/jashkenas/backbone/issues/3560#issuecomment-113709224
function props(value) {
return function decorator(target) {
_.extend(target.prototype, value);
}
}
@props({
events: {
'click': function() { console.log('clicked!'); }
}
})
class Hello extends backbone.View {
render() {
this.$el.html('Hello, ' + this.model.getFullName() + '.');
}
}
var myView = new Hello({el: document.getElementById('root'), model: new Person({
firstName: 'George',
lastName: 'Washington'
})});
myView.render(); | 'use strict';
import backbone from 'backbone';
import _ from 'underscore';
class Person extends backbone.Model {
getFullName() {
return this.get('firstName') + ' ' + this.get('lastName');
}
}
// Using benmccormick's suggestion
// for decorators to apply properties to class
// before instantiation
// https://github.com/jashkenas/backbone/issues/3560#issuecomment-113709224
function props(value) {
return function decorator(target) {
_.extend(target.prototype, value);
}
}
@props({
events: {
'click': function() { console.log('clicked!'); }
}
})
class Hello extends backbone.View {
initialize() {
this.person = new Person({
firstName: 'George',
lastName: 'Washington'
});
}
render() {
this.$el.html('Hello, ' + this.person.getFullName() + '.');
}
}
var myView = new Hello({el: document.getElementById('root')});
myView.render(); |
fix(scripts): Fix fs-extra breaking change :bread: | #!/usr/bin/env node
import childProcess from 'child_process';
import fs from 'fs-extra';
import moment from 'moment';
const today = new Date();
const path = `pages/posts/${moment(today).format('YYYY-MM-DD')}.md`;
/**
* Set Weekdays Locale
*/
moment.locale('jp', {weekdays: ['日', '月', '火', '水', '木', '金', '土']});
/**
* Get Post Template
*
* @return {string}
*/
function getPostTmp() {
return [
'---\n',
'title: "post"\n',
`date: "${moment(today).format('YYYY-MM-DD HH:mm:ss (dddd)')}"\n`,
'layout: post\n',
`path: "/${moment(today).format('YYYYMMDD')}/"\n`,
'---'
].join('');
}
/**
* If already been created: Open File
* else: Create & Open File
*/
fs.open(path, 'r+', err => {
if (err) {
fs.outputFile(path, getPostTmp());
}
childProcess.spawn('vim', [path], {stdio: 'inherit'});
});
| #!/usr/bin/env node
import childProcess from 'child_process';
import fs from 'fs-extra';
import moment from 'moment';
const today = new Date();
const path = `pages/posts/${moment(today).format('YYYY-MM-DD')}.md`;
/**
* Set Weekdays Locale
*/
moment.locale('jp', {weekdays: ['日', '月', '火', '水', '木', '金', '土']});
/**
* Get Post Template
*
* @return {string}
*/
function getPostTmp() {
return [
'---\n',
'title: "post"\n',
`date: "${moment(today).format('YYYY-MM-DD HH:mm:ss (dddd)')}"\n`,
'layout: post\n',
`path: "/${moment(today).format('YYYYMMDD')}/"\n`,
'---'
].join('');
}
/**
* If already been created: Open File
* else: Create & Open File
*/
fs.open(path, 'r+', err => {
if (err) {
const ws = fs.createOutputStream(path);
ws.write(getPostTmp());
}
childProcess.spawn('vim', [path], {stdio: 'inherit'});
});
|
Change default theme to Holo Light | /*
* Copyright (C) 2013 Simon Marquis (http://www.simon-marquis.fr)
*
* 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 fr.simon.marquis.preferencesmanager.model;
import fr.simon.marquis.preferencesmanager.R;
public enum AppTheme {
LIGHT(R.style.AppThemeLight, R.string.dark_theme), DARK(R.style.AppThemeDark, R.string.light_theme);
public static final AppTheme DEFAULT_THEME = LIGHT;
public final int theme;
/**
* This is the title displayed in menu, so it's normal that's inverted
*/
public final int title;
AppTheme(int theme, int title) {
this.theme = theme;
this.title = title;
}
} | /*
* Copyright (C) 2013 Simon Marquis (http://www.simon-marquis.fr)
*
* 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 fr.simon.marquis.preferencesmanager.model;
import fr.simon.marquis.preferencesmanager.R;
public enum AppTheme {
LIGHT(R.style.AppThemeLight, R.string.dark_theme), DARK(R.style.AppThemeDark, R.string.light_theme);
public static final AppTheme DEFAULT_THEME = DARK;
public final int theme;
/**
* This is the title displayed in menu, so it's normal that's inverted
*/
public final int title;
AppTheme(int theme, int title) {
this.theme = theme;
this.title = title;
}
} |
Allow subclass customizing event and action |
mi2JS.comp.add('base/Button', 'Base', '',
// component initializer function that defines constructor and adds methods to the prototype
function(proto, superProto, comp, superComp){
proto.construct = function(el, tpl, parent){
superProto.construct.call(this, el, tpl, parent);
this.lastClick = 0;
this.listen(el,"click",function(evt){
evt.stop();
});
this.listen(el,"mousedown",function(evt){
if(evt.which != 1) return; // only left click
evt.stop();
if(this.isEnabled() && this.parent.fireEvent){
var now = new Date().getTime();
if(now -this.lastClick > 300){ // one click per second
this.parent.fireEvent(this.getEvent(), {
action: this.getAction(),
button:this,
domEvent: evt,
src:this,
eventFor: 'parent'
});
this.lastClick = now;
}
}
});
};
proto.getEvent = function(){
return this.attr("event") || "action";
};
proto.getAction = function(){
return this.attr("action") || "action";
};
proto.setValue = function(value){
this.el.value = value;
};
proto.getValue = function(value){
return this.el.value;
};
});
|
mi2JS.comp.add('base/Button', 'Base', '',
// component initializer function that defines constructor and adds methods to the prototype
function(proto, superProto, comp, superComp){
proto.construct = function(el, tpl, parent){
superProto.construct.call(this, el, tpl, parent);
this.action = this.attr("action") || "action";
this.event = this.attr("event") || "action";
this.lastClick = 0;
this.listen(el,"click",function(evt){
evt.stop();
});
this.listen(el,"mousedown",function(evt){
if(evt.which != 1) return; // only left click
evt.stop();
if(this.isEnabled() && this.parent.fireEvent){
var now = new Date().getTime();
if(now -this.lastClick > 300){ // one click per second
this.parent.fireEvent(this.event, {
action: this.action,
button:this,
domEvent: evt,
src:this,
eventFor: 'parent'
});
this.lastClick = now;
}
}
});
};
proto.setValue = function(value){
this.el.value = value;
};
proto.getValue = function(value){
return this.el.value;
};
});
|
Prepare development of new version. | # -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
""" Library to implement a well-behaved Unix daemon process
This library implements PEP [no number yet], Standard daemon
process library.
A well-behaved Unix daemon process is tricky to get right, but the
required steps are much the same for every daemon program. An
instance of the `DaemonContext` holds the behaviour and configured
process environment for the program; use the instance as a context
manager to enter a daemon state.
Simple example of usage::
import daemon
from spam import do_main_program
with daemon.DaemonContext() as daemon_context:
do_main_program()
"""
from daemon import DaemonContext
version = "1.4.4"
| # -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
""" Library to implement a well-behaved Unix daemon process
This library implements PEP [no number yet], Standard daemon
process library.
A well-behaved Unix daemon process is tricky to get right, but the
required steps are much the same for every daemon program. An
instance of the `DaemonContext` holds the behaviour and configured
process environment for the program; use the instance as a context
manager to enter a daemon state.
Simple example of usage::
import daemon
from spam import do_main_program
with daemon.DaemonContext() as daemon_context:
do_main_program()
"""
from daemon import DaemonContext
version = "1.4.3"
|
Allow testing if institution is listed
This check is used to select the preferred institution for the
authenticating RA(A). | <?php
/**
* Copyright 2014 SURFnet bv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Surfnet\StepupMiddlewareClientBundle\Identity\Dto;
use Surfnet\StepupMiddlewareClientBundle\Dto\CollectionDto;
class RaListingCollection extends CollectionDto
{
protected static function createElementFromData(array $raListing)
{
return RaListing::fromData($raListing);
}
/**
* Checks if a certain institution is listed in the RA listing
* @param $institution
* @return bool
*/
public function isListed($institution)
{
/** @var RaListing $raListing */
foreach ($this->getElements() as $raListing) {
if ($raListing->institution === $institution) {
return true;
}
}
return false;
}
}
| <?php
/**
* Copyright 2014 SURFnet bv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Surfnet\StepupMiddlewareClientBundle\Identity\Dto;
use Surfnet\StepupMiddlewareClientBundle\Dto\CollectionDto;
class RaListingCollection extends CollectionDto
{
protected static function createElementFromData(array $raListing)
{
return RaListing::fromData($raListing);
}
}
|
Make the ledger type selector work | def compare_ledger_types(account, data, orm):
account_ledgers = [ledger.id for ledger in account.ledger_types]
selected_ledgers = data['form']['ledger_types']
# Store in data to avoid recomputing.
if 'ledger_type_all' not in data:
ledger_A = orm.pool.get('alternate_ledger.ledger_type').search(
orm.cursor, orm.uid, [('name', '=', 'A')]
)
data['ledger_type_all'] = (
ledger_A and
ledger_A[0] in selected_ledgers
)
catch_all = data['ledger_type_all']
if catch_all and account_ledgers == []:
return True
for selected_ledger in selected_ledgers:
if selected_ledger in account_ledgers:
return True
return False
def should_show_account(account, data):
if 'account_from' not in data['form'] or 'account_to' not in data['form']:
return True
low = data['form']['account_from']
high = data['form']['account_to']
return low <= account.code <= high
| def compare_ledger_types(account, data, orm):
# TODO alternate_ledger
return True
account_ledgers = [ledger.id for ledger in account.ledger_types]
selected_ledger = int(data['form']['ledger_type'])
# Store in data to avoid recomputing.
if 'ledger_type_all' not in data:
data['ledger_type_all'] = (
orm.pool.get('alternate_ledger.ledger_type').browse(
orm.cursor, orm.uid, selected_ledger).name == 'A')
catch_all = data['ledger_type_all']
return (selected_ledger in account_ledgers or
(catch_all and account_ledgers == []))
def should_show_account(account, data):
if 'account_from' not in data['form'] or 'account_to' not in data['form']:
return True
low = data['form']['account_from']
high = data['form']['account_to']
return low <= account.code <= high
|
Move version num to own line | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
ckanny
~~~~~~
Miscellaneous CKAN utility scripts
Examples:
literal blocks::
python example_google.py
Attributes:
module_level_variable1 (int): Module level variables may be documented in
"""
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from manager import Manager
from . import datastorer, filestorer, package, hdx
__version__ = '0.17.0'
__title__ = 'ckanny'
__author__ = 'Reuben Cummings'
__description__ = 'Miscellaneous CKAN utility scripts'
__email__ = 'reubano@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 Reuben Cummings'
manager = Manager()
manager.merge(datastorer.manager, namespace='ds')
manager.merge(filestorer.manager, namespace='fs')
manager.merge(hdx.manager, namespace='hdx')
manager.merge(package.manager, namespace='pk')
@manager.command
def ver():
"""Show ckanny version"""
print('v%s' % __version__)
if __name__ == '__main__':
manager.main()
| # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
ckanny
~~~~~~
Miscellaneous CKAN utility scripts
Examples:
literal blocks::
python example_google.py
Attributes:
module_level_variable1 (int): Module level variables may be documented in
"""
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from manager import Manager
from . import datastorer, filestorer, package, hdx
__title__ = 'ckanny'
__author__ = 'Reuben Cummings'
__description__ = 'Miscellaneous CKAN utility scripts'
__email__ = 'reubano@gmail.com'
__version__ = '0.17.0'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 Reuben Cummings'
manager = Manager()
manager.merge(datastorer.manager, namespace='ds')
manager.merge(filestorer.manager, namespace='fs')
manager.merge(hdx.manager, namespace='hdx')
manager.merge(package.manager, namespace='pk')
@manager.command
def ver():
"""Show ckanny version"""
print('v%s' % __version__)
if __name__ == '__main__':
manager.main()
|
Fix for problem with tags | package com.xamoom.android.xamoomsdk.Utils;
import java.util.List;
/**
* ListUtil to join lists of string.
* (Because TextUtil gets mocked in tests)
*/
public class ListUtil {
/**
* Will return joined list with seperator.
*
* @param list List of Strings.
* @param seperator String to seperate them.
* @return Joined list.
*/
public static String joinStringList(List<String> list, String seperator) {
if (list == null || seperator == null) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
int counter = 0;
for (String item : list) {
counter++;
sb.append("'");
sb.append(item);
sb.append("'");
if (counter != list.size()) {
sb.append(seperator);
}
}
sb.append("]");
return sb.toString();
}
}
| package com.xamoom.android.xamoomsdk.Utils;
import java.util.List;
/**
* ListUtil to join lists of string.
* (Because TextUtil gets mocked in tests)
*/
public class ListUtil {
/**
* Will return joined list with seperator.
*
* @param list List of Strings.
* @param seperator String to seperate them.
* @return Joined list.
*/
public static String joinStringList(List<String> list, String seperator) {
if (list == null || seperator == null) {
return "";
}
StringBuilder sb = new StringBuilder();
int counter = 0;
for (String item : list) {
counter++;
sb.append(item);
if (counter != list.size()) {
sb.append(seperator);
}
}
return sb.toString();
}
}
|
Update core my_controller add blank after ',' | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require APPPATH.'/libraries/REST_Controller.php';
/**
* CodeIgniter Parsing Controller
*
* url请求参数解析
*
* @package CodeIgniter
* @subpackage Core
* @category Core
* @author Fire
*/
class Parsing_Controller extends REST_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('kakou');
$this->gets = $this->_getParams();
}
/**
* 获取ulr请求参数
*
* @access private
* @return void
*/
private function _getParams()
{
$query_str = urldecode(str_replace('+', '%2B', $_SERVER["QUERY_STRING"]));
return h_convertUrlQuery($query_str);
}
} | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require APPPATH.'/libraries/REST_Controller.php';
/**
* CodeIgniter Parsing Controller
*
* url请求参数解析
*
* @package CodeIgniter
* @subpackage Core
* @category Core
* @author Fire
*/
class Parsing_Controller extends REST_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('kakou');
$this->gets = $this->_getParams();
}
/**
* 获取ulr请求参数
*
* @access private
* @return void
*/
private function _getParams()
{
$query_str = urldecode(str_replace('+','%2B',$_SERVER["QUERY_STRING"]));
return h_convertUrlQuery($query_str);
}
} |
Raise with endpoint when duplicated. | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, *urls, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
for url in urls:
self.app.add_url_rule(url, view_func=resource_func, **kw)
| # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, *urls, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError, "already set"
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
for url in urls:
self.app.add_url_rule(url, view_func=resource_func, **kw)
|
Change isSingleton as we return a new mock every time. | /*
* Copyright 2013-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.autonomy.frontend.testing.mock;
import org.springframework.beans.factory.FactoryBean;
import static org.mockito.Mockito.mock;
/**
* {@link FactoryBean} for creating Mockito mock objects. This is useful if you're using a test application context
* written in XML.
*
* If your test context uses Java configuration, there is no need to use this method.
*/
public class MocksFactory implements FactoryBean<Object> {
private Class<?> type;// the created object type
/**
* @param type The type of the mock object. This is a required property.
*/
public void setType(final Class<?> type) {
this.type = type;
}
/**
* @return A Mockito mock of the given type
* @throws Exception
*/
@Override
public Object getObject() throws Exception {
return mock(type);
}
/**
* @return The type of the mock object
*/
@Override
public Class<?> getObjectType() {
return type;
}
@Override
public boolean isSingleton() {
return false;
}
}
| /*
* Copyright 2013-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.autonomy.frontend.testing.mock;
import org.springframework.beans.factory.FactoryBean;
import static org.mockito.Mockito.mock;
/**
* {@link FactoryBean} for creating Mockito mock objects. This is useful if you're using a test application context
* written in XML.
*
* If your test context uses Java configuration, there is no need to use this method.
*/
public class MocksFactory implements FactoryBean<Object> {
private Class<?> type;// the created object type
/**
* @param type The type of the mock object. This is a required property.
*/
public void setType(final Class<?> type) {
this.type = type;
}
/**
* @return A Mockito mock of the given type
* @throws Exception
*/
@Override
public Object getObject() throws Exception {
return mock(type);
}
/**
* @return The type of the mock object
*/
@Override
public Class<?> getObjectType() {
return type;
}
@Override
public boolean isSingleton() {
return true;
}
}
|
Remove the backwards compatibility as it wasn't working for some reason. | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.3.4'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_tools
from PyFVCOM import ctd_tools
from PyFVCOM import grid_tools
from PyFVCOM import ll2utm
from PyFVCOM import ocean_tools
from PyFVCOM import stats_tools
from PyFVCOM import tide_tools
from PyFVCOM import tidal_ellipse
from PyFVCOM import process_results
from PyFVCOM import read_results
# External TAPPY now instead of my bundled version. Requires my forked version
# of TAPPY from https://github.com/pwcazenave/tappy or
# http://gitlab.em.pml.ac.uk/pica/tappy.
try:
from tappy import tappy
except ImportError:
raise ImportError('TAPPY not found. Please install it from http://gitlab.em.pml.ac.uk/pica/tappy or https://github.com/pwcazenave/tappy.')
| """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.3.4'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_tools
from PyFVCOM import ctd_tools
from PyFVCOM import grid_tools
from PyFVCOM import ll2utm
from PyFVCOM import ocean_tools
from PyFVCOM import stats_tools
from PyFVCOM import tide_tools
from PyFVCOM import tidal_ellipse
from PyFVCOM import process_results
from PyFVCOM import read_results
# External TAPPY now instead of my bundled version. Requires my forked version
# of TAPPY from https://github.com/pwcazenave/tappy or
# http://gitlab.em.pml.ac.uk/pica/tappy.
try:
from tappy import tappy
except ImportError:
raise ImportError('TAPPY not found. Please install it from http://gitlab.em.pml.ac.uk/pica/tappy or https://github.com/pwcazenave/tappy.')
# For backwards-compatibility.
process_FVCOM_results = process_results
read_FVCOM_results = read_results
|
Remove unused helpers, use lodash | /*
* pat
* https://github.com/mikko/pat
*
* Copyright (c) 2013 Mikko Koski
* Licensed under the MIT license.
*/
"use strict";
var _ = require("lodash");
function match(patterns, args) {
var matches = patterns.filter(function(pattern) {
return pattern.args.length === args.length && _.every(_.zip(pattern.args, args), function(zipped) {
var patt = zipped[0], arg = zipped[1];
return _.isFunction(patt) ? patt(arg) : _.isEqual(patt, arg);
})
});
return matches[0];
}
function pat(f) {
var patterns = [];
if(!f) {
f = function() {};
}
var wrapper = function() {
var matchedPattern = match(patterns, _.toArray(arguments));
if(matchedPattern) {
return matchedPattern.clbk.apply(this, arguments);
} else {
return f.apply(this, arguments);
}
}
wrapper.caseof = function() {
var clbk = _.last(arguments);
var args = _.initial(arguments);
patterns.push(Object.freeze({args: args, clbk: clbk}));
return wrapper;
};
return wrapper;
}
module.exports = pat;
| /*
* pat
* https://github.com/mikko/pat
*
* Copyright (c) 2013 Mikko Koski
* Licensed under the MIT license.
*/
"use strict";
var _ = require("lodash");
function last(arr) {
return arr.slice(-1)[0];
}
function initial(arr) {
return arr.slice(0, -1);
}
function toArray(args) {
return Array.prototype.slice.call(args);
}
function match(patterns, args) {
var matches = patterns.filter(function(pattern) {
return pattern.args.length === args.length && _.every(_.zip(pattern.args, args), function(zipped) {
var patt = zipped[0], arg = zipped[1];
return _.isFunction(patt) ? patt(arg) : _.isEqual(patt, arg);
})
});
return matches[0];
}
function pat(f) {
var patterns = [];
if(!f) {
f = function() {};
}
var wrapper = function() {
var matchedPattern = match(patterns, toArray(arguments));
if(matchedPattern) {
return matchedPattern.clbk.apply(this, arguments);
} else {
return f.apply(this, arguments);
}
}
wrapper.caseof = function() {
var args = toArray(arguments);
var clbk = last(args);
args = initial(args);
patterns.push(Object.freeze({args: args, clbk: clbk}));
return wrapper;
};
return wrapper;
}
module.exports = pat;
|
Set back original jshint path | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
files: [
'Gruntfile.js',
'package.json',
'js/*.js'
]
},
connect: {
www: {
options: {
base: '.',
port: 4545
}
}
},
ghost: {
dist: {
filesSrc: ['tests/integration/casperjs/*_test.js'],
options: {
args: {
baseUrl: 'http://localhost:' +
'<%= connect.www.options.port %>/'
},
direct: false,
logLevel: 'error',
printCommand: false,
printFilePaths: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-ghost');
grunt.registerTask('test', ['jshint', 'connect', 'ghost']);
};
| module.exports = function(grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
files: [
'Gruntfile.js',
'package.json',
'js/**/*.js'
]
},
connect: {
www: {
options: {
base: '.',
port: 4545
}
}
},
ghost: {
dist: {
filesSrc: ['tests/integration/casperjs/*_test.js'],
options: {
args: {
baseUrl: 'http://localhost:' +
'<%= connect.www.options.port %>/'
},
direct: false,
logLevel: 'error',
printCommand: false,
printFilePaths: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-ghost');
grunt.registerTask('test', ['jshint', 'connect', 'ghost']);
};
|
Use ActiveModelAdapter instead of RESTAdapter | //= require "lib/moment.min"
//= require "lib/jquery-2.0.3"
//= require "lib/handlebars-v1.1.2"
//= require "lib/ember"
//= require "lib/ember-data"
//= require_self
//= require "models"
//= require "views"
//= require "helpers"
//= require "./routes/authenticated_route"
//= require_tree "./controllers"
//= require_tree "./routes"
window.App = Em.Application.create({LOG_TRANSITIONS: true})
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({})
App.ApplicationAdapter = DS.ActiveModelAdapter.reopen({namespace: "api"})
App.ApplicationView = Em.View.extend({classNames: ["container"]})
App.Router.map(function() {
// login
this.route("login");
// rooms
this.resource("rooms", function() {
this.route("new");
this.resource("room", {path: "/:room_id"}, function() {
this.route("edit");
});
});
// users
// users/new
// users/:user_id
this.resource("users", function() {
this.route("new");
this.resource("user", {path: "/:user_id"}, function() {
this.route("edit");
});
});
});
| //= require "lib/moment.min"
//= require "lib/jquery-2.0.3"
//= require "lib/handlebars-v1.1.2"
//= require "lib/ember"
//= require "lib/ember-data"
//= require_self
//= require "models"
//= require "views"
//= require "helpers"
//= require "./routes/authenticated_route"
//= require_tree "./controllers"
//= require_tree "./routes"
window.App = Em.Application.create({LOG_TRANSITIONS: true})
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({})
App.ApplicationAdapter = DS.RESTAdapter.reopen({namespace: "api"})
App.ApplicationView = Em.View.extend({classNames: ["container"]})
App.Router.map(function() {
// login
this.route("login");
// rooms
this.resource("rooms", function() {
this.route("new");
this.resource("room", {path: "/:room_id"}, function() {
this.route("edit");
});
});
// users
// users/new
// users/:user_id
this.resource("users", function() {
this.route("new");
this.resource("user", {path: "/:user_id"}, function() {
this.route("edit");
});
});
});
|
Add error message if directory can't be read | <?php require_once 'config.php';
if ($env == 'production') {
error_reporting(E_ERROR | E_PARSE);
}
function print_files($url, $dir)
{
$hide = ".";
$myDirectory = opendir($dir);
if ($myDirectory) {
while ($entryName = readdir($myDirectory))
{
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
for ($index = 0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != $hide)
{
$name = $dirArray[$index];
$namehref = $dirArray[$index];
echo("
<li>
<a class='link' href='$url/$namehref'>$name</a>
</li>
");
}
}
} else {
echo("
<p class='tac'>Couldn't open the directory specified.</p>
");
}
}
| <?php require_once 'config.php';
function print_files($url, $dir)
{
$hide = ".";
$myDirectory = opendir($dir);
while ($entryName = readdir($myDirectory))
{
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
for ($index = 0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != $hide)
{
$name = $dirArray[$index];
$namehref = $dirArray[$index];
echo("
<li>
<a class='link' href='$url/$namehref'>$name</a>
</li>
");
}
}
}
|
Make the default language easily configurable | var available_langs = ['en', 'de'];
var default_lang = 'en';
// Determine language from browser variable
var lang = navigator.language || navigator.browserLanguage;
if ($.inArray(lang, available_langs) === -1) {
// Currently only the language is support (en instead of en-gb/en-us)
if (lang.length > 2 && $.inArray(lang.substr(0, 2), available_langs) >= 0) {
lang = lang.substring(0, 2);
} else {
lang = default_lang;
}
}
log('Loading language:', lang);
if (lang === default_lang) {
var i18n = {};
} else {
document.write('<script src="js/lang/' + lang + '.js"><\/script>');
}
/**
* Get the translated version of key. Can also be used as $._(key).
*
* @param {String} The string to be translated
* @returns {String} The translated string
*/
function gettext(key) {
if (i18n[key] && i18n[key].length > 0) {
return i18n[key];
} else {
lang === default_lang || log('Unknown translation key:', key);
return key;
}
}
$.extend({ '_': gettext });
| var available_langs = ['en', 'de'];
// Determine language from browser variable
var lang = navigator.language || navigator.browserLanguage;
if ($.inArray(lang, available_langs) === -1) {
// Currently only the language is support (en instead of en-gb/en-us)
if (lang.length > 2 && $.inArray(lang.substr(0, 2), available_langs) >= 0) {
lang = lang.substring(0, 2);
} else {
lang = 'en';
}
}
log('Loading language:', lang);
if (lang === 'en') {
var i18n = {};
} else {
document.write('<script src="js/lang/' + lang + '.js"><\/script>');
}
/**
* Get the translated version of key. Can also be used as $._(key).
*
* @param {String} The string to be translated
* @returns {String} The translated string
*/
function gettext(key) {
if (i18n[key] && i18n[key].length > 0) {
return i18n[key];
} else {
lang === 'en' || log('Unknown translation key:', key);
return key;
}
}
$.extend({ '_': gettext });
|
Fix bug with old dates | <?php
/*
* This file is part of the Bukashk0zzzTimestampTypeBundle
*
* (c) Denis Golubovskiy <bukashk0zzz@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Bukashk0zzz\TimestampTypeBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception;
/**
* Class TimestampToDateTimeTransformer
* @author Denis Golubovskiy <bukashk0zzz@gmail.com>
*/
class TimestampToDateTimeTransformer implements DataTransformerInterface
{
/**
* @param mixed $value
* @return int|mixed
*/
public function transform($value)
{
if ($value instanceof \DateTime) {
return $value->getTimestamp();
}
return $value;
}
/**
* @param mixed $value
* @return \DateTime|null
*/
public function reverseTransform($value)
{
if ($value) {
$date = new \DateTime();
return $date->setTimestamp($value);
}
return null;
}
}
| <?php
/*
* This file is part of the Bukashk0zzzTimestampTypeBundle
*
* (c) Denis Golubovskiy <bukashk0zzz@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Bukashk0zzz\TimestampTypeBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception;
/**
* Class TimestampToDateTimeTransformer
* @author Denis Golubovskiy <bukashk0zzz@gmail.com>
*/
class TimestampToDateTimeTransformer implements DataTransformerInterface
{
/**
* @param mixed $value
* @return int|mixed
*/
public function transform($value)
{
if ($value instanceof \DateTime) {
return $value->getTimestamp();
}
return $value;
}
/**
* @param mixed $value
* @return \DateTime|null
*/
public function reverseTransform($value)
{
if ($value) {
return new \DateTime('@'.$value);
}
return null;
}
}
|
Rename doi function, add keyword options | # -*- coding: utf-8 -*-
"""Tools for downloading bibtex files from digital object identifiers."""
import bibpy
try:
from urllib.request import Request, urlopen
except ImportError:
from urllib2 import Request, urlopen
def retrieve(doi, source='http://dx.doi.org/{0}', raw=False, **options):
"""Download a bibtex file specified by a digital object identifier.
The source is a URL containing a single format specifier which is where the
requested doi should appear.
By default, the bibtex string from the doi is parsed by bibpy. Specify
raw=True to get the raw bibtex string instead.
"""
req = Request(source.format(doi))
req.add_header('accept', 'application/x-bibtex')
try:
handle = urlopen(req)
contents = handle.read()
if raw:
return contents
else:
return bibpy.read_string(contents, **options).entries[0]
finally:
handle.close()
| # -*- coding: utf-8 -*-
"""Tools for downloading bibtex files from digital object identifiers."""
import bibpy
try:
from urllib.request import Request, urlopen
except ImportError:
from urllib2 import Request, urlopen
def download(doi, source='http://dx.doi.org/{0}', raw=False):
"""Download a bibtex file specified by a digital object identifier.
The source is a URL containing a single format specifier which is where the
requested doi should appear.
By default, the bibtex string from the doi is parsed by bibpy. Specify
raw=True to get the raw bibtex string instead.
"""
req = Request(source.format(doi))
req.add_header('accept', 'application/x-bibtex')
try:
handle = urlopen(req)
contents = handle.read()
return contents if raw else bibpy.read_string(contents).entries[0]
finally:
handle.close()
|
Support responseOk for custom errors | export function responseOk(response, throwError=Error) {
if(response.status >= 200 && response.status < 300) {
return response
} else {
throw new throwError(response.statusText)
}
}
export function responseToJson(response) {
return response.json()
}
// Store array with mappings from numerical to hex representation
const _hexMap = Array.from(Array(0xff), (_, i) => (i + 0x100).toString(16).substr(1))
export function generateUUID() {
let rand = new Uint8Array(16)
crypto.getRandomValues(rand)
rand[6] = (rand[6] & 0x0f) | 0x40;
rand[8] = (rand[8] & 0x3f) | 0x80;
return _hexMap[rand[0]] + _hexMap[rand[1]] +
_hexMap[rand[2]] + _hexMap[rand[3]] + '-' +
_hexMap[rand[4]] + _hexMap[rand[5]] + '-' +
_hexMap[rand[6]] + _hexMap[rand[7]] + '-' +
_hexMap[rand[8]] + _hexMap[rand[9]] + '-' +
_hexMap[rand[10]] + _hexMap[rand[11]] +
_hexMap[rand[12]] + _hexMap[rand[13]] +
_hexMap[rand[14]] + _hexMap[rand[15]];
}
| export function responseOk(response) {
if(response.status >= 200 && response.status < 300) {
return response
} else {
throw new Error(response.statusText)
}
}
export function responseToJson(response) {
return response.json()
}
// Store array with mappings from numerical to hex representation
const _hexMap = Array.from(Array(0xff), (_, i) => (i + 0x100).toString(16).substr(1))
export function generateUUID() {
let rand = new Uint8Array(16)
crypto.getRandomValues(rand)
rand[6] = (rand[6] & 0x0f) | 0x40;
rand[8] = (rand[8] & 0x3f) | 0x80;
return _hexMap[rand[0]] + _hexMap[rand[1]] +
_hexMap[rand[2]] + _hexMap[rand[3]] + '-' +
_hexMap[rand[4]] + _hexMap[rand[5]] + '-' +
_hexMap[rand[6]] + _hexMap[rand[7]] + '-' +
_hexMap[rand[8]] + _hexMap[rand[9]] + '-' +
_hexMap[rand[10]] + _hexMap[rand[11]] +
_hexMap[rand[12]] + _hexMap[rand[13]] +
_hexMap[rand[14]] + _hexMap[rand[15]];
}
|
Add profile scope to google auth | import EmberObject from "@ember/object";
import config from "fakturama/config/environment";
const {
APP: {
FIREBASE,
FIREBASE: { projectId }
}
} = config;
const { firebase } = window;
const app = firebase.initializeApp(FIREBASE);
function delegateMethod(name) {
return function() {
return this.get("content")[name](...arguments);
};
}
export default EmberObject.extend({
init() {
this._super(...arguments);
this.set("content", app.auth(projectId));
this.set("googleProvider", new firebase.auth.GoogleAuthProvider());
},
onAuthStateChanged: delegateMethod("onAuthStateChanged"),
signInAnonymously: delegateMethod("signInAnonymously"),
signInWithGoogle() {
const content = this.get("content");
const provider = this.get("googleProvider");
provider.addScope("email");
provider.addScope("profile");
return content.signInWithPopup(provider);
},
signOut: delegateMethod("signOut")
});
| import EmberObject from "@ember/object";
import config from "fakturama/config/environment";
const { APP: { FIREBASE, FIREBASE: { projectId } } } = config;
const { firebase } = window;
const app = firebase.initializeApp(FIREBASE);
function delegateMethod(name) {
return function() {
return this.get("content")[name](...arguments);
};
}
export default EmberObject.extend({
init() {
this._super(...arguments);
this.set("content", app.auth(projectId));
this.set("googleProvider", new firebase.auth.GoogleAuthProvider());
},
onAuthStateChanged: delegateMethod("onAuthStateChanged"),
signInAnonymously: delegateMethod("signInAnonymously"),
signInWithGoogle() {
const content = this.get("content")
const provider = this.get("googleProvider")
provider.addScope("email");
return content.signInWithPopup(provider)
},
signOut: delegateMethod("signOut")
});
|
Support pattern provided on relation | 'use strict';
var d = require('es5-ext/lib/Object/descriptor')
, Db = require('dbjs')
, DOMInput = require('../_controls/input')
, StringLine = require('dbjs/lib/objects')._get('StringLine')
, Input;
require('../');
Input = function (document, ns/*, options*/) {
var options = Object(arguments[2]), pattern;
DOMInput.call(this, document, ns, options);
this.dom.setAttribute('type', 'text');
if (options.relation && options.relation.__pattern.__value) {
pattern = Db.RegExp(options.relation.__pattern.__value);
}
if (!pattern) pattern = ns.pattern;
this.dom.setAttribute('pattern', pattern.source.slice(1, -1));
if (ns.max) this.dom.setAttribute('maxlength', ns.max);
this.dom.addEventListener('input', this.onchange.bind(this), false);
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
knownAttributes: d({ class: true, id: true, required: true, style: true,
placeholder: true })
});
module.exports = Object.defineProperty(StringLine, 'DOMInput', d(Input));
| 'use strict';
var d = require('es5-ext/lib/Object/descriptor')
, DOMInput = require('../_controls/input')
, StringLine = require('dbjs/lib/objects')._get('StringLine')
, Input;
require('../');
Input = function (document, ns/*, options*/) {
DOMInput.apply(this, arguments);
this.dom.setAttribute('type', 'text');
if (ns.pattern) {
this.dom.setAttribute('pattern', ns.pattern.source.slice(1, -1));
}
if (ns.max) this.dom.setAttribute('maxlength', ns.max);
this.dom.addEventListener('input', this.onchange.bind(this), false);
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
knownAttributes: d({ class: true, id: true, required: true, style: true,
placeholder: true })
});
module.exports = Object.defineProperty(StringLine, 'DOMInput', d(Input));
|
Add requests as a dependency | from __future__ import absolute_import
from setuptools import setup, find_packages
setup(
name='flyingcloud',
version='0.1.9',
description='Build Docker images using SaltStack',
author='CookBrite, Inc.',
author_email='flyingcloud-admin@cookbrite.com',
license='Apache Software License 2.0',
url='https://github.com/cookbrite/flyingcloud',
packages=find_packages(exclude='tests'),
install_requires=['docker-py', 'requests', 'sh', 'six'],
classifiers=['Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Topic :: Utilities',
'Topic :: System :: Clustering',
'Topic :: System :: Distributed Computing'],
long_description=open('README.rst').read(),
keywords="docker saltstack devops automation",
)
| from __future__ import absolute_import
from setuptools import setup, find_packages
setup(
name='flyingcloud',
version='0.1.9',
description='Build Docker images using SaltStack',
author='CookBrite, Inc.',
author_email='flyingcloud-admin@cookbrite.com',
license='Apache Software License 2.0',
url='https://github.com/cookbrite/flyingcloud',
packages=find_packages(exclude='tests'),
install_requires=['docker-py', 'sh', 'six'],
classifiers=['Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Topic :: Utilities',
'Topic :: System :: Clustering',
'Topic :: System :: Distributed Computing'],
long_description=open('README.rst').read(),
keywords="docker saltstack devops automation",
)
|
Add missing models to __all__ list | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Import all of the models from submodules and thread them together.
"""
from calaccess_processed.models.campaign.entities import (
Candidate,
CandidateCommittee,
)
from calaccess_processed.models.campaign.filings import (
Form460,
Form460Version,
Schedule497,
Schedule497Version,
)
from calaccess_processed.models.campaign.contributions import (
MonetaryContribution,
MonetaryContributionVersion,
NonMonetaryContribution,
NonMonetaryContributionVersion,
LateContributionReceived,
LateContributionReceivedVersion,
LateContributionMade,
LateContributionMadeVersion,
)
from calaccess_processed.models.common import (
FilerIDValue,
FilingIDValue,
)
from calaccess_processed.models.tracking import (
ProcessedDataVersion,
ProcessedDataFile,
)
__all__ = (
'ProcessedDataVersion',
'ProcessedDataFile',
'Candidate',
'CandidateCommittee',
'Form460',
'Form460Version',
'Schedule497',
'Schedule497Version',
'MonetaryContribution',
'MonetaryContributionVersion',
'NonMonetaryContribution',
'NonMonetaryContributionVersion',
'LateContributionReceived',
'LateContributionReceivedVersion',
'LateContributionMade',
'LateContributionMadeVersion',
'FilerIDValue',
'FilingIDValue',
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Import all of the models from submodules and thread them together.
"""
from calaccess_processed.models.campaign.entities import (
Candidate,
CandidateCommittee,
)
from calaccess_processed.models.campaign.filings import (
Form460,
Form460Version,
Schedule497,
Schedule497Version,
)
from calaccess_processed.models.campaign.contributions import (
MonetaryContribution,
MonetaryContributionVersion,
NonMonetaryContribution,
NonMonetaryContributionVersion,
LateContributionReceived,
LateContributionReceivedVersion,
LateContributionMade,
LateContributionMadeVersion,
)
from calaccess_processed.models.common import (
FilerIDValue,
FilingIDValue,
)
from calaccess_processed.models.tracking import (
ProcessedDataVersion,
ProcessedDataFile,
)
__all__ = (
'ProcessedDataVersion',
'ProcessedDataFile',
'Candidate',
'CandidateCommittee',
'Form460',
'Form460Version',
'Schedule497',
'Schedule497Version',
'LateContributionReceived',
'LateContributionReceivedVersion',
'LateContributionMade',
'LateContributionMadeVersion',
'FilerIDValue',
'FilingIDValue',
)
|
Enable filtering over the published field
Tastypie requires that we define a list of fields that can be used
for filtering; add the "published" to this list so we can query pinry
for the list of images created after some date. | from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization
from django.contrib.auth.models import User
from pinry.pins.models import Pin
class PinResource(ModelResource): # pylint: disable-msg=R0904
thumbnail = fields.CharField(readonly=True)
class Meta:
queryset = Pin.objects.all()
resource_name = 'pin'
include_resource_uri = False
filtering = {
'published': ['gt'],
}
def dehydrate_thumbnail(self, bundle):
pin = Pin.objects.only('image').get(pk=bundle.data['id'])
return pin.image.url_200x1000
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
excludes = ['email', 'password', 'is_superuser']
# Add it here.
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
| from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization
from django.contrib.auth.models import User
from pinry.pins.models import Pin
class PinResource(ModelResource): # pylint: disable-msg=R0904
thumbnail = fields.CharField(readonly=True)
class Meta:
queryset = Pin.objects.all()
resource_name = 'pin'
include_resource_uri = False
def dehydrate_thumbnail(self, bundle):
pin = Pin.objects.only('image').get(pk=bundle.data['id'])
return pin.image.url_200x1000
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
excludes = ['email', 'password', 'is_superuser']
# Add it here.
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
|
Fix goof in classification fix | from pax import plugin, units
class AdHocClassification(plugin.TransformPlugin):
def transform_event(self, event):
for peak in event.peaks:
# Don't work on noise and lone_hit
if peak.type in ('noise', 'lone_hit'):
continue
if peak.range_90p_area < 150 * units.ns:
peak.type = 's1'
elif peak.range_90p_area > 200 * units.ns:
if peak.area > 5:
peak.type = 's2'
else:
peak.type = 'coincidence'
return event
| from pax import plugin, units
class AdHocClassification(plugin.TransformPlugin):
def transform_event(self, event):
for peak in event.peaks:
# Don't work on noise and lone_hit
if peak.type in ('unknown', 'lone_hit'):
continue
if peak.range_90p_area < 150 * units.ns:
peak.type = 's1'
elif peak.range_90p_area > 200 * units.ns:
if peak.area > 5:
peak.type = 's2'
else:
peak.type = 'coincidence'
return event
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.