text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Use pluginLoader in contextual extension
If a contextual module is defined passing a string as the `definer`
parameter, the `pluginLoader` needs to be used to dynamically load the
`definer` function; otherwise steal-tools won't build the app.
Closes #952 | addStealExtension(function (loader) {
loader._contextualModules = {};
loader.setContextual = function(moduleName, definer){
this._contextualModules[moduleName] = definer;
};
var normalize = loader.normalize;
loader.normalize = function(name, parentName){
var loader = this;
var pluginLoader = loader.pluginLoader || loader;
if (parentName) {
var definer = this._contextualModules[name];
// See if `name` is a contextual module
if (definer) {
name = name + '/' + parentName;
if(!loader.has(name)) {
// `definer` could be a function or could be a moduleName
if (typeof definer === 'string') {
definer = pluginLoader['import'](definer);
}
return Promise.resolve(definer)
.then(function(definer) {
if (definer['default']) {
definer = definer['default'];
}
var definePromise = Promise.resolve(
definer.call(loader, parentName)
);
return definePromise;
})
.then(function(moduleDef){
loader.set(name, loader.newModule(moduleDef));
return name;
});
}
return Promise.resolve(name);
}
}
return normalize.apply(this, arguments);
};
});
| addStealExtension(function (loader) {
loader._contextualModules = {};
loader.setContextual = function(moduleName, definer){
this._contextualModules[moduleName] = definer;
};
var normalize = loader.normalize;
loader.normalize = function(name, parentName){
var loader = this;
if (parentName) {
var definer = this._contextualModules[name];
// See if `name` is a contextual module
if (definer) {
name = name + '/' + parentName;
if(!loader.has(name)) {
// `definer` could be a function or could be a moduleName
if (typeof definer === 'string') {
definer = loader['import'](definer);
}
return Promise.resolve(definer)
.then(function(definer) {
if (definer['default']) {
definer = definer['default'];
}
var definePromise = Promise.resolve(
definer.call(loader, parentName)
);
return definePromise;
})
.then(function(moduleDef){
loader.set(name, loader.newModule(moduleDef));
return name;
});
}
return Promise.resolve(name);
}
}
return normalize.apply(this, arguments);
};
}); |
Fix bug with the laravel4 paginator | <?php
namespace Michaeljennings\Carpenter\Pagination\Laravel4;
use Michaeljennings\Carpenter\Contracts\Paginator as PaginatorContract;
class Illuminate implements PaginatorContract
{
/**
* An instance of the IOC container.
*
* @var mixed
*/
protected $app;
/**
* The illuminate paginator.
*
* @var mixed
*/
protected $paginator;
public function __construct($app)
{
$this->app = $app;
}
/**
* Create a new paginator.
*
* @param string|integer $total
* @param string|integer $perPage
* @param string $tableKey
* @return $this
*/
public function make($total, $perPage, $tableKey)
{
$this->app['paginator']->setPageName($tableKey);
$this->paginator = $this->app['paginator']->make([], $total, $perPage);
return $this;
}
/**
* Get the pagination links.
*
* @return string
*/
public function links()
{
return $this->paginator->links();
}
/**
* Get the current page.
*
* @return integer|string
*/
public function currentPage()
{
return $this->paginator->getCurrentPage();
}
} | <?php
namespace Michaeljennings\Carpenter\Pagination\Laravel4;
use Michaeljennings\Carpenter\Contracts\Paginator as PaginatorContract;
class Illuminate implements PaginatorContract
{
/**
* An instance of the IOC container.
*
* @var mixed
*/
protected $app;
/**
* The illuminate paginator.
*
* @var mixed
*/
protected $paginator;
public function __construct($app)
{
$this->app = $app;
}
/**
* Create a new paginator.
*
* @param string|integer $total
* @param string|integer $perPage
* @param string $tableKey
* @return $this
*/
public function make($total, $perPage, $tableKey)
{
$this->paginator = $this->app['paginator']->make([], $total, $perPage);
$this->paginator->setPageName($tableKey);
return $this;
}
/**
* Get the pagination links.
*
* @return string
*/
public function links()
{
return $this->paginator->links();
}
/**
* Get the current page.
*
* @return integer|string
*/
public function currentPage()
{
return $this->paginator->getCurrentPage();
}
} |
Move to using methods that are not deprecated and unescape the hash
when using it as default value. | import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = window.location.hash.length > 0 ?
decodeURI(window.location.hash.substr(1)) :
`Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
let savedLog = console.log.bind(console);
console.log = function (...args) {
print(...args);
savedLog(...args);
};
function print(...args) {
outputHtmlNode.innerHTML += `<div>${args.join(" ")}</div>`;
}
function runParser() {
outputHtmlNode.innerHTML = "";
try {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.style.borderColor = "black";
print(parsedHtml.replace(/</g, "<").replace(/>/g, ">"));
} catch (error) {
outputHtmlNode.style.borderColor = "red";
print(error);
}
window.location.hash = `#${encodeURI(inputNode.value)}`;
}
inputNode.addEventListener("input", runParser);
runParser();
}); | import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = window.location.hash.length > 0 ?
window.location.hash.substr(1) :
`Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
let savedLog = console.log.bind(console);
console.log = function (...args) {
print(...args);
savedLog(...args);
};
function print(...args) {
outputHtmlNode.innerHTML += `<div>${args.join(" ")}</div>`;
}
function runParser() {
outputHtmlNode.innerHTML = "";
try {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.style.borderColor = "black";
print(parsedHtml.replace(/</g, "<").replace(/>/g, ">"));
} catch (error) {
outputHtmlNode.style.borderColor = "red";
print(error);
}
window.location.hash = `#${window.escape(inputNode.value)}`;
}
inputNode.addEventListener("input", runParser);
runParser();
}); |
Make preprocess testset argument accessible through API | from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
| from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu',
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=False)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
Fix loading issue for reactions | package dev.nincodedo.ninbot.components.reaction;
import lombok.Data;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import java.util.List;
@Data
class ReactionResponse {
protected String response;
protected String target;
protected List<String> responses;
protected ReactionMatchType reactionMatchType;
public ReactionResponse() {
}
public ReactionResponse(ReactionResponse reactionResponse) {
this.response = reactionResponse.response;
this.target = reactionResponse.target;
this.responses = reactionResponse.responses;
this.reactionMatchType = reactionResponse.reactionMatchType;
}
void react(Message message, MessageChannel channel) {
//NO-OP
}
boolean canRespond(MessageReceivedEvent event) {
return switch (reactionMatchType) {
case EXACT -> getTarget()
.equalsIgnoreCase(event.getMessage().getContentStripped());
case CONTAINS -> event.getMessage()
.getContentStripped()
.toLowerCase()
.contains(getTarget()
.toLowerCase());
case REGEX -> event.getMessage().getContentStripped().matches(getTarget());
};
}
}
| package dev.nincodedo.ninbot.components.reaction;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import java.util.List;
@NoArgsConstructor
@Data
abstract class ReactionResponse {
protected String response;
protected String target;
protected List<String> responses;
protected ReactionMatchType reactionMatchType;
public ReactionResponse(ReactionResponse reactionResponse) {
this.response = reactionResponse.response;
this.target = reactionResponse.target;
this.responses = reactionResponse.responses;
this.reactionMatchType = reactionResponse.reactionMatchType;
}
abstract void react(Message message, MessageChannel channel);
boolean canRespond(MessageReceivedEvent event) {
return switch (reactionMatchType) {
case EXACT -> getTarget()
.equalsIgnoreCase(event.getMessage().getContentStripped());
case CONTAINS -> event.getMessage()
.getContentStripped()
.toLowerCase()
.contains(getTarget()
.toLowerCase());
case REGEX -> event.getMessage().getContentStripped().matches(getTarget());
};
}
}
|
Add get_absolute_url on notification model | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable
from opps.db import Db
NOTIFICATION_TYPE = (
(u'json', _(u'JSON')),
(u'text', _(u'Text')),
(u'html', _(u'HTML')),
)
class Notification(Publishable):
container = models.ForeignKey('containers.Container')
action = models.CharField(_('Action'), max_length=75,
default="message")
type = models.CharField(_('Type'), max_length=10,
choices=NOTIFICATION_TYPE,
default='json')
message = models.TextField(_('Message'))
def save(self, *args, **kwargs):
super(Notification, self).save(*args, **kwargs)
_db = Db(self.container.get_absolute_url(),
self.container.id)
message = self.message
if self.type == "json":
message = json.dumps(self.message)
_db.publish(json.dumps({
"action": self.action,
"id": self.id,
"published": self.published,
"date": self.date_available.strftime("%D %T"),
"message": message}))
def get_absolute_url(self):
return u"/{}/{}.server".format(self.container.channel_long_slug,
self.container.slug)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable
from opps.db import Db
NOTIFICATION_TYPE = (
(u'json', _(u'JSON')),
(u'text', _(u'Text')),
(u'html', _(u'HTML')),
)
class Notification(Publishable):
container = models.ForeignKey('containers.Container')
action = models.CharField(_('Action'), max_length=75,
default="message")
type = models.CharField(_('Type'), max_length=10,
choices=NOTIFICATION_TYPE,
default='json')
message = models.TextField(_('Message'))
def save(self, *args, **kwargs):
super(Notification, self).save(*args, **kwargs)
_db = Db(self.container.get_absolute_url(),
self.container.id)
message = self.message
if self.type == "json":
message = json.dumps(self.message)
_db.publish(json.dumps({
"action": self.action,
"id": self.id,
"published": self.published,
"date": self.date_available.strftime("%D %T"),
"message": message}))
|
Fix issue with loading of files due to wrong filepath | import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
/**
* Created by TUDelft SID on 1-5-2017.
*/
public class MenuController {
@FXML
private AnchorPane anchorPane;
@FXML
private Canvas canvas;
private GraphicsContext gc;
private GraphDrawer drawer;
@FXML
public void initialize() {
gc = canvas.getGraphicsContext2D();
}
@FXML
public void openFileClicked() {
Stage stage = (Stage) anchorPane.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
//fileChooser.setInitialDirectory(this.getClass().getResource("/resources").toString());
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
try {
GfaParser parser = new GfaParser();
System.out.println("src/main/resources/" + file.getName());
SequenceGraph graph = graph = parser.parse(file.getAbsolutePath());
drawer = new GraphDrawer(graph, gc);
drawer.drawShapes();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
/**
* Created by TUDelft SID on 1-5-2017.
*/
public class MenuController {
@FXML
private AnchorPane anchorPane;
@FXML
private Canvas canvas;
private GraphicsContext gc;
private GraphDrawer drawer;
@FXML
public void initialize() {
gc = canvas.getGraphicsContext2D();
}
@FXML
public void openFileClicked() {
Stage stage = (Stage) anchorPane.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
//fileChooser.setInitialDirectory(this.getClass().getResource("/resources").toString());
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
try {
GfaParser parser = new GfaParser();
System.out.println("src/main/resources/" + file.getName());
SequenceGraph graph = graph = parser.parse("src/main/resources/" + file.getName());
drawer = new GraphDrawer(graph, gc);
drawer.drawShapes();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
Add secret check and remove response code. | var express = require('express');
var router = express.Router();
var request = require('request');
router.get('/', function(req, res) {
if (req.query.secret !== process.env.SECRET) {
res.sendStatus(404).end();
} else {
request({
url: 'https://status.heroku.com/api/v3/current-status',
method: 'GET'
}, function(error, response, body) {
var result = JSON.parse(body);
var color;
if (result.status.Production === 'green' && result.status.Development === 'green') {
color = 'good';
} else {
color = 'danger';
}
var payload = {
channel: '#hackers',
username: 'Heroku',
icon_emoji: ':heroku:',
attachments: [{
fallback: 'Heroku Status',
color: color,
title: 'Heroku Status',
title_link: 'https://status.heroku.com/',
fields: [{
title: 'Production',
value: result.status.Production === 'green' ? 'Operational' : 'Experiencing issues'
}, {
title: 'Development',
value: result.status.Development === 'green' ? 'Operational' : 'Experiencing issues'
}, {
title: 'Issues',
value: result.issues.length ? issues : 'No issues'
}]
}]
};
request({
url: process.env.URL,
method: 'POST',
body: JSON.stringify(payload)
}, function() {
res.end();
});
});
}
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var request = require('request');
router.get('/', function(req, res) {
request({
url: 'https://status.heroku.com/api/v3/current-status',
method: 'GET'
}, function(error, response, body) {
var result = JSON.parse(body);
var color;
if (result.status.Production === 'green' && result.status.Development === 'green') {
color = 'good';
} else {
color = 'danger';
}
var payload = {
channel: '#hackers',
username: 'Heroku',
icon_emoji: ':heroku:',
attachments: [{
fallback: 'Heroku Status',
color: color,
title: 'Heroku Status',
title_link: 'https://status.heroku.com/',
fields: [{
title: 'Production',
value: result.status.Production === 'green' ? 'Operational' : 'Experiencing issues',
short: 'true'
}, {
title: 'Development',
value: result.status.Development === 'green' ? 'Operational' : 'Experiencing issues',
short: 'true'
}, {
title: 'Issues',
value: result.issues.length ? issues : 'No issues'
}]
}]
};
request({
url: process.env.URL,
method: 'POST',
body: JSON.stringify(payload)
}, function() {
res.sendStatus(200).end();
});
});
});
module.exports = router;
|
Add branding and spanish wording | <html>
<head>
<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<style>
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
.brand {
font-weight: bold;
font-size: 24px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Be right back.</div>
<div class="title">Enseguida volvemos.</div>
<div class="brand">timegrid.io</div>
</div>
</div>
</body>
</html>
| <html>
<head>
<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<style>
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Be right back.</div>
</div>
</div>
</body>
</html>
|
Fix tests related to result collection | from kernel.kernel import Kernel
from modules import AbstractModule
from kernel.config import Config
from kernel.result import Result
from kernel.module_chain import ModuleChain
import glob
import os
import json
def test_get_module():
mod = Kernel.get_module('modules', 'file.Extension')
assert isinstance(mod, AbstractModule)
try:
mod = Kernel.get_module('modules', 'not.Exists')
except SystemExit:
assert True
try:
mod = Kernel.get_module('tests.modules', 'file.WrongModule')
except KeyError:
assert True
def test_main_exec_search():
config = Config('./examples/phone_msg.yml', './tests/modules/file/extension_mocks')
result = Result(config)
Kernel.result = result
mc = ModuleChain()
mc.id = "abcetc"
mc.files = [
'./tests/modules/file/extension_mocks/database.sqlite',
'./tests/modules/file/extension_mocks/database2.db'
]
module = Kernel.get_module('modules', 'file.Extension')
module.files = mc.files
module.args = ['db']
mc.modules.append(module)
Kernel.exec_search([mc])
data = Kernel.result.result[0]
assert data['module_chain_id'] == 'abcetc'
assert len(data['modules']) == 1
assert data['modules'][0]['mod'] == 'file.Extension'
assert data['modules'][0]['files_count'] == 1
assert len(data['modules'][0]['files']) == 1
| from kernel.kernel import Kernel
from modules import AbstractModule
from kernel.module_chain import ModuleChain
import glob
import os
import json
def test_get_module():
mod = Kernel.get_module('modules', 'file.Extension')
assert isinstance(mod, AbstractModule)
try:
mod = Kernel.get_module('modules', 'not.Exists')
except SystemExit:
assert True
try:
mod = Kernel.get_module('tests.modules', 'file.WrongModule')
except KeyError:
assert True
def test_main_exec_search():
remove_files = glob.glob('abcetc_*.json')
for rf in remove_files:
os.remove(rf)
mc = ModuleChain()
mc.id = "abcetc"
mc.files = [
'./tests/modules/file/extension_mocks/database.sqlite',
'./tests/modules/file/extension_mocks/database2.db'
]
module = Kernel.get_module('modules', 'file.Extension')
module.files = mc.files
module.args = ['db']
mc.modules.append(module)
Kernel.exec_search([mc])
files = glob.glob('abcetc_*.json')
assert len(files) == 1
with open(files[0], 'r') as file_data:
data = json.load(file_data)
assert data['module_chain_id'] == 'abcetc'
assert len(data['modules']) == 1
assert data['modules'][0]['mod'] == 'file.Extension'
assert data['modules'][0]['files_count'] == 1
assert len(data['modules'][0]['files']) == 1
|
Change discover page layout a little | import React, { Component } from 'react';
import {
View,
ScrollView,
} from 'react-native';
import _ from 'lodash'
import { observer } from 'mobx-react/native'
import { BarMapView } from './BarMap.js'
import { BarCard } from './BarCard.js'
import { DownloadResultView } from './HTTP.js'
import { T } from './AppText.js'
import { store } from './Store.js'
import { config } from './Config.js'
@observer export class DiscoverPage extends DownloadResultView {
constructor(props) {
super(props, "Error downloading list of bars:")
}
refreshPage = store.initialize
getDownloadResult = () => store.barList
renderNotStarted = () => <View />
saveScrollView = (scrollview) => {
store.discoverScrollView = scrollview
}
renderFinished = (barList) => {
return (
<ScrollView style={{flex: 1}} ref={this.saveScrollView}>
<BarMapView />
<View style={{flex: 1}}>
{/*
<T style={
{ marginLeft: 10
, fontSize: 20
, color: config.theme.primary.medium
}}>
Nearby Bars
</T>
*/}
{barList.slice(0, 3).map((bar, i) => <BarCard key={i} bar={bar} />)}
</View>
</ScrollView>
)
}
}
| import React, { Component } from 'react';
import {
View,
ScrollView,
} from 'react-native';
import _ from 'lodash'
import { observer } from 'mobx-react/native'
import { BarMapView } from './BarMap.js'
import { BarCard } from './BarCard.js'
import { DownloadResultView } from './HTTP.js'
import { T } from './AppText.js'
import { store } from './Store.js'
import { config } from './Config.js'
@observer export class DiscoverPage extends DownloadResultView {
constructor(props) {
super(props, "Error downloading list of bars:")
}
refreshPage = store.initialize
getDownloadResult = () => store.barList
renderNotStarted = () => <View />
renderFinished = (barList) => {
return <ScrollView style={{flex: 1}}>
<BarMapView />
<View style={{flex: 1}}>
{/*
<T style={
{ marginLeft: 10
, fontSize: 20
, color: config.theme.primary.medium
}}>
Nearby Bars
</T>
*/}
{barList.slice(0, 3).map((bar, i) => <BarCard key={i} bar={bar} />)}
</View>
</ScrollView>
}
}
|
Fix overflow menu reopening immediately after selecting an item
Was caused by mouseout toggling, instead of closing | import React, { Component, PropTypes, cloneElement } from 'react';
import styles from './OverFlowMenu.module.scss';
export class OverflowItem extends Component {
onClick(e) {
this.props.onClick(e);
this.props.onClicked();
}
render() {
return (
<div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}>
{ this.props.children }
</div>
);
}
}
export default class OverFlowMenu extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
toggle() {
this.setOpen(!this.isOpen());
}
isOpen() {
return this.state.open;
}
setOpen(openOrClosed) {
this.setState({open: openOrClosed});
}
onItemClicked() {
this.toggle();
}
onMouseLeave() {
this.setOpen(false);
}
render() {
const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' ');
return (
<div className={ cn }>
<button className={styles.btn} onClick={this.toggle.bind(this)}>
<i className="fa small fa-ellipsis-v"/>
</button>
<div className="items" onMouseLeave={this.onMouseLeave.bind(this)}>
{ React.Children.map(this.props.children, (child) => {
return cloneElement(child, {
onClicked: this.onItemClicked.bind(this)
});
})}
</div>
</div>
);
}
}
| import React, { Component, PropTypes, cloneElement } from 'react';
import styles from './OverFlowMenu.module.scss';
export class OverflowItem extends Component {
onClick(e) {
this.props.onClick(e);
this.props.onClicked();
}
render() {
return (
<div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}>
{ this.props.children }
</div>
);
}
}
export default class OverFlowMenu extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
toggle() {
this.setState({open: !this.state.open});
}
onItemClicked() {
this.toggle();
}
onMouseLeave() {
this.toggle();
}
render() {
const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' ');
return (
<div className={ cn }>
<button className={styles.btn} onClick={this.toggle.bind(this)}>
<i className="fa small fa-ellipsis-v"/>
</button>
<div className="items" onMouseLeave={this.onMouseLeave.bind(this)}>
{ React.Children.map(this.props.children, (child) => {
return cloneElement(child, {
onClicked: this.onItemClicked.bind(this)
});
})}
</div>
</div>
);
}
}
|
Fix capital O missing umlaut | # coding=utf-8
from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
import re
class Provider(InternetProvider):
free_email_domains = (
'web.de', 'gmail.com', 'hotmail.de', 'yahoo.de', 'googlemail.com',
'aol.de', 'gmx.de'
)
tlds = ('com', 'com', 'com', 'net', 'org', 'de', 'de', 'de')
@staticmethod
def _to_ascii(string):
replacements = (
('รค', 'ae'), ('ร', 'Ae'),
('รถ', 'oe'), ('ร', 'Oe'),
('รผ', 'ue'), ('ร', 'Ue'),
('ร', 'ss')
)
for search, replace in replacements:
string = string.replace(search, replace)
return string
def user_name(self):
pattern = self.random_element(self.user_name_formats)
return self._to_ascii(
self.bothify(self.generator.parse(pattern)
).lower())
def domain_word(self):
company = self.generator.format('company')
company_elements = company.split(' ')
company = self._to_ascii(company_elements.pop(0))
return re.sub(r'\W', '', company).lower()
| # coding=utf-8
from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
import re
class Provider(InternetProvider):
free_email_domains = (
'web.de', 'gmail.com', 'hotmail.de', 'yahoo.de', 'googlemail.com',
'aol.de', 'gmx.de'
)
tlds = ('com', 'com', 'com', 'net', 'org', 'de', 'de', 'de')
@staticmethod
def _to_ascii(string):
replacements = (
('รค', 'ae'), ('ร', 'Ae'),
('รถ', 'oe'), ('O', 'Oe'),
('รผ', 'ue'), ('ร', 'Ue'),
('ร', 'ss')
)
for search, replace in replacements:
string = string.replace(search, replace)
return string
def user_name(self):
pattern = self.random_element(self.user_name_formats)
return self._to_ascii(
self.bothify(self.generator.parse(pattern)
).lower())
def domain_word(self):
company = self.generator.format('company')
company_elements = company.split(' ')
company = self._to_ascii(company_elements.pop(0))
return re.sub(r'\W', '', company).lower()
|
Set jshint to ignore minified files. | module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
handlebars: {
compile: {
options: {
amd: ['handlebars', 'handlebars.helpers'],
namespace: 'templates',
partialRegex: /.*/,
partialsPathRegex: /\/partials\//,
processName: function (path) {
return path.match(/([\w]+)\.hbs/)[1];
}
},
files: {
'static/templates/compiled.js': ['src/views/**/*.hbs']
}
}
},
jshint: {
server: {
options: {
jshintrc: true
},
src: ['src/**/*.js']
},
client: {
options: {
jshintrc: true,
ignores: ['static/js/**/*.min.js']
},
src: ['static/js/**/*.js']
},
tests: {
options: {
jshintrc: true
},
src: ['test/**/*.js']
}
},
sass: {
dist: {
files: {
'static/css/styles.css': 'static/css/styles.scss'
}
}
},
watch: {
handlebars: {
files: ['src/views/**/*.hbs'],
tasks: ['handlebars']
},
jshint: {
files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'],
tasks: ['jshint']
},
sass: {
files: ['static/css/**/*.scss'],
tasks: ['sass']
}
}
});
grunt.registerTask('default', ['handlebars', 'jshint', 'sass']);
};
| module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
handlebars: {
compile: {
options: {
amd: ['handlebars', 'handlebars.helpers'],
namespace: 'templates',
partialRegex: /.*/,
partialsPathRegex: /\/partials\//,
processName: function (path) {
return path.match(/([\w]+)\.hbs/)[1];
}
},
files: {
'static/templates/compiled.js': ['src/views/**/*.hbs']
}
}
},
jshint: {
server: {
options: {
jshintrc: true
},
src: ['src/**/*.js']
},
client: {
options: {
jshintrc: true
},
src: ['static/js/**/*.js']
},
tests: {
options: {
jshintrc: true
},
src: ['test/**/*.js']
}
},
sass: {
dist: {
files: {
'static/css/styles.css': 'static/css/styles.scss'
}
}
},
watch: {
handlebars: {
files: ['src/views/**/*.hbs'],
tasks: ['handlebars']
},
jshint: {
files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'],
tasks: ['jshint']
},
sass: {
files: ['static/css/**/*.scss'],
tasks: ['sass']
}
}
});
grunt.registerTask('default', ['handlebars', 'jshint', 'sass']);
};
|
Use the right name for the profile role's values. | from django.shortcuts import render_to_response
from pytask.profile import models as profile_models
def show_msg(user, message, redirect_url=None, url_desc=None):
""" simply redirect to homepage """
return render_to_response('show_msg.html',{'user': user,
'message': message,
'redirect_url': redirect_url,
'url_desc': url_desc})
def home_page(request):
""" get the user and display info about the project if not logged in.
if logged in, display info of their tasks.
"""
user = request.user
if not user.is_authenticated():
return render_to_response("index.html")
profile = user.get_profile()
claimed_tasks = user.claimed_tasks.all()
selected_tasks = user.selected_tasks.all()
reviewing_tasks = user.reviewing_tasks.all()
unpublished_tasks = user.created_tasks.filter(status="UP").all()
can_create_task = True if profile.role != profile_models.ROLES_CHOICES[3][0] else False
context = {"user": user,
"profile": profile,
"claimed_tasks": claimed_tasks,
"selected_tasks": selected_tasks,
"reviewing_tasks": reviewing_tasks,
"unpublished_tasks": unpublished_tasks,
"can_create_task": can_create_task
}
return render_to_response("index.html", context)
def under_construction(request):
return render_to_response("under_construction.html")
| from django.shortcuts import render_to_response
def show_msg(user, message, redirect_url=None, url_desc=None):
""" simply redirect to homepage """
return render_to_response('show_msg.html',{'user': user,
'message': message,
'redirect_url': redirect_url,
'url_desc': url_desc})
def home_page(request):
""" get the user and display info about the project if not logged in.
if logged in, display info of their tasks.
"""
user = request.user
if not user.is_authenticated():
return render_to_response("index.html")
profile = user.get_profile()
claimed_tasks = user.claimed_tasks.all()
selected_tasks = user.selected_tasks.all()
reviewing_tasks = user.reviewing_tasks.all()
unpublished_tasks = user.created_tasks.filter(status="UP").all()
can_create_task = True if profile.rights != "CT" else False
context = {"user": user,
"profile": profile,
"claimed_tasks": claimed_tasks,
"selected_tasks": selected_tasks,
"reviewing_tasks": reviewing_tasks,
"unpublished_tasks": unpublished_tasks,
"can_create_task": can_create_task
}
return render_to_response("index.html", context)
def under_construction(request):
return render_to_response("under_construction.html")
|
Update route on interval drop-down changes. | define([], function() {
'use strict';
return Backbone.View.extend({
jqplotId: null,
initialize: function(options) {
this.render();
var view = this;
diana.helpers.Event.on('DashboardTimeIntervalChange', function(interval) {
view.options.dashArgs.interval = interval;
view.navigate('dashboard', view.options.dashArgs, {trigger: false});
view.render();
});
},
render: function() {
// Use convention-based IDs so markup can just hold positional containers.
this.jqplotId = this.el.id + '-canvas';
var url = this.buildUrl('/job/count_all_graph?', {
interval: this.options.dashArgs.interval
}, false);
var view = this;
$.ajax(
url, {
success: function(data) {
view.$el.empty();
view.$el.append($('<div>').attr('id', view.jqplotId));
var graphData = [];
_.each(data, function(result, time) {
graphData.push([time, result.count]);
});
var defaults = {
xaxis: {
renderer: $.jqplot.DateAxisRenderer
}
};
var axes = diana.helpers.Graph.adjustAxes(graphData, defaults);
try {
$.jqplot(
view.jqplotId,
[graphData],
{
title: 'Events',
axes: axes,
series:[{lineWidth:2}]
}
);
} catch (e) {
if (e.message != 'No data to plot.') {
console.log(e);
}
}
}
});
}
});
});
| define([], function() {
'use strict';
return Backbone.View.extend({
jqplotId: null,
initialize: function(options) {
this.render();
var view = this;
diana.helpers.Event.on('DashboardTimeIntervalChange', function(interval) {
view.options.dashArgs.interval = interval;
view.render();
});
},
render: function() {
// Use convention-based IDs so markup can just hold positional containers.
this.jqplotId = this.el.id + '-canvas';
var url = this.buildUrl('/job/count_all_graph?', {
interval: this.options.dashArgs.interval
}, false);
var view = this;
$.ajax(
url, {
success: function(data) {
view.$el.empty();
view.$el.append($('<div>').attr('id', view.jqplotId));
var graphData = [];
_.each(data, function(result, time) {
graphData.push([time, result.count]);
});
var defaults = {
xaxis: {
renderer: $.jqplot.DateAxisRenderer
}
};
var axes = diana.helpers.Graph.adjustAxes(graphData, defaults);
try {
$.jqplot(
view.jqplotId,
[graphData],
{
title: 'Events',
axes: axes,
series:[{lineWidth:2}]
}
);
} catch (e) {
if (e.message != 'No data to plot.') {
console.log(e);
}
}
}
});
}
});
});
|
Read the correct package name
We can't read the package name from the cordova interface since that is in the
org.apache.cordova package. Instead, we get it from the cordova activity. So as
long as the new screen is in the same package as the cordova activity, we are
fine. | package edu.berkeley.eecs.emission.cordova.launchnative;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
public class LaunchNative extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
if (action.equals("launch")) {
String pkgName = cordova.getActivity().getPackageName();
System.out.println("cordova has package name "+pkgName);
String activityName = data.getString(0);
String fqcn = pkgName+"."+activityName;
System.out.println("FQCN = "+ fqcn);
try {
Class fqClass = Class.forName(fqcn);
Intent startIntent = new Intent(cordova.getActivity(), fqClass);
cordova.getActivity().startActivity(startIntent);
callbackContext.success("Launched activity " + activityName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
callbackContext.error("Class "+fqcn+" not found, unable to launch");
}
return true;
} else {
return false;
}
}
}
| package edu.berkeley.eecs.emission.cordova.launchnative;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
public class LaunchNative extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
if (action.equals("launch")) {
java.lang.Package pkg = cordova.getClass().getPackage();
System.out.println("cordova has package name "+pkg);
String activityName = data.getString(0);
String fqcn = pkg.getName()+"."+activityName;
System.out.println("FQCN = "+pkg.getName() + fqcn);
try {
Class fqClass = Class.forName(fqcn);
Intent startIntent = new Intent(cordova.getActivity(), fqClass);
cordova.getActivity().startActivity(startIntent);
callbackContext.success("Launched activity " + activityName);
} catch (ClassNotFoundException e) {
callbackContext.error("Class "+fqcn+" not found, unable to launch");
}
return true;
} else {
return false;
}
}
}
|
Move all the process creation in a new function
This reduces the size of code. | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
client = create_process("client", mfhclient.main, args, update_event)
serv = create_process("server", server.main, args, update_event)
if args.client is not None:
client.start()
if args.client is not None:
serv.start()
if args.updater:
trigger = create_process("trigger", update.trigger, update_event)
trigger.start()
trigger.join()
while client.is_alive() or serv.is_alive():
time.sleep(5)
else:
if args.updater:
update.pull("origin", "master")
sys.stdout.flush()
os.execl(sys.executable, sys.executable, *sys.argv)
def create_process(name, function, *arguments):
process = Process(
args=arguments,
name="{0}_process".format(name),
target=function,
)
return process
if __name__ == '__main__':
# Parse arguments
args = parse()
if args.c:
args.client = HONEYPORT
if args.s:
args.server = HIVEPORT
processes = {}
main()
| import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfhclient_process",
target=mfhclient.main,
)
server_process = Process(
args=(args, update_event,),
name="server_process",
target=server.main,
)
if args.client is not None:
mfhclient_process.start()
if args.client is not None:
server_process.start()
if args.updater:
trigger_process = Process(
args=(update_event,),
name="trigger_process",
target=update.trigger,
)
trigger_process.start()
trigger_process.join()
while mfhclient_process.is_alive() or server_process.is_alive():
time.sleep(5)
else:
if args.updater:
# update.pull("origin", "master")
sys.stdout.flush()
os.execl(sys.executable, sys.executable, *sys.argv)
if __name__ == '__main__':
# Parse arguments
args = parse()
if args.c:
args.client = HONEYPORT
if args.s:
args.server = HIVEPORT
main()
|
Use correct method to get classname of self | import os.path
from utils import file_sha1sum
class Artefact(object):
def __init__(self, filename, extension):
if not filename.endswith(extension):
raise ValueError
self._filename = filename
self._ext_length = len(extension)
self._abspath = os.path.abspath(filename)
def checksum(self):
return file_sha1sum(self.filename)
def exists(self):
return os.path.exists(self.filename)
@property
def abspath(self):
return self._abspath
@property
def basename(self):
"""Return the filename without the extension"""
return self._filename[:-self._ext_length]
def dereference(self):
self._filename = os.path.basename(self._filename)
@property
def filename(self):
return self._filename
def __repr__(self):
return '{0}({1!r})'.format(self.__class__.__name__, self.filename)
class NiiGzImage(Artefact):
def __init__(self, filename):
super(NiiGzImage, self).__init__(filename, '.nii.gz')
def __repr__(self):
return '{0}({1!r})'.format(self.__class__.__name__, self.filename)
class TextFile(Artefact):
def __init__(self, filename):
super(TextFile, self).__init__(filename, '.txt')
def __repr__(self):
return '{0}({1!r})'.format(self.__class__.__name__, self.filename)
| import os.path
from utils import file_sha1sum
class Artefact(object):
def __init__(self, filename, extension):
if not filename.endswith(extension):
raise ValueError
self._filename = filename
self._ext_length = len(extension)
self._abspath = os.path.abspath(filename)
def checksum(self):
return file_sha1sum(self.filename)
def exists(self):
return os.path.exists(self.filename)
@property
def abspath(self):
return self._abspath
@property
def basename(self):
"""Return the filename without the extension"""
return self._filename[:-self._ext_length]
def dereference(self):
self._filename = os.path.basename(self._filename)
@property
def filename(self):
return self._filename
def __repr__(self):
return 'Artefact({0!r})'.format(self.filename)
class NiiGzImage(Artefact):
def __init__(self, filename):
super(NiiGzImage, self).__init__(filename, '.nii.gz')
def __repr__(self):
return '{0}({1!r})'.format(self.__clsname__, self.filename)
class TextFile(Artefact):
def __init__(self, filename):
super(TextFile, self).__init__(filename, '.txt')
def __repr__(self):
return '{0}({1!r})'.format(self.__clsname__, self.filename)
|
Use a constant to specify the number of child threads to create.
Instead of assuming that the number process ids of the threads is the
same as the process id of the controlling process, use a copy of the
dictionary and check for changes in the process ids of the threads
from the thread's process ids in the parent process. This makes the
test make more sense on systems which assign a new pid to each thread
(i.e., Linux).
This doesn't fix the other problems evident with this test on Linux. | """This test checks for correct fork() behavior.
We want fork1() semantics -- only the forking thread survives in the
child after a fork().
On some systems (e.g. Solaris without posix threads) we find that all
active threads survive in the child after a fork(); this is an error.
"""
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(NUM_THREADS):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(NUM_THREADS)
prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
for key in alive.keys():
if alive[key] != prefork_lives[key]:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
| """This test checks for correct fork() behavior.
We want fork1() semantics -- only the forking thread survives in the
child after a fork().
On some systems (e.g. Solaris without posix threads) we find that all
active threads survive in the child after a fork(); this is an error.
"""
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(4):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(4)
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
pid = os.getpid()
for key in alive.keys():
if alive[key] == pid:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
|
Add the Javascript half of the new Geolocation code | var constructGeolocationLink = function constructGeolocationLink($wrapper){
var geolocationIsSupported = false;
if ("geolocation" in navigator) {
geolocationIsSupported = true;
}
if(geolocationIsSupported) {
var t1 = $wrapper.attr('data-link-text') || 'Use my current location';
var t2 = $wrapper.attr('data-loading-text') || 'Getting location\u2026';
var $a = $('<a>').text(t1).addClass('geolocation-link');
$a.on('click', function(){
var that = this;
$(this).text(t2);
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON(
'/geolocator/' + position.coords.latitude + ',' + position.coords.longitude,
function ( data ) {
if ( data['error'] ) {
$(that).text(data['error']);
} else if ( data['url'] ) {
window.location=data['url']
} else {
$(that).text(data['error']);
}
});
});
})
$a.appendTo($wrapper);
}
}
$(function(){
$('.js-geolocation-link').each(function(){
constructGeolocationLink( $(this) );
});
});
| var constructGeolocationLink = function constructGeolocationLink($wrapper){
var geolocationIsSupported = false;
if ("geolocation" in navigator) {
geolocationIsSupported = true;
}
if(geolocationIsSupported) {
var t1 = $wrapper.attr('data-link-text') || 'Use my current location';
var t2 = $wrapper.attr('data-loading-text') || 'Getting location\u2026';
var $a = $('<a>').text(t1).addClass('geolocation-link');
$a.on('click', function(){
var that = this;
$(this).text(t2);
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON(
'/geolocator/' + position.coords.latitude + ',' + position.coords.longitude,
function ( data ) {
if ( data['error'] ) {
$(that).text(data['error']);
} else if ( data['url'] ) {
window.location=data['url']
}
});
});
})
$a.appendTo($wrapper);
}
}
$(function(){
$('.js-geolocation-link').each(function(){
constructGeolocationLink( $(this) );
});
});
|
feat: Add koan about object duplicate properties | describe("About Objects", function () {
describe("Shorthand Syntax", function () {
it('should understand initailiser shorthand', function() {
function passThrough(one, two) {
return {
one,
two
}
}
var data = passThrough('one', 'two');
expect(typeof data).toEqual(FILL_ME_IN);
expect(data.one).toEqual(FILL_ME_IN);
expect(data.two).toEqual(FILL_ME_IN);
})
it('should understand method shorthand', function() {
var utils = {
uppercase(string) {
return string.toUpperCase();
}
};
expect(typeof utils.uppercase).toEqual(FILL_ME_IN);
expect(typeof utils.uppercase('upper')).toEqual(FILL_ME_IN);
})
});
describe('Computed Names', function() {
it('should understand computed names usage', function() {
var car = 'ford';
var engine = 'Engine';
var carDetails = {
[car] : {
[car + 'Doors']: 4,
[car + engine]: 'v8',
[car + 'Model'] : 'Mustang'
}
}
expect(typeof FILL_ME_IN).toEqual('object');
expect(FILL_ME_IN).toEqual(4);
expect(FILL_ME_IN).toEqual('v8');
expect(FILL_ME_IN).toEqual('Mustang');
})
})
describe('Duplicate Literal Properties', function() {
it('should understand have duplicate keys are handled', function() {
var newJsStandard = {
name: 'harmony',
name: 'es6',
name: 'es2015'
};
expect(newJsStandard.name).toEqual(FILL_ME_IN);
})
})
});
| describe("About Objects", function () {
describe("Shorthand Syntax", function () {
it('should understand initailiser shorthand', function() {
function passThrough(one, two) {
return {
one,
two
}
}
var data = passThrough('one', 'two');
expect(typeof data).toEqual(FILL_ME_IN);
expect(data.one).toEqual(FILL_ME_IN);
expect(data.two).toEqual(FILL_ME_IN);
})
it('should understand method shorthand', function() {
var utils = {
uppercase(string) {
return string.toUpperCase();
}
};
expect(typeof utils.uppercase).toEqual(FILL_ME_IN);
expect(typeof utils.uppercase('upper')).toEqual(FILL_ME_IN);
})
});
describe('Computed Names', function() {
it('should understanding computed names usage', function() {
var car = 'ford';
var engine = 'Engine';
var carDetails = {
[car] : {
[car + 'Doors']: 4,
[car + engine]: 'v8',
[car + 'Model'] : 'Mustang'
}
}
expect(typeof FILL_ME_IN).toEqual('object');
expect(FILL_ME_IN).toEqual(4);
expect(FILL_ME_IN).toEqual('v8');
expect(FILL_ME_IN).toEqual('Mustang');
})
})
});
|
Upgrade Facebook API to v. 2.10 | klimaChallenge.controller('newsCtrl', function($scope, $http, $sce) {
$scope.facebookImages = Array();
$http.get('https://graph.facebook.com/v2.10/klimachallenge/photos/uploaded?fields=link,width,name,images&limit=10&access_token=846767055411205|UKF39DbxTvvEeA9BuKkWsJgiuLE').
success(function(data, status, headers, config) {
angular.forEach(data.data, function(image, key) {
// Only take images when they are big enough
if (image.width >= 720) {
if (image.name) {
// Shorten image text if longer than 160 chars
if (image.name.length > 160) {
var newText = image.name.substring(0,140);
var i = 140;
while (image.name.charAt(i) != " ") {
newText = newText + image.name.charAt(i);
i++;
}
image.name = newText;
image.showReadMore = true;
}
}
$scope.facebookImages.push(image);
}
});
});
});
| klimaChallenge.controller('newsCtrl', function($scope, $http, $sce) {
$scope.facebookImages = Array();
$http.get('https://graph.facebook.com/v2.4/klimachallenge/photos/uploaded?fields=link,width,name,images&limit=10&access_token=846767055411205|UKF39DbxTvvEeA9BuKkWsJgiuLE').
success(function(data, status, headers, config) {
angular.forEach(data.data, function(image, key) {
// Only take images when they are big enough
if (image.width >= 720) {
if (image.name) {
// Shorten image text if longer than 160 chars
if (image.name.length > 160) {
var newText = image.name.substring(0,140);
var i = 140;
while (image.name.charAt(i) != " ") {
newText = newText + image.name.charAt(i);
i++;
}
image.name = newText;
image.showReadMore = true;
}
}
$scope.facebookImages.push(image);
}
});
});
});
|
Include watching config.json for changes | 'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['./*.js', 'routes/*.js', 'models/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: ['<%= jshint.lib.src %>', 'config.json'],
tasks: ['jshint:lib', 'express:dev'],
options: {
spawn: false
}
},
},
express: {
dev: {
options: {
script: './bin/www'
}
},
prod: {
options: {
script: './bin/www',
node_env: 'production'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-express-server');
grunt.registerTask('default', ['jshint']);
grunt.registerTask('server', [ 'express:dev', 'watch' ]);
};
| 'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['./*.js', 'routes/*.js', 'models/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'express:dev'],
options: {
spawn: false
}
},
},
express: {
dev: {
options: {
script: './bin/www'
}
},
prod: {
options: {
script: './bin/www',
node_env: 'production'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-express-server');
grunt.registerTask('default', ['jshint']);
grunt.registerTask('server', [ 'express:dev', 'watch' ]);
};
|
Fix bug where dependencies aren't part of the context | import lodash from 'lodash';
export function listeningTo(storeNames, getterMethodName = 'getStateFromDependencies') {
return decorator;
function decorator(fn) {
const originalCDM = fn.prototype.componentDidMount;
const originalCWU = fn.prototype.componentWillUnmount;
fn.prototype.componentDidMount = function componentWillMount() {
if (originalCDM) {
originalCDM.apply(this, arguments);
}
const stores = storeNames.map(name => this.context.dependencies[name]);
const getterMethod = this[getterMethodName];
this._setStateFromStores = () => {
this.setState(getterMethod.call(this));
};
lodash.each(stores, store => {
store.on('change', this._setStateFromStores);
});
};
fn.prototype.componentWillUnmount = function componentWillMount() {
if (originalCWU) {
originalCWU.apply(this, arguments);
}
const stores = storeNames.map(name => this.context.dependencies[name]);
const getterMethod = this[getterMethodName];
lodash.each(stores, store => {
store.removeListener('change', this._setStateFromStores);
});
};
}
}
| import lodash from 'lodash';
export function listeningTo(storeNames, getterMethodName = 'getStateFromDependencies') {
return decorator;
function decorator(fn) {
const originalCDM = fn.prototype.componentDidMount;
const originalCWU = fn.prototype.componentWillUnmount;
fn.prototype.componentDidMount = function componentWillMount() {
if (originalCDM) {
originalCDM.apply(this, arguments);
}
const stores = storeNames.map(name => this.dependencies[name]);
const getterMethod = this[getterMethodName];
this._setStateFromStores = () => {
this.setState(getterMethod.call(this));
};
lodash.each(stores, store => {
store.on('change', this._setStateFromStores);
});
};
fn.prototype.componentWillUnmount = function componentWillMount() {
if (originalCWU) {
originalCWU.apply(this, arguments);
}
const stores = storeNames.map(name => this.dependencies[name]);
const getterMethod = this[getterMethodName];
lodash.each(stores, store => {
store.removeListener('change', this._setStateFromStores);
});
};
}
}
|
Throw an error if no Client-ID is given | var http = require("https");
var querystring = require("querystring");
var ImgurProto = {
gallery: function(params, callback) {
var qs = querystring.stringify(params);
var options = {
hostname: "api.imgur.com",
path: ["/3/gallery.json", qs].join("?"),
headers: {
"Authorization": ["Client-ID", this.clientId].join(" "),
"Content-Type": "application/json"
}
};
http.get(options, function(res) {
var body = "";
res.on("data", function(chunk) {
body += chunk;
});
res.on("end", function() {
try {
var payload = JSON.parse(body);
if (payload.success) {
callback(null, payload.data || []);
} else {
callback(payload.data.error);
}
} catch (error) {
callback(error);
}
});
}).on("error", function(error) {
callback(error);
});
}
};
module.exports = function(clientId) {
if (!clientId) {
throw "You must provide an Imgur Client-ID";
}
return Object.create(ImgurProto, {
clientId: {
writable: false,
configurable: false,
enumerable: false,
value: clientId
}
});
};
| var http = require("https");
var querystring = require("querystring");
var ImgurProto = {
gallery: function(params, callback) {
var qs = querystring.stringify(params);
var options = {
hostname: "api.imgur.com",
path: ["/3/gallery.json", qs].join("?"),
headers: {
"Authorization": ["Client-ID", this.clientId].join(" "),
"Content-Type": "application/json"
}
};
http.get(options, function(res) {
var body = "";
res.on("data", function(chunk) {
body += chunk;
});
res.on("end", function() {
try {
var payload = JSON.parse(body);
if (payload.success) {
callback(null, payload.data || []);
} else {
callback(payload.data.error);
}
} catch (error) {
callback(error);
}
});
}).on("error", function(error) {
callback(error);
});
}
};
module.exports = function(clientId) {
return Object.create(ImgurProto, {
clientId: {
writable: false,
configurable: false,
enumerable: false,
value: clientId
}
});
};
|
Change default value to use UTC time | from datetime import datetime, timedelta
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
DATE_FORMAT = '%Y-%m-%d %H:%M:%S GMT'
schema = {
'name': {
'type': 'string',
'minlength': 3,
'maxlength': 50,
'required': True,
},
'occurred_on': {
'type': 'datetime',
'default': datetime.utcnow(),
},
'source': {
'type': 'string',
'minlength': 2,
'maxlength': 50,
'required': True,
},
'reporter': {
'type': 'string',
'minlength': 3,
'maxlength': 20,
'required': True,
},
'details': {
'type': 'string',
'minlength': 0,
'maxlength': 300,
'required': False
},
}
event = {
'item_title': 'event',
'additional_lookup': {
'url': 'regex("[\w]+")',
'field': 'name',
},
'cache_control': 'max-age=10, must-revalidate',
'cache_expires': 10,
'resource_methods': ['GET', 'POST'],
'schema': schema
}
DOMAIN = {
'event': event,
}
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_USERNAME = ''
MONGO_PASSWORD = ''
MONGO_DBNAME = 'historia'
| from datetime import datetime, timedelta
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
DATE_FORMAT = '%Y-%m-%d %H:%M:%S GMT'
schema = {
'name': {
'type': 'string',
'minlength': 3,
'maxlength': 50,
'required': True,
},
'occurred_on': {
'type': 'datetime',
'default': datetime.now(),
},
'source': {
'type': 'string',
'minlength': 2,
'maxlength': 50,
'required': True,
},
'reporter': {
'type': 'string',
'minlength': 3,
'maxlength': 20,
'required': True,
},
'details': {
'type': 'string',
'minlength': 0,
'maxlength': 300,
'required': False
},
}
event = {
'item_title': 'event',
'additional_lookup': {
'url': 'regex("[\w]+")',
'field': 'name',
},
'cache_control': 'max-age=10, must-revalidate',
'cache_expires': 10,
'resource_methods': ['GET', 'POST'],
'schema': schema
}
DOMAIN = {
'event': event,
}
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_USERNAME = ''
MONGO_PASSWORD = ''
MONGO_DBNAME = 'historia'
|
Add shebang and make file executable | #!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
content = file.read()
return content
readers = {
b'application/x-gzip': read_gzip,
b'text/plain': read_plain,
}
def read(filename):
type = magic.from_file(filename, mime=True)
return readers[type](filename).decode()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', help='path to moita configuration file',
dest='moita', metavar='MOITA', required=True)
parser.add_argument('filename', nargs='+')
args = parser.parse_args()
sys.path.append(os.path.dirname(args.moita))
import config
connection = pymongo.MongoClient()
collection = connection[config.DATABASE].timetables
for file in args.filename:
content = json.loads(read(file))
identifier = binascii.unhexlify(
os.path.basename(file).split('.', 1)[0]).decode()
content['_id'] = identifier
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
content['updated_at'] = mtime
collection.save(content)
| import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
content = file.read()
return content
readers = {
b'application/x-gzip': read_gzip,
b'text/plain': read_plain,
}
def read(filename):
type = magic.from_file(filename, mime=True)
return readers[type](filename).decode()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', help='path to moita configuration file',
dest='moita', metavar='MOITA', required=True)
parser.add_argument('filename', nargs='+')
args = parser.parse_args()
sys.path.append(os.path.dirname(args.moita))
import config
connection = pymongo.MongoClient()
collection = connection[config.DATABASE].timetables
for file in args.filename:
content = json.loads(read(file))
identifier = binascii.unhexlify(
os.path.basename(file).split('.', 1)[0]).decode()
content['_id'] = identifier
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
content['updated_at'] = mtime
collection.save(content)
|
ADD the new parameter for specify ident service ids | <?php
/**
* Contact Common model class
*/
namespace SecucardConnect\Product\Common\Model;
/**
* Contact Data Model class
*
*/
class Contact
{
/**
* @var string
*/
public $salutation;
/**
* @var string
*/
public $title;
/**
* @var string
*/
public $forename;
/**
* @var string
*/
public $surname;
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $companyname;
/**
* @var \DateTime
*/
public $dob;
/**
* @var string
*/
public $birthplace;
/**
* @var string
*/
public $nationality;
/**
* @var string
*/
public $gender;
/**
* @var string
*/
public $phone;
/**
* @var string
*/
public $mobile;
/**
* @var string
*/
public $email;
/**
* A user picture URL.
* @var string
*/
public $picture;
/**
* The img object for the picture
* @var MediaResource
*/
public $pictureObject;
/**
* @var string
*/
public $url_website;
/**
* @var \SecucardConnect\Product\Common\Model\Address
*/
public $address;
/**
* A (indexed) list of ids for completed identification results
* (f.e. from SecuIdent-Service with 'POSTIDENT' or 'IDnow')
*
* @var array
*/
public $ident_service_ids = [];
}
| <?php
/**
* Contact Common model class
*/
namespace SecucardConnect\Product\Common\Model;
/**
* Contact Data Model class
*
*/
class Contact
{
/**
* @var string
*/
public $salutation;
/**
* @var string
*/
public $title;
/**
* @var string
*/
public $forename;
/**
* @var string
*/
public $surname;
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $companyname;
/**
* @var \DateTime
*/
public $dob;
/**
* @var string
*/
public $birthplace;
/**
* @var string
*/
public $nationality;
/**
* @var string
*/
public $gender;
/**
* @var string
*/
public $phone;
/**
* @var string
*/
public $mobile;
/**
* @var string
*/
public $email;
/**
* A user picture URL.
* @var string
*/
public $picture;
/**
* The img object for the picture
* @var MediaResource
*/
public $pictureObject;
/**
* @var string
*/
public $url_website;
/**
* @var \SecucardConnect\Product\Common\Model\Address
*/
public $address;
}
|
Update child fn name to onItemSelect from clickHandler | import {Dropdown} from 'reactjs-components';
import React from 'react';
import Icon from './Icon';
const getMenuItems = (children) => {
return [
{
className: 'hidden',
html: <Icon id="ellipsis-vertical" size="mini" />,
id: 'trigger'
},
...React.Children.map(children, getDropdownItemFromComponent)
];
};
const handleItemSelection = (item) => {
if (item.onItemSelect) {
item.onItemSelect();
}
};
const getDropdownItemFromComponent = (child, index) => {
return {
onItemSelect: child.props.onItemSelect,
html: child,
id: index
};
};
const PageHeaderActionsMenu = ({children}) => {
return (
<Dropdown
buttonClassName="button button-link"
items={getMenuItems(children)}
onItemSelection={handleItemSelection}
persistentID="trigger"
transition={true}
dropdownMenuClassName="dropdown-menu"
dropdownMenuListClassName="dropdown-menu-list"
wrapperClassName="dropdown" />
);
};
PageHeaderActionsMenu.defaultProps = {
anchorRight: true
};
PageHeaderActionsMenu.propTypes = {
// anchorRight gets passed to Dropdown. It's truthy here unlike in the Dropdown.
anchorRight: React.PropTypes.bool,
children: React.PropTypes.arrayOf(
React.PropTypes.shape({
props: React.PropTypes.shape({
onItemSelect: React.PropTypes.func
})
})
)
};
module.exports = PageHeaderActionsMenu;
| import {Dropdown} from 'reactjs-components';
import React from 'react';
import Icon from './Icon';
const getMenuItems = (children) => {
return [
{
className: 'hidden',
html: <Icon id="ellipsis-vertical" size="mini" />,
id: 'trigger'
},
...React.Children.map(children, getDropdownItemFromComponent)
];
};
const handleItemSelection = (item) => {
if (item.onItemSelect) {
item.onItemSelect();
}
};
const getDropdownItemFromComponent = (child, index) => {
return {
clickHandler: child.props.clickHandler,
html: child,
id: index
};
};
const PageHeaderActionsMenu = ({children}) => {
return (
<Dropdown
buttonClassName="button button-link"
items={getMenuItems(children)}
onItemSelection={handleItemSelection}
persistentID="trigger"
transition={true}
dropdownMenuClassName="dropdown-menu"
dropdownMenuListClassName="dropdown-menu-list"
wrapperClassName="dropdown" />
);
};
PageHeaderActionsMenu.defaultProps = {
anchorRight: true
};
PageHeaderActionsMenu.propTypes = {
// anchorRight gets passed to Dropdown. It's truthy here unlike in the Dropdown.
anchorRight: React.PropTypes.bool,
children: React.PropTypes.arrayOf(
React.PropTypes.shape({
props: React.PropTypes.shape({
onItemSelect: React.PropTypes.func
})
})
)
};
module.exports = PageHeaderActionsMenu;
|
Disable errors in Ace Editor
I did this as errors always seem to show in the editor and this can be very offputting for the end user | function component( args ) {
/*
base_component_id("editorComponent")
load_once_from_file(true)
*/
//alert(JSON.stringify(args,null,2))
var uid = uuidv4()
var uid2 = uuidv4()
var mm = Vue.component(uid, {
data: function () {
return {
text: args.text,
uid2: uid2
}
},
template: `<div>
<div v-bind:id='uid2' ></div>
<hr />
<slot :text2="text"></slot>
</div>`
,
mounted: function() {
var mm = this
var editor = ace.edit( uid2, {
mode: "ace/mode/javascript",
selectionStyle: "text"
})
document.getElementById(uid2).style.width="100%"
document.getElementById(uid2).style.height="45vh"
editor.getSession().setValue(mm.text);
editor.getSession().setUseWorker(false);
editor.getSession().on('change', function() {
mm.text = editor.getSession().getValue();
//alert("changed text to : " + mm.text)
});
},
methods: {
getText: function() {
return this.text
}
}
})
return {
name: uid
}
}
| function component( args ) {
/*
base_component_id("editorComponent")
load_once_from_file(true)
*/
//alert(JSON.stringify(args,null,2))
var uid = uuidv4()
var uid2 = uuidv4()
var mm = Vue.component(uid, {
data: function () {
return {
text: args.text,
uid2: uid2
}
},
template: `<div>
<div v-bind:id='uid2' ></div>
<hr />
<slot :text2="text"></slot>
</div>`
,
mounted: function() {
var mm = this
var editor = ace.edit( uid2, {
mode: "ace/mode/javascript",
selectionStyle: "text"
})
document.getElementById(uid2).style.width="100%"
document.getElementById(uid2).style.height="45vh"
editor.getSession().setValue(mm.text);
editor.getSession().on('change', function() {
mm.text = editor.getSession().getValue();
//alert("changed text to : " + mm.text)
});
},
methods: {
getText: function() {
return this.text
}
}
})
return {
name: uid
}
}
|
Convert the file to UTF-8 | package com.fewlaps.mentiondetector;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RemovePunctuationMarksTest {
RemovePunctuationMarks removePunctuationMarks;
@Before
public void setup() {
removePunctuationMarks = new RemovePunctuationMarks();
}
@Test
public void shouldRemoveExclamationMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello!!!!";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("!");
}
@Test
public void shouldRemoveQuestionMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello????";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("?");
}
@Test
public void shouldRemoveReversedExclamationMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("๏ฟฝ");
}
@Test
public void shouldRemoveReversedQuestionMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello๏ฟฝ๏ฟฝ๏ฟฝ";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("๏ฟฝ");
}
}
| package com.fewlaps.mentiondetector;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RemovePunctuationMarksTest {
RemovePunctuationMarks removePunctuationMarks;
@Before
public void setup() {
removePunctuationMarks = new RemovePunctuationMarks();
}
@Test
public void shouldRemoveExclamationMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello!!!!";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("!");
}
@Test
public void shouldRemoveQuestionMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello????";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("?");
}
@Test
public void shouldRemoveReversedExclamationMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("");
}
@Test
public void shouldRemoveReversedQuestionMarks() throws InterruptedException {
String textWithPunctuationMarks = "hello";
String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);
assertThat(textWithoutPunctuationMarks).doesNotContain("");
}
}
|
Add fee_account to BuildingData of legacy test base | # Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from fixture import DataSet
from .address import AddressData
from .finance import AccountData
class SiteData(DataSet):
class dummy:
name = "dummy"
class BuildingData(DataSet):
class dummy_house1:
site = SiteData.dummy
street = "dummy"
number = "01"
short_name = "abc"
fee_account = AccountData.dummy_revenue
class dummy_house2:
site = SiteData.dummy
street = "dummy"
number = "02"
short_name = "def"
fee_account = AccountData.dummy_revenue
class RoomData(DataSet):
class dummy_room1:
number = "1"
level = 1
inhabitable = True
building = BuildingData.dummy_house1
address = AddressData.dummy_address1
class dummy_room2:
number = "2"
level = 2
inhabitable = True
building = BuildingData.dummy_house2
address = AddressData.dummy_address2
class dummy_room3:
number = "2"
level = 2
inhabitable = True
building = BuildingData.dummy_house1
address = AddressData.dummy_address3
class dummy_room4(dummy_room1):
number = "2"
address = AddressData.dummy_address4
class dummy_room5(dummy_room1):
number = "2"
address = AddressData.dummy_address5
| # Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from fixture import DataSet
from .address import AddressData
class SiteData(DataSet):
class dummy:
name = "dummy"
class BuildingData(DataSet):
class dummy_house1:
site = SiteData.dummy
street = "dummy"
number = "01"
short_name = "abc"
class dummy_house2:
site = SiteData.dummy
street = "dummy"
number = "02"
short_name = "def"
class RoomData(DataSet):
class dummy_room1:
number = "1"
level = 1
inhabitable = True
building = BuildingData.dummy_house1
address = AddressData.dummy_address1
class dummy_room2:
number = "2"
level = 2
inhabitable = True
building = BuildingData.dummy_house2
address = AddressData.dummy_address2
class dummy_room3:
number = "2"
level = 2
inhabitable = True
building = BuildingData.dummy_house1
address = AddressData.dummy_address3
class dummy_room4(dummy_room1):
number = "2"
address = AddressData.dummy_address4
class dummy_room5(dummy_room1):
number = "2"
address = AddressData.dummy_address5
|
Use the dots reporter for karms tests | module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'browserify', 'source-map-support'],
reporters: ['dots'],
files: [
'src/js/Application.js',
'src/modules/**/*.html',
'src/html/**/*.html',
'src/test/**/*.js'
],
exclude: [
'src/test/mocks.js',
'src/test/test-main.js'
],
preprocessors: {
'src/modules/**/*.html': ['ng-html2js'],
'src/html/**/*.html': ['ng-html2js'],
'src/js/Application.js': ['browserify'],
'src/test/**/*.js': ['browserify']
},
ngHtml2JsPreprocessor: {
// strip this from the file path
cacheIdFromPath: function (path) {
var newPath = path.replace(/^src/, '');
console.log('Processing template', newPath);
return newPath;
},
// the name of the Angular module to create
moduleName: "karma.templates"
},
browserify: {
debug: true
//debug: true,
//transform: [
//['babelify', { compact: 'none' }],
//['browserify-shim']
//]
},
browsers: ['Chrome']
});
};
| module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'browserify', 'source-map-support'],
files: [
'src/js/Application.js',
'src/modules/**/*.html',
'src/html/**/*.html',
'src/test/**/*.js'
],
exclude: [
'src/test/mocks.js',
'src/test/test-main.js'
],
preprocessors: {
'src/modules/**/*.html': ['ng-html2js'],
'src/html/**/*.html': ['ng-html2js'],
'src/js/Application.js': ['browserify'],
'src/test/**/*.js': ['browserify']
},
ngHtml2JsPreprocessor: {
// strip this from the file path
cacheIdFromPath: function (path) {
var newPath = path.replace(/^src/, '');
console.log('Processing template', newPath);
return newPath;
},
// the name of the Angular module to create
moduleName: "karma.templates"
},
browserify: {
debug: true
//debug: true,
//transform: [
//['babelify', { compact: 'none' }],
//['browserify-shim']
//]
},
browsers: ['Chrome']
});
};
|
Add null check of BGC at execute() on first | package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiErrorType;
import java.util.UUID;
import info.izumin.android.bletia.BletiaErrorType;
import info.izumin.android.bletia.BletiaException;
import info.izumin.android.bletia.action.WriteCharacteristicAction;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;
/**
* Created by izumin on 9/17/15.
*/
public abstract class KonashiWriteCharacteristicAction extends WriteCharacteristicAction {
protected KonashiWriteCharacteristicAction(BluetoothGattCharacteristic characteristic) {
super(characteristic);
}
protected KonashiWriteCharacteristicAction(BluetoothGattService service, UUID uuid) {
this(service.getCharacteristic(uuid));
}
@Override
public boolean execute(BluetoothGattWrapper gattWrapper) {
if (getCharacteristic() != null) {
rejectIfParamsAreInvalid(KonashiErrorType.UNSUPPORTED_OPERATION);
return false;
}
BletiaErrorType errorType = validate();
if (errorType == KonashiErrorType.NO_ERROR) {
setValue();
return super.execute(gattWrapper);
} else {
rejectIfParamsAreInvalid(errorType);
return false;
}
}
protected void rejectIfParamsAreInvalid(BletiaErrorType errorType) {
getDeferred().reject(new BletiaException(this, errorType));
}
protected abstract void setValue();
protected abstract BletiaErrorType validate();
}
| package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiErrorType;
import java.util.UUID;
import info.izumin.android.bletia.BletiaErrorType;
import info.izumin.android.bletia.BletiaException;
import info.izumin.android.bletia.action.WriteCharacteristicAction;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;
/**
* Created by izumin on 9/17/15.
*/
public abstract class KonashiWriteCharacteristicAction extends WriteCharacteristicAction {
protected KonashiWriteCharacteristicAction(BluetoothGattCharacteristic characteristic) {
super(characteristic);
}
protected KonashiWriteCharacteristicAction(BluetoothGattService service, UUID uuid) {
this(service.getCharacteristic(uuid));
}
@Override
public boolean execute(BluetoothGattWrapper gattWrapper) {
BletiaErrorType errorType = validate();
if (errorType == KonashiErrorType.NO_ERROR) {
setValue();
return super.execute(gattWrapper);
} else {
rejectIfParamsAreInvalid(errorType);
return false;
}
}
protected void rejectIfParamsAreInvalid(BletiaErrorType errorType) {
getDeferred().reject(new BletiaException(this, errorType));
}
protected abstract void setValue();
protected abstract BletiaErrorType validate();
}
|
Add Schemes to JSON preview | import {header} from './header';
import {mime} from './mime';
import {security} from './security';
import {tags} from './tags';
import {paths} from './paths';
import {types} from './types';
export const fieldsToShow = {
'header': [
'info',
'contact',
'license',
'host',
'basePath',
'schemes'
],
'types': ['definitions'],
'mime': ['consumes', 'produces']
};
export const schema = {
'type': 'object',
'children': {
header,
mime,
security,
tags,
paths,
types,
'definitions': {
'type': 'link',
'target': '/types'
},
'info': {
'type': 'link',
'target': '/header/info'
},
'contact': {
'type': 'link',
'target': '/header/contact'
},
'license': {
'type': 'link',
'target': '/header/license'
},
'host': {
'type': 'link',
'target': '/header/host/host'
},
'basePath': {
'type': 'link',
'target': '/header/host/basePath'
},
'schemes': {
'type': 'link',
'target': '/header/host/schemes'
},
'consumes': {
'type': 'link',
'target': '/mime/consumes'
},
'produces': {
'type': 'link',
'target': '/mime/produces'
}
}
};
| import {header} from './header';
import {mime} from './mime';
import {security} from './security';
import {tags} from './tags';
import {paths} from './paths';
import {types} from './types';
export const fieldsToShow = {
'header': [
'info',
'contact',
'license',
'host',
'basePath'
],
'types': ['definitions'],
'mime': ['consumes', 'produces']
};
export const schema = {
'type': 'object',
'children': {
header,
mime,
security,
tags,
paths,
types,
'definitions': {
'type': 'link',
'target': '/types'
},
'info': {
'type': 'link',
'target': '/header/info'
},
'contact': {
'type': 'link',
'target': '/header/contact'
},
'license': {
'type': 'link',
'target': '/header/license'
},
'host': {
'type': 'link',
'target': '/header/host/host'
},
'basePath': {
'type': 'link',
'target': '/header/host/basePath'
},
'schemes': {
'type': 'link',
'target': '/header/host/schemes'
},
'consumes': {
'type': 'link',
'target': '/mime/consumes'
},
'produces': {
'type': 'link',
'target': '/mime/produces'
}
}
};
|
Make this a bit cleaner. | <?php
namespace ComplexPie\Atom10;
class Feed
{
private static $aliases = array(
'description' => 'subtitle',
'tagline' => 'subtitle',
'copyright' => 'rights',
);
private static $elements = array(
'title' => array(
'element' => 'atom:title',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
'subtitle' => array(
'element' => 'atom:subtitle',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
'rights' => array(
'element' => 'atom:rights',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
);
public function __invoke($dom, $name)
{
if (isset(self::$elements[$name]))
{
return $this->elements_table($dom, $name);
}
elseif (isset(self::$aliases[$name]))
{
return $this->__invoke($dom, self::$aliases[$name]);
}
}
private function elements_table($dom, $name)
{
$element = self::$elements[$name];
if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single']))
{
return call_user_func($element['contentConstructor'], $return);
}
}
}
| <?php
namespace ComplexPie\Atom10;
class Feed
{
private static $aliases = array(
'description' => 'subtitle',
'tagline' => 'subtitle',
'copyright' => 'rights',
);
private static $elements = array(
'title' => array(
'element' => 'atom:title',
'type' => 'atomTextConstruct',
'single' => true
),
'subtitle' => array(
'element' => 'atom:subtitle',
'type' => 'atomTextConstruct',
'single' => true
),
'rights' => array(
'element' => 'atom:rights',
'type' => 'atomTextConstruct',
'single' => true
),
);
public function __invoke($dom, $name)
{
if (isset(self::$elements[$name]))
{
return $this->elements_table($dom, $name);
}
elseif (isset(self::$aliases[$name]))
{
return $this->__invoke($dom, self::$aliases[$name]);
}
}
private function elements_table($dom, $name)
{
$element = self::$elements[$name];
if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single']))
{
switch ($element['type'])
{
case 'atomTextConstruct':
return Content::from_text_construct($return);
default:
throw new \Exception('Um, this shouldn\'t happen');
}
}
}
}
|
Disable tab stop on password show/hide links | <style type="text/css">
a.show-password{
color: #2196f3;
font-size: 0.9em;
margin-top: 10px;
position: absolute;
right: 0;
top: 0;
transition: all .8s linear;
}
a.show-password:hover{
transition: all .8s linear;
}
</style>
<script>
(function(){
$('input[name="password"], input[name="new_password"], input[name="new_password_confirmation"]').parent().append('<a href="" class="show-password" tabindex="-1"><i class="zmdi zmdi-eye"></i></a>');
function toggleIcon (elem) {
if ( elem.hasClass ( 'zmdi-eye' ) ) {
return elem.removeClass ( 'zmdi-eye' ).addClass ( 'zmdi-eye-off' );
}
return elem.removeClass ( 'zmdi-eye-off' ).addClass ( 'zmdi-eye' );
}
function toggleType (elem) {
return (elem.attr ( 'type' ) === 'password') ? 'text' : 'password';
}
$('body').on('click', '.show-password', function (e) {
var password_field = $(this).siblings('input');
var new_type = toggleType( password_field );
var current_icon = $(this).children('i');
toggleIcon(current_icon);
password_field.attr('type', new_type);
e.preventDefault();
});
})();
</script>
| <style type="text/css">
a.show-password{
color: #2196f3;
font-size: 0.9em;
margin-top: 10px;
position: absolute;
right: 0;
top: 0;
transition: all .8s linear;
}
a.show-password:hover{
transition: all .8s linear;
}
</style>
<script>
(function(){
$('input[name="password"], input[name="new_password"], input[name="new_password_confirmation"]').parent().append('<a href="" class="show-password"><i class="zmdi zmdi-eye"></i></a>');
function toggleIcon (elem) {
if ( elem.hasClass ( 'zmdi-eye' ) ) {
return elem.removeClass ( 'zmdi-eye' ).addClass ( 'zmdi-eye-off' );
}
return elem.removeClass ( 'zmdi-eye-off' ).addClass ( 'zmdi-eye' );
}
function toggleType (elem) {
return (elem.attr ( 'type' ) === 'password') ? 'text' : 'password';
}
$('body').on('click', '.show-password', function (e) {
var password_field = $(this).siblings('input');
var new_type = toggleType( password_field );
var current_icon = $(this).children('i');
toggleIcon(current_icon);
password_field.attr('type', new_type);
e.preventDefault();
});
})();
</script>
|
Add user agent to Blizzard visit log | <?php
namespace BNETDocs\Libraries;
use \BNETDocs\Libraries\Authentication;
use \BNETDocs\Libraries\EventTypes;
use \BNETDocs\Libraries\Logger;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\IP;
class BlizzardChecker {
/**
* Block instantiation of this object.
*/
private function __construct() {}
public static function checkIfBlizzard() {
$IP = getenv('REMOTE_ADDR');
$CIDRs = file_get_contents(getcwd() . '/static/a/Blizzard-CIDRs.txt');
$CIDRs = preg_replace("/^#.*?\n/sm", '', $CIDRs);
$CIDRs = Common::stripLinesWith($CIDRs, "\n");
$CIDRs = explode("\n", $CIDRs);
return IP::checkCIDRArray($IP, $CIDRs);
}
public static function logIfBlizzard() {
$user_id = (
isset(Authentication::$user) ? Authentication::$user->getId() : null
);
if (self::checkIfBlizzard()) {
Logger::logEvent(
EventTypes::BLIZZARD_VISIT,
$user_id,
getenv('REMOTE_ADDR'),
json_encode([
'method' => getenv('REQUEST_METHOD'),
'referer' => getenv('HTTP_REFERER'),
'uri' => getenv('REQUEST_URI'),
'user_agent' => getenv('HTTP_USER_AGENT'),
'version' => VersionInfo::get(),
])
);
}
}
}
| <?php
namespace BNETDocs\Libraries;
use \BNETDocs\Libraries\Authentication;
use \BNETDocs\Libraries\EventTypes;
use \BNETDocs\Libraries\Logger;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\IP;
class BlizzardChecker {
/**
* Block instantiation of this object.
*/
private function __construct() {}
public static function checkIfBlizzard() {
$IP = getenv('REMOTE_ADDR');
$CIDRs = file_get_contents(getcwd() . '/static/a/Blizzard-CIDRs.txt');
$CIDRs = preg_replace("/^#.*?\n/sm", '', $CIDRs);
$CIDRs = Common::stripLinesWith($CIDRs, "\n");
$CIDRs = explode("\n", $CIDRs);
return IP::checkCIDRArray($IP, $CIDRs);
}
public static function logIfBlizzard() {
$user_id = (
isset(Authentication::$user) ? Authentication::$user->getId() : null
);
if (self::checkIfBlizzard()) {
Logger::logEvent(
EventTypes::BLIZZARD_VISIT,
$user_id,
getenv('REMOTE_ADDR'),
json_encode([
'method' => getenv('REQUEST_METHOD'),
'referer' => getenv('HTTP_REFERER'),
'uri' => getenv('REQUEST_URI'),
'version' => VersionInfo::get(),
])
);
}
}
}
|
Use array_is_list() function when available
Suggested by Alexander M. Turek <[email protected]> in https://github.com/sebastianbergmann/phpunit/pull/4818#pullrequestreview-830852046 | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use function array_is_list;
use function is_array;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
*/
final class ArrayIsList extends Constraint
{
/**
* Returns a string representation of the constraint.
*/
public function toString(): string
{
return 'is list';
}
/**
* Evaluates the constraint for parameter $other. Returns true if the
* constraint is met, false otherwise.
*/
protected function matches(mixed $other): bool
{
if (!is_array($other)) {
return false;
}
if (function_exists('array_is_list')) {
return array_is_list($other);
}
// @todo Remove this code once we require PHP >= 8.1
if ($other === []) {
return true;
}
$expectedKey = 0;
foreach ($other as $key => $value) {
if ($key !== $expectedKey) {
return false;
}
$expectedKey++;
}
return true;
}
/**
* Returns the description of the failure.
*
* The beginning of failure messages is "Failed asserting that" in most
* cases. This method should return the second part of that sentence.
*/
protected function failureDescription(mixed $other): string
{
return 'an array ' . $this->toString();
}
}
| <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use function is_array;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
*/
final class ArrayIsList extends Constraint
{
/**
* Returns a string representation of the constraint.
*/
public function toString(): string
{
return 'is list';
}
/**
* Evaluates the constraint for parameter $other. Returns true if the
* constraint is met, false otherwise.
*/
protected function matches(mixed $other): bool
{
if (!is_array($other)) {
return false;
}
if ($other === []) {
return true;
}
$expectedKey = 0;
foreach ($other as $key => $value) {
if ($key !== $expectedKey) {
return false;
}
$expectedKey++;
}
return true;
}
/**
* Returns the description of the failure.
*
* The beginning of failure messages is "Failed asserting that" in most
* cases. This method should return the second part of that sentence.
*/
protected function failureDescription(mixed $other): string
{
return 'an array ' . $this->toString();
}
}
|
Fix the regexp that ate the quiz page | function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function fixPath (path) {
var match = RegExp('https?://[^/]*/(.*?)([?#]|$)').exec(window.location.href);
// If a stub exists, assume secure operation, so:
var stub = match && match[1];
if (stub) {
// (1) remove &admin= value from URL
path = path.replace(/(\?)(?:admin=[^&]*)*(.*?)(?:&admin=[^&]*)*/,'$1$2');
// (2) if URL begins with '/?', append stub to '/'
path = path.replace(/^(\/)(\?)/, '$1' + stub + '$2');
// (3) remove any port designation from URL
path = path.replace(/(https?:\/\/[^\/]*):[0-9]+/, '$1');
}
return path;
}
function apiRequest (url, obj, returnAsString) {
url = fixPath(url);
if ("object" === typeof obj) {
obj = JSON.stringify(obj);
} else if (!obj) {
obj = null;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader("Content-type","text/plain");
xhr.send(obj);
var ret = xhr.responseText;
if (!returnAsString) {
ret = JSON.parse(ret);
}
return ret;
}
| function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function fixPath (path) {
var match = RegExp('https?://[^/]*/(.*?)([?#]|$)').exec(window.location.href);
// If a stub exists, assume secure operation, so:
var stub = match && match[1];
if (stub) {
// (1) remove &admin= value from URL
path = path.replace(/(\?)(?:admin=[^&]*)*(.*?)(?:&)(?:admin=[^&]*)*/,'$1$2');
// (2) if URL begins with '/?', append stub to '/'
path = path.replace(/^(\/)(\?)/, '$1' + stub + '$2');
// (3) remove any port designation from URL
path = path.replace(/(https?:\/\/[^\/]*):[0-9]+/, '$1');
}
return path;
}
function apiRequest (url, obj, returnAsString) {
url = fixPath(url);
if ("object" === typeof obj) {
obj = JSON.stringify(obj);
} else if (!obj) {
obj = null;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader("Content-type","text/plain");
xhr.send(obj);
var ret = xhr.responseText;
if (!returnAsString) {
ret = JSON.parse(ret);
}
return ret;
}
|
Upgrade django-local-settings 1.0a12 => 1.0a13 | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a13',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a12',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Add simplejson as requirement for python 2.5 | """
Flask-MongoKit
--------------
Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask
applications.
Links
`````
* `documentation <http://packages.python.org/Flask-MongoKit>`_
* `development version <http://github.com/jarus/flask-mongokit/zipball/master#egg=Flask-MongoKit-dev>`_
* `MongoKit <http://namlook.github.com/mongokit/>`_
* `Flask <http://flask.pocoo.org>`_
"""
import sys
from setuptools import setup
install_requires = [
"Flask",
"MongoKit"
]
if sys.version_info < (2, 6):
install_requires.append('simplejson')
setup(
name='Flask-MongoKit',
version='0.6',
url='http://github.com/jarus/flask-mongokit',
license='BSD',
author='Christoph Heer',
author_email='[email protected]',
description='A Flask extension simplifies to use MongoKit',
long_description=__doc__,
py_modules=['flask_mongokit'],
zip_safe=False,
platforms='any',
install_requires=install_requires,
test_suite='tests.suite',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| """
Flask-MongoKit
--------------
Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask
applications.
Links
`````
* `documentation <http://packages.python.org/Flask-MongoKit>`_
* `development version <http://github.com/jarus/flask-mongokit/zipball/master#egg=Flask-MongoKit-dev>`_
* `MongoKit <http://namlook.github.com/mongokit/>`_
* `Flask <http://flask.pocoo.org>`_
"""
from setuptools import setup
setup(
name='Flask-MongoKit',
version='0.6',
url='http://github.com/jarus/flask-mongokit',
license='BSD',
author='Christoph Heer',
author_email='[email protected]',
description='A Flask extension simplifies to use MongoKit',
long_description=__doc__,
py_modules=['flask_mongokit'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'MongoKit'
],
test_suite='tests.suite',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Use browser test file with grunt connect | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bower: grunt.file.readJSON('bower.json'),
uglify: {
options: {
banner: '/*! This is hwcrypto.js <%= bower.version %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
},
build: {
src: 'hwcrypto.js',
dest: 'build/<%= pkg.name %>.min.js'
},
dist: {
options: {
beautify: true,
mangle: false,
compress: false
},
src: 'hwcrypto.js',
}
},
jshint: {
app: {
src: ['hwcrypto.js', 'test/*.js'],
},
},
mocha: {
test: {
src: ['test/api.html'],
options: {
run: true,
},
},
},
connect: {
server: {
options: {
keepalive: true,
port: 8888,
open: 'http://localhost:8888/test/okbrowser.html'
}
}
}
});
// Minification
grunt.loadNpmTasks('grunt-contrib-uglify');
// code check
grunt.loadNpmTasks('grunt-contrib-jshint');
// development server
grunt.loadNpmTasks('grunt-contrib-connect');
// testing
grunt.loadNpmTasks('grunt-mocha');
// Default task(s).
grunt.registerTask('default', ['mocha']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bower: grunt.file.readJSON('bower.json'),
uglify: {
options: {
banner: '/*! This is hwcrypto.js <%= bower.version %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
},
build: {
src: 'hwcrypto.js',
dest: 'build/<%= pkg.name %>.min.js'
},
dist: {
options: {
beautify: true,
mangle: false,
compress: false
},
src: 'hwcrypto.js',
}
},
jshint: {
app: {
src: ['hwcrypto.js', 'test/*.js'],
},
},
mocha: {
test: {
src: ['test/api.html'],
options: {
run: true,
},
},
},
connect: {
server: {
options: {
keepalive: true,
port: 8888,
open: 'http://localhost:8888/test/test.html'
}
}
}
});
// Minification
grunt.loadNpmTasks('grunt-contrib-uglify');
// code check
grunt.loadNpmTasks('grunt-contrib-jshint');
// development server
grunt.loadNpmTasks('grunt-contrib-connect');
// testing
grunt.loadNpmTasks('grunt-mocha');
// Default task(s).
grunt.registerTask('default', ['mocha']);
};
|
Make workload optional when editing vacancies | from flask_wtf import Form
from flask_babel import lazy_gettext as _ # noqa
from wtforms import StringField, SubmitField, TextAreaField, \
DateField, SelectField
from wtforms.validators import InputRequired
class VacancyForm(Form):
title = StringField(_('Title'), validators=[InputRequired(
message=_('A title is required.'))])
description = TextAreaField(_('Description'), validators=[InputRequired(
message=_('A description is required.'))])
start_date = DateField(_('Start date'), validators=[InputRequired(
message=_('Start date is required.'))])
end_date = DateField(_('End date'), validators=[InputRequired(
message=_('End date is required.'))])
contract_of_service = SelectField(_('Contract'),
choices=[('voltijd', _('Voltijd')),
('deeltijd', _('Deeltijd')),
('bijbaan', _('Bijbaan')),
('stage', _('Stage'))])
workload = StringField(_('Workload'))
company_id = SelectField(_('Company'), coerce=int)
submit = SubmitField(_('Submit'))
| from flask_wtf import Form
from flask_babel import lazy_gettext as _ # noqa
from wtforms import StringField, SubmitField, TextAreaField, \
DateField, SelectField
from wtforms.validators import InputRequired
class VacancyForm(Form):
title = StringField(_('Title'), validators=[InputRequired(
message=_('A title is required.'))])
description = TextAreaField(_('Description'), validators=[InputRequired(
message=_('A description is required.'))])
start_date = DateField(_('Start date'), validators=[InputRequired(
message=_('Start date is required.'))])
end_date = DateField(_('End date'), validators=[InputRequired(
message=_('End date is required.'))])
contract_of_service = SelectField(_('Contract'),
choices=[('voltijd', _('Voltijd')),
('deeltijd', _('Deeltijd')),
('bijbaan', _('Bijbaan')),
('stage', _('Stage'))])
workload = StringField(_('Workload'), validators=[InputRequired(
message=_('Workload is required.'))])
company_id = SelectField(_('Company'), coerce=int)
submit = SubmitField(_('Submit'))
|
Check to see if browserify has modified process to check for browser environment. | var write = require('./write'),
geojson = require('./geojson'),
prj = require('./prj'),
JSZip = require('jszip');
module.exports = function(gj, options) {
var zip = new JSZip(),
layers = zip.folder(options && options.folder ? options.folder : 'layers');
[geojson.point(gj), geojson.line(gj), geojson.polygon(gj)]
.forEach(function(l) {
if (l.geometries.length) {
write(
// field definitions
l.properties,
// geometry type
l.type,
// geometries
l.geometries,
function(err, files) {
var fileName = options && options.types[l.type.toLowerCase()] ? options.types[l.type.toLowerCase()] : l.type;
layers.file(fileName + '.shp', files.shp.buffer, { binary: true });
layers.file(fileName + '.shx', files.shx.buffer, { binary: true });
layers.file(fileName + '.dbf', files.dbf.buffer, { binary: true });
layers.file(fileName + '.prj', prj);
});
}
});
var generateOptions = { compression:'STORE' };
if (!process.browser) {
generateOptions.type = 'nodebuffer';
}
return zip.generate(generateOptions);
};
| var write = require('./write'),
geojson = require('./geojson'),
prj = require('./prj'),
JSZip = require('jszip');
module.exports = function(gj, options) {
var zip = new JSZip(),
layers = zip.folder(options && options.folder ? options.folder : 'layers');
[geojson.point(gj), geojson.line(gj), geojson.polygon(gj)]
.forEach(function(l) {
if (l.geometries.length) {
write(
// field definitions
l.properties,
// geometry type
l.type,
// geometries
l.geometries,
function(err, files) {
var fileName = options && options.types[l.type.toLowerCase()] ? options.types[l.type.toLowerCase()] : l.type;
layers.file(fileName + '.shp', files.shp.buffer, { binary: true });
layers.file(fileName + '.shx', files.shx.buffer, { binary: true });
layers.file(fileName + '.dbf', files.dbf.buffer, { binary: true });
layers.file(fileName + '.prj', prj);
});
}
});
var generateOptions = { compression:'STORE' };
if (typeof window === 'undefined') {
generateOptions.type = 'nodebuffer';
}
return zip.generate(generateOptions);
};
|
Add a loading indicator on the auth page | const React = require('react');
const Utils = require('../utils');
const AuthentificationPage = React.createClass({
getInitialState() { return { loading: false }; },
openAuthWindow() {
this.setState({ loading: true });
Utils.Socket.emit('youtube/auth');
},
render() {
if (this.state.loading) {
return (
<div className="text-page">
<div className="jumbotron">
<h1 className="display-3">YouWatch</h1>
<p className="lead">Please fulfill the informations on the other window</p>
<p className="lead">
<button className="btn btn-primary btn-lg disabled"><i className="fa fa-spinner fa-pulse" /> Logging in...</button>
</p>
</div>
</div>
);
}
return (
<div className="text-page">
<div className="jumbotron">
<h1 className="display-3">YouWatch</h1>
<p className="lead">{'Let\'s connect to your YouTube Account'}</p>
<p className="lead">
<button className="btn btn-primary btn-lg" onClick={this.openAuthWindow}>Log in</button>
</p>
</div>
</div>
);
},
});
module.exports = AuthentificationPage;
| const React = require('react');
const Utils = require('../utils');
const AuthentificationPage = React.createClass({
getInitialState() { return { loading: false }; },
openAuthWindow() {
this.setState({ loading: true });
Utils.Socket.emit('youtube/auth');
},
render() {
if (this.state.loading) {
return (
<div className="text-page">
<div className="jumbotron">
<h1 className="display-3">YouWatch</h1>
<p className="lead">Please fulfill the informations on the other window</p>
<p className="lead">
<button className="btn btn-primary btn-lg disabled">Logging in...</button>
</p>
</div>
</div>
);
}
return (
<div className="text-page">
<div className="jumbotron">
<h1 className="display-3">YouWatch</h1>
<p className="lead">{'Let\'s connect to your YouTube Account'}</p>
<p className="lead">
<button className="btn btn-primary btn-lg" onClick={this.openAuthWindow}>Log in</button>
</p>
</div>
</div>
);
},
});
module.exports = AuthentificationPage;
|
Fix unicode source code on py3 | import json
from . import _dukpy
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
try: # pragma: no cover
unicode
string_types = (str, unicode)
jscode_type = str
except NameError: # pragma: no cover
string_types = (bytes, str)
jscode_type = str
class JSInterpreter(object):
"""JavaScript Interpreter"""
def __init__(self):
self._ctx = _dukpy.create_context()
def evaljs(self, code, **kwargs):
"""Runs JavaScript code in the context of the interpreter.
All arguments will be converted to plain javascript objects
through the JSON encoder and will be available in `dukpy`
global object.
Returns the last object on javascript stack.
"""
jsvars = json.dumps(kwargs)
jscode = code
if not isinstance(code, string_types):
jscode = ';\n'.join(code)
if not isinstance(jscode, str):
# Source code must be str on both Py2 and Py3
# so it must be encoded on Py2 and decoded on Py3
if isinstance(jscode, bytes):
jscode = jscode.decode('utf-8')
else:
jscode = jscode.encode('utf-8')
res = _dukpy.eval_string(self._ctx, jscode, jsvars)
if res is None:
return None
return json.loads(res.decode('utf-8'))
def evaljs(code, **kwargs):
"""Evaluates the given ``code`` as JavaScript and returns the result"""
return JSInterpreter().evaljs(code, **kwargs) | import json
from . import _dukpy
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
try: # pragma: no cover
unicode
string_types = (str, unicode)
except NameError: # pragma: no cover
string_types = (bytes, str)
class JSInterpreter(object):
"""JavaScript Interpreter"""
def __init__(self):
self._ctx = _dukpy.create_context()
def evaljs(self, code, **kwargs):
"""Runs JavaScript code in the context of the interpreter.
All arguments will be converted to plain javascript objects
through the JSON encoder and will be available in `dukpy`
global object.
Returns the last object on javascript stack.
"""
jsvars = json.dumps(kwargs)
jscode = code
if not isinstance(code, string_types):
jscode = ';\n'.join(code)
if not isinstance(jscode, bytes):
jscode = jscode.encode('utf-8')
res = _dukpy.eval_string(self._ctx, jscode, jsvars)
if res is None:
return None
return json.loads(res.decode('utf-8'))
def evaljs(code, **kwargs):
"""Evaluates the given ``code`` as JavaScript and returns the result"""
return JSInterpreter().evaljs(code, **kwargs) |
Fix passing arguments to async() blocks | <?php
namespace CrystalPlanet\Redshift\EventLoop;
class EventLoop
{
/**
* @var array
*/
private $queue = [];
/**
* Adds a new task to the queue.
*
* @param callable $callback
* @param mixed ...$args Arguments to be supplied to the $callback
* at the time of execution.
*/
public function put(callable $callback, ...$args)
{
array_push($this->queue, new Task($callback, ...$args));
}
/**
* Returns the next task in the queue.
*
* @return Task
*/
public function take()
{
return array_shift($this->queue);
}
/**
* Starts the event loop.
* It will run until there are no more tasks sheduled for execution.
*
* If a task was blocked/interrupted,
* it is put back at the end of the queue.
*/
public function run()
{
while (!$this->isEmpty()) {
$task = $this->take();
$task->run();
if ($task->valid()) {
array_push($this->queue, $task);
}
}
}
/**
* Checks if there are no more tasks in the queue.
*
* @return boolean
*/
private function isEmpty()
{
return empty($this->queue);
}
}
| <?php
namespace CrystalPlanet\Redshift\EventLoop;
class EventLoop
{
/**
* @var array
*/
private $queue = [];
/**
* Adds a new task to the queue.
*
* @param callable $callback
* @param mixed ...$args Arguments to be supplied to the $callback
* at the time of execution.
*/
public function put(callable $callback, ...$args)
{
array_push($this->queue, new Task($callback, $args));
}
/**
* Returns the next task in the queue.
*
* @return Task
*/
public function take()
{
return array_shift($this->queue);
}
/**
* Starts the event loop.
* It will run until there are no more tasks sheduled for execution.
*
* If a task was blocked/interrupted,
* it is put back at the end of the queue.
*/
public function run()
{
while (!$this->isEmpty()) {
$task = $this->take();
$task->run();
if ($task->valid()) {
array_push($this->queue, $task);
}
}
}
/**
* Checks if there are no more tasks in the queue.
*
* @return boolean
*/
private function isEmpty()
{
return empty($this->queue);
}
}
|
Use the correct type for numbers! | package main
import (
"encoding/json"
"fmt"
"os"
)
func parseObj(in interface{}, out map[string]interface{}, prefix string) {
switch vv := in.(type) {
case map[string]interface{}:
for key, value := range vv {
parseObj(value, out, fmt.Sprintf("%s.%s", prefix, key))
}
case []interface{}:
for index, value := range vv {
parseObj(value, out, fmt.Sprintf("%s.%d", prefix, index))
}
case string:
out[prefix[1:]] = vv
case float64:
out[prefix[1:]] = vv
case bool:
out[prefix[1:]] = vv
default:
fmt.Fprintln(os.Stderr, "Input appears to be invalid json")
os.Exit(1)
}
}
func main() {
var in interface{}
out := make(map[string]interface{})
dec := json.NewDecoder(os.Stdin)
dec.Decode(&in)
parseObj(in, out, "")
if len(os.Args) > 1 {
key := os.Args[1]
if value, ok := out[key]; ok {
fmt.Println(value)
}
} else {
for key, value := range out {
fmt.Printf("%s=%v\n", key, value)
}
}
}
| package main
import (
"encoding/json"
"fmt"
"os"
)
func parseObj(in interface{}, out map[string]interface{}, prefix string) {
switch vv := in.(type) {
case map[string]interface{}:
for key, value := range vv {
parseObj(value, out, fmt.Sprintf("%s.%s", prefix, key))
}
case []interface{}:
for index, value := range vv {
parseObj(value, out, fmt.Sprintf("%s.%d", prefix, index))
}
case string:
out[prefix[1:]] = vv
case int:
out[prefix[1:]] = vv
case bool:
out[prefix[1:]] = vv
default:
fmt.Fprintln(os.Stderr, "Input appears to be invalid json")
os.Exit(1)
}
}
func main() {
var in interface{}
out := make(map[string]interface{})
dec := json.NewDecoder(os.Stdin)
dec.Decode(&in)
parseObj(in, out, "")
if len(os.Args) > 1 {
key := os.Args[1]
if value, ok := out[key]; ok {
fmt.Println(value)
}
} else {
for key, value := range out {
fmt.Printf("%s=%v\n", key, value)
}
}
}
|
Revert "Bump version to 0.2.0"
This reverts commit 189e4bc4bcd7a6764740d9974a633996f6ba1fc7. | import os.path
import sys
from setuptools import setup, find_packages
from build_manpage import build_manpage
HOME=os.path.expanduser('~')
setup(
name='popup',
version='0.1.0',
author='Jay Edwards',
cmdclass={'build_manpage': build_manpage},
author_email='[email protected]',
packages=['PopupServer', 'PopupServer.test'],
package_data={'PopupServer': ['playbooks/*/*.yaml']},
data_files=[('%s/.popup/config/ssh_configs' % HOME, []),
('%s/.popup/config/ssh_control' % HOME, []), ('%s/.popup/keys' % HOME, []),
('%s/.popup/manifests' % HOME, []), ('%s/share/man/man1' % sys.prefix, ['doc/popup.1'])],
url="http://pypi.python.org/pypi/popup",
license='BSD',
description='Quickly setup an EC2 server running OpenVPN and other useful tools',
long_description=open('README.txt').read(),
install_requires=[
"ansible == 0.9",
"boto >= 2.7.0",
],
setup_requires=[
"github-distutils >= 0.1.0",
],
entry_points = {
'console_scripts': [
'popup = PopupServer.popup:main',
],
'distutils.commands': [
'build_manpage = build_manpage.build_manpage'
]
}
)
| import os.path
import sys
from setuptools import setup, find_packages
from build_manpage import build_manpage
HOME=os.path.expanduser('~')
setup(
name='popup',
version='0.2.0',
author='Jay Edwards',
cmdclass={'build_manpage': build_manpage},
author_email='[email protected]',
packages=['PopupServer', 'PopupServer.test'],
package_data={'PopupServer': ['playbooks/*/*.yaml']},
data_files=[('%s/.popup/config/ssh_configs' % HOME, []),
('%s/.popup/config/ssh_control' % HOME, []), ('%s/.popup/keys' % HOME, []),
('%s/.popup/manifests' % HOME, []), ('%s/share/man/man1' % sys.prefix, ['doc/popup.1'])],
url="http://pypi.python.org/pypi/popup",
license='BSD',
description='Quickly setup an EC2 server running OpenVPN and other useful tools',
long_description=open('README.txt').read(),
install_requires=[
"ansible == 0.9",
"boto >= 2.7.0",
],
setup_requires=[
"github-distutils >= 0.1.0",
],
entry_points = {
'console_scripts': [
'popup = PopupServer.popup:main',
],
'distutils.commands': [
'build_manpage = build_manpage.build_manpage'
]
}
)
|
Change search type to cross_fields and operator to and | var module = angular.module('JGivenApp',['ngSanitize']);
var elasticSearchHost = 'localhost'
module.controller(
'ApplicationController',
['$scope', '$http',
function( $scope, $http ) {
$scope.getScenarios = function() {
console.log("Searching for "+$scope.search);
data = {
query: {
multi_match: {
query: $scope.search,
type: 'cross_fields',
operator: 'and',
fields: ['description', '_all']
}
},
size: 20,
highlight : {
fields : {
"description" : {}
}
}
};
$http({
method: 'POST',
url: 'http://' + elasticSearchHost + ':9200/r14.9/scenario/_search?pretty=true',
data: data
}).success( function(data) {
console.log( JSON.stringify( data.hits.hits ) );
$scope.searchResult = data;
$scope.scenarios = data.hits.hits;
});
};
$scope.trustHtml = function( html ) {
return $sce.trustAsHtml( html );
};
}
]);
| var module = angular.module('JGivenApp',['ngSanitize']);
var elasticSearchHost = 'localhost'
module.controller(
'ApplicationController',
['$scope', '$http',
function( $scope, $http ) {
$scope.getScenarios = function() {
console.log("Searching for "+$scope.search);
data = {
query: {
multi_match: {
query: $scope.search,
type: 'most_fields',
fields: ['description', '_all']
}
},
size: 20,
highlight : {
fields : {
"description" : {}
}
}
};
$http({
method: 'POST',
url: 'http://' + elasticSearchHost + ':9200/r14.9/scenario/_search?pretty=true',
data: data
}).success( function(data) {
console.log( JSON.stringify( data.hits.hits ) );
$scope.searchResult = data;
$scope.scenarios = data.hits.hits;
});
};
$scope.trustHtml = function( html ) {
return $sce.trustAsHtml( html );
};
}
]);
|
Use trait methods to get column names | <?php
namespace Yajra\Auditable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
class AuditableTraitObserver
{
/**
* Model's creating event hook.
*
* @param Model $model
*/
public function creating(Model $model)
{
$createdBy = $model->getCreatedByColumn();
$updatedBy = $model->getUpdatedByColumn();
if (! $model->$createdBy) {
$model->$createdBy = $this->getAuthenticatedUserId();
}
if (! $model->$updatedBy) {
$model->$updatedBy = $this->getAuthenticatedUserId();
}
}
/**
* Get authenticated user id depending on model's auth guard.
*
* @return int
*/
protected function getAuthenticatedUserId()
{
return auth()->check() ? auth()->id() : null;
}
/**
* Model's updating event hook.
*
* @param Model $model
*/
public function updating(Model $model)
{
$updatedBy = $model->getUpdatedByColumn();
if (! $model->isDirty($updatedBy)) {
$model->$updatedBy = $this->getAuthenticatedUserId();
}
}
/**
* Model's deleting event hook
*
* @param Model $model
*/
public function deleting(Model $model)
{
$deletedBy = $model->getDeletedByColumn();
if (Schema::hasColumn($model->getTable(), $deletedBy)) {
if (! $model->$deletedBy) {
$model->$deletedBy = $this->getAuthenticatedUserId();
}
}
}
}
| <?php
namespace Yajra\Auditable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
class AuditableTraitObserver
{
/**
* Model's creating event hook.
*
* @param Model $model
*/
public function creating(Model $model)
{
if (! $model->created_by) {
$model->created_by = $this->getAuthenticatedUserId();
}
if (! $model->updated_by) {
$model->updated_by = $this->getAuthenticatedUserId();
}
}
/**
* Get authenticated user id depending on model's auth guard.
*
* @return int
*/
protected function getAuthenticatedUserId()
{
return auth()->check() ? auth()->id() : null;
}
/**
* Model's updating event hook.
*
* @param Model $model
*/
public function updating(Model $model)
{
if (! $model->isDirty('updated_by')) {
$model->updated_by = $this->getAuthenticatedUserId();
}
}
/**
* Model's deleting event hook
*
* @param Model $model
*/
public function deleting(Model $model)
{
if (Schema::hasColumn($model->getTable(), 'deleted_by')) {
if (! $model->deleted_by) {
$model->deleted_by = $this->getAuthenticatedUserId();
}
}
}
}
|
Add platform type to dao | package org.pdxfinder.graph.dao;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 21/07/2017.
*/
@NodeEntity
public class Platform {
@GraphId
private Long id;
private String name;
private String url;
private String type;
@Relationship(type = "GROUP", direction = Relationship.INCOMING)
private Group group;
@Relationship(type = "ASSOCIATED_WITH")
private Set<PlatformAssociation> platformAssociations;
public Platform() {
}
public Platform(Set<PlatformAssociation> platformAssociations) {
this.platformAssociations = platformAssociations;
}
public Set<PlatformAssociation> getPlatformAssociations() {
return platformAssociations;
}
public void setPlatformAssociations(Set<PlatformAssociation> platformAssociations) {
this.platformAssociations = platformAssociations;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| package org.pdxfinder.graph.dao;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 21/07/2017.
*/
@NodeEntity
public class Platform {
@GraphId
private Long id;
private String name;
private String url;
@Relationship(type = "GROUP", direction = Relationship.INCOMING)
private Group group;
@Relationship(type = "ASSOCIATED_WITH")
private Set<PlatformAssociation> platformAssociations;
public Platform() {
}
public Platform(Set<PlatformAssociation> platformAssociations) {
this.platformAssociations = platformAssociations;
}
public Set<PlatformAssociation> getPlatformAssociations() {
return platformAssociations;
}
public void setPlatformAssociations(Set<PlatformAssociation> platformAssociations) {
this.platformAssociations = platformAssociations;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
}
|
[core] ENHANCE: Add UserInputSource as a InputProviderSource | package org.museautomation.core.task.input;
import org.museautomation.core.task.state.*;
/**
* @author Christopher L Merrill (see LICENSE.txt for license details)
*/
public abstract class ResolvedInputSource
{
public abstract String getDescription();
public static class TaskStateSource extends ResolvedInputSource
{
public TaskStateSource(InterTaskState state)
{
_state = state;
}
@Override
public String getDescription()
{
return "from task state " + _state.getStateDefinitionId();
}
public InterTaskState getState()
{
return _state;
}
private final InterTaskState _state;
}
public static class InputProviderSource extends ResolvedInputSource
{
public InputProviderSource(TaskInputProvider provider)
{
_provider = provider;
}
@Override
public String getDescription()
{
return "from task input provider " + _provider.getDescription();
}
public TaskInputProvider getProvider()
{
return _provider;
}
private final TaskInputProvider _provider;
}
@SuppressWarnings("unused") // used in UI
public static class UserInputSource extends ResolvedInputSource
{
@Override
public String getDescription()
{
return "from user";
}
}
public static class DefaultValueSource extends ResolvedInputSource
{
@Override
public String getDescription()
{
return "from default value ";
}
}
} | package org.museautomation.core.task.input;
import org.museautomation.core.task.state.*;
/**
* @author Christopher L Merrill (see LICENSE.txt for license details)
*/
public abstract class ResolvedInputSource
{
public abstract String getDescription();
public static class TaskStateSource extends ResolvedInputSource
{
public TaskStateSource(InterTaskState state)
{
_state = state;
}
@Override
public String getDescription()
{
return "from task state " + _state.getStateDefinitionId();
}
public InterTaskState getState()
{
return _state;
}
private final InterTaskState _state;
}
public static class InputProviderSource extends ResolvedInputSource
{
public InputProviderSource(TaskInputProvider provider)
{
_provider = provider;
}
@Override
public String getDescription()
{
return "from task input provider " + _provider.getDescription();
}
public TaskInputProvider getProvider()
{
return _provider;
}
private final TaskInputProvider _provider;
}
public static class DefaultValueSource extends ResolvedInputSource
{
@Override
public String getDescription()
{
return "from default value ";
}
}
} |
Throw exception if null is provided as service interfaces array. | /**
* This file is part of Everit - Component Metadata.
*
* Everit - Component Metadata is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Everit - Component Metadata is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Everit - Component Metadata. If not, see <http://www.gnu.org/licenses/>.
*/
package org.everit.osgi.ecm.metadata;
public class ServiceMetadata {
public static class ServiceMetadataBuilder {
private Class<?>[] clazzes = new Class<?>[0];
public ServiceMetadata build() {
return new ServiceMetadata(clazzes);
}
public ServiceMetadataBuilder withClazzes(final Class<?>[] clazzes) {
if (clazzes == null) {
throw new MetadataValidationException(
"Null cannot be provided as service interface array for ServiceMetadata");
}
this.clazzes = clazzes.clone();
return this;
}
}
private final Class<?>[] clazzes;
private ServiceMetadata(final Class<?>[] clazzes) {
this.clazzes = clazzes;
}
public Class<?>[] getClazzes() {
if (clazzes != null) {
return clazzes.clone();
} else {
return null;
}
}
}
| /**
* This file is part of Everit - Component Metadata.
*
* Everit - Component Metadata is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Everit - Component Metadata is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Everit - Component Metadata. If not, see <http://www.gnu.org/licenses/>.
*/
package org.everit.osgi.ecm.metadata;
public class ServiceMetadata {
public static class ServiceMetadataBuilder {
private Class<?>[] clazzes;
public ServiceMetadata build() {
return new ServiceMetadata(clazzes);
}
public ServiceMetadataBuilder withClazzes(final Class<?>[] clazzes) {
if (clazzes == null) {
this.clazzes = null;
} else {
this.clazzes = clazzes.clone();
}
return this;
}
}
private final Class<?>[] clazzes;
private ServiceMetadata(final Class<?>[] clazzes) {
this.clazzes = clazzes;
}
public Class<?>[] getClazzes() {
if (clazzes != null) {
return clazzes.clone();
} else {
return null;
}
}
}
|
Make handle_read a private method | # -*- coding: utf-8 -*-
import logging
import time
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
class KafkaReader(object):
def __init__(self, host, port, group, topic, reconnect_wait_time=2):
"""
Initialize Kafka reader
"""
self.host = host
self.port = port
self.group = group
self.topic = topic
self.reconnect_wait_time = reconnect_wait_time
# Initialized on read
self.kafka_client = None
self.consumer = None
def connect(self):
connection = "{0}:{1}".format(self.host, self.port)
logging.info("Connecting to Kafka at %s...", connection)
self.kafka_client = KafkaClient(connection)
self.consumer = SimpleConsumer(self.kafka_client,
self.group,
self.topic)
def read(self):
"""
Read from Kafka. Reconnect on error.
"""
while True:
for msg in self._handle_read():
yield msg
def _handle_read(self):
"""
Yield messages from Kafka topic
"""
try:
self.connect()
for raw_message in self.consumer:
yield raw_message.message.value
except Exception as e:
logging.error("Kafka error: %s.", e)
logging.error("Trying to reconnect to %s:%s", self.host, self.port)
time.sleep(self.reconnect_wait_time)
pass
| # -*- coding: utf-8 -*-
import logging
import time
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
class KafkaReader(object):
def __init__(self, host, port, group, topic, reconnect_wait_time=2):
"""
Initialize Kafka reader
"""
self.host = host
self.port = port
self.group = group
self.topic = topic
self.reconnect_wait_time = reconnect_wait_time
# Initialized on read
self.kafka_client = None
self.consumer = None
def connect(self):
connection = "{0}:{1}".format(self.host, self.port)
logging.info("Connecting to Kafka at %s...", connection)
self.kafka_client = KafkaClient(connection)
self.consumer = SimpleConsumer(self.kafka_client,
self.group,
self.topic)
def read(self):
"""
Read from Kafka. Reconnect on error.
"""
while True:
for msg in self.handle_read():
yield msg
def handle_read(self):
"""
Yield messages from Kafka topic
"""
try:
self.connect()
for raw_message in self.consumer:
yield raw_message.message.value
except Exception as e:
logging.error("Kafka error: %s.", e)
logging.error("Trying to reconnect to %s:%s", self.host, self.port)
time.sleep(self.reconnect_wait_time)
pass
|
Fix method to always return a value. | Application.Services.factory('Events', ['$filter', EventsService]);
function EventsService($filter) {
var service = {
date: '',
addConvertedTime: function (project) {
project.reviews = service.update(project.open_reviews);
project.samples = service.update(project.samples);
project.processes = service.update(project.processes);
project.notes = service.update(project.notes);
project.drafts = service.update(project.drafts);
return project;
},
update: function (items) {
items.forEach(function (item) {
var item_date = new Date(0);
item_date.setUTCSeconds(item.mtime.epoch_time);
item.converted_mtime = Date.UTC(item_date.getUTCFullYear(), item_date.getUTCMonth(), item_date.getUTCDay());
});
return items;
},
prepareCalendarEvent: function (items) {
var calendar_event = [];
if (items.length !== 0) {
var grouped_by_convertedtime = $filter('groupBy')(items, 'converted_mtime');
Object.keys(grouped_by_convertedtime).forEach(function (key) {
var d = new Date(0);
var value = grouped_by_convertedtime[key][0];
d.setUTCSeconds(value.mtime.epoch_time);
calendar_event.push({title: value.title, start: d});
});
}
return calendar_event;
},
updateDate: function (project, date) {
project.date = date;
return project;
}
};
return service;
}
| Application.Services.factory('Events', ['$filter', EventsService]);
function EventsService($filter) {
var service = {
date: '',
addConvertedTime: function (project) {
project.reviews = service.update(project.open_reviews);
project.samples = service.update(project.samples);
project.processes = service.update(project.processes);
project.notes = service.update(project.notes);
project.drafts = service.update(project.drafts);
return project;
},
update: function (items) {
items.forEach(function (item) {
var item_date = new Date(0);
item_date.setUTCSeconds(item.mtime.epoch_time);
item.converted_mtime = Date.UTC(item_date.getUTCFullYear(), item_date.getUTCMonth(), item_date.getUTCDay());
});
return items;
},
prepareCalendarEvent: function (items) {
var calendar_event = [];
if (items.length !== 0) {
var grouped_by_convertedtime = $filter('groupBy')(items, 'converted_mtime');
Object.keys(grouped_by_convertedtime).forEach(function (key) {
var d = new Date(0);
var value = grouped_by_convertedtime[key][0];
d.setUTCSeconds(value.mtime.epoch_time);
calendar_event.push({title: value.title, start: d});
});
return calendar_event;
}
},
updateDate: function (project, date) {
project.date = date;
return project;
}
};
return service;
}
|
Format JavaScript files with Prettier: scripts/draft-js/__github__/src
Differential Revision: D32201648
fbshipit-source-id: f94342845cbe6454bb7ae4f02814e788fb25de9f | /**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @emails oncall+ads_integration_management
* @flow strict-local
* @format
*/
'use strict';
const MAX_ASCII_CHARACTER = 127;
/**
* Serializes strings with non-ASCII characters to their Unicode escape
* sequences (eg. \u2022), to avoid hitting this lint rule:
* "Source code should only include printable US-ASCII bytes"
*/
const NonASCIIStringSnapshotSerializer = {
test(val: mixed): boolean {
if (typeof val !== 'string') {
return false;
}
for (let i = 0; i < val.length; i++) {
if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) {
return true;
}
}
return false;
},
print: (val: string): string => {
return (
'"' +
val
.split('')
.map((char) => {
const code = char.charCodeAt(0);
return code > MAX_ASCII_CHARACTER
? '\\u' + code.toString(16).padStart(4, '0')
: char;
})
.join('')
// Keep the same behaviour as Jest's regular string snapshot
// serialization, which escapes double quotes.
.replace(/"/g, '\\"') +
'"'
);
},
};
module.exports = NonASCIIStringSnapshotSerializer;
| /**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @emails oncall+ads_integration_management
* @flow strict-local
* @format
*/
'use strict';
const MAX_ASCII_CHARACTER = 127;
/**
* Serializes strings with non-ASCII characters to their Unicode escape
* sequences (eg. \u2022), to avoid hitting this lint rule:
* "Source code should only include printable US-ASCII bytes"
*/
const NonASCIIStringSnapshotSerializer = {
test(val: mixed): boolean {
if (typeof val !== 'string') {
return false;
}
for (let i = 0; i < val.length; i++) {
if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) {
return true;
}
}
return false;
},
print: (val: string): string => {
return (
'"' +
val
.split('')
.map(char => {
const code = char.charCodeAt(0);
return code > MAX_ASCII_CHARACTER
? '\\u' + code.toString(16).padStart(4, '0')
: char;
})
.join('')
// Keep the same behaviour as Jest's regular string snapshot
// serialization, which escapes double quotes.
.replace(/"/g, '\\"') +
'"'
);
},
};
module.exports = NonASCIIStringSnapshotSerializer;
|
Make outlook emit single files | import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
class OutlookPSTIngestor(Ingestor, TempFileSupport, OLESupport, ShellSupport):
MIME_TYPES = ['application/vnd.ms-outlook']
EXTENSIONS = ['pst', 'ost', 'pab']
BASE_SCORE = 5
COMMAND_TIMEOUT = 12 * 60 * 60
def ingest(self, file_path, entity):
entity.schema = model.get('Package')
self.extract_ole_metadata(file_path, entity)
temp_dir = self.make_empty_directory()
try:
self.exec_command('readpst',
'-e', # make subfolders, files per message
'-S', # single files
'-D', # include deleted
# '-r', # recursive structure
'-8', # utf-8 where possible
'-cv', # export vcards
# '-q', # quiet
'-o', temp_dir,
file_path)
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
except Exception:
log.exception("Failed to unpack PST.")
# Handle partially extracted archives.
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
raise
| import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
class OutlookPSTIngestor(Ingestor, TempFileSupport, OLESupport, ShellSupport):
MIME_TYPES = ['application/vnd.ms-outlook']
EXTENSIONS = ['pst', 'ost', 'pab']
BASE_SCORE = 5
COMMAND_TIMEOUT = 12 * 60 * 60
def ingest(self, file_path, entity):
entity.schema = model.get('Package')
self.extract_ole_metadata(file_path, entity)
temp_dir = self.make_empty_directory()
try:
self.exec_command('readpst',
'-e', # make subfolders, files per message
'-D', # include deleted
'-r', # recursive structure
'-8', # utf-8 where possible
'-b',
'-q', # quiet
'-o', temp_dir,
file_path)
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
except Exception:
log.exception("Failed to unpack PST.")
# Handle partially extracted archives.
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
raise
|
refactor: Change userPos func to build API url | // use strict:
"use strict";
// Function gets the location of the user provided the user opts in
// Function for geolocation, success and error adapted from Sitepoint;
// URL https://www.sitepoint.com/html5-geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPosition, showError);
} else {
alert('Geolocation is not supported in your browser so cannot display your local weather');
}
// Success callback function
// Determine's user location and builds in latitude and longitude into the DarkSky API url
function userPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log("User's latitude is " + lat + " User's longitude is " + lon);
// Next line builds the API url for DarkSky
var darkSkyAPI = 'https://api.darksky.net/forecast/' + darkSkyToken + '/' + lat + ',' + lon;
console.log(darkSkyAPI);
return darkSkyAPI;
}
// Error callback function
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
$.ajax({
url: 'https://api.darksky.net/forecast/c9ef245f82717baa8be804cab471c6f2/51,0',
type: "GET",
dataType: "jsonp",
success: function (weather) {
$('#temperature').prepend(weather.currently.temperature);
$('#weather-icon').append(weather.currently.icon);
// console.log(weather.currently.icon);
},
xhrFields: {
withCredentials: false
}
}) // end ajax | // use strict:
"use strict";
// Function gets the location of the user provided the user opts in
// function adapted from Sitepoint; https://www.sitepoint.com/html5-geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPosition, showError);
} else {
alert('Geolocation is not supported in your browser so cannot display your local weather');
}
// Success callback function
function userPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log("User's latitude is " + lat + " User's longitude is " + lon);
// return lat, lon; // how to return two vars?
}
// Error callback function
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
|
Use padding on the index | from typing import Iterable, Tuple
def gallery(samples: Iterable[Tuple[str, str]], *, refresh: bool = False) -> str:
lines = []
for url, template in samples:
if refresh:
url += "?time=0"
else:
url += "?width=300&height=300"
lines.append(
f"""
<a href="{template or url}">
<img src="{url}" style="padding: 5px;">
</a>
"""
)
if refresh:
lines.append(
r"""
<script>
setInterval(function() {
var images = document.images;
for (var i=0; i<images.length; i++) {
images[i].src = images[i].src.replace(
/\btime=[^&]*/, 'time=' + new Date().getTime()
);
}
}, 2000);
</script>
"""
)
return "\n".join(lines).replace("\n" + " " * 12, "\n")
| from typing import Iterable, Tuple
def gallery(samples: Iterable[Tuple[str, str]], *, refresh: bool = False) -> str:
lines = []
for url, template in samples:
if refresh:
url += "?time=0"
lines.append(
f"""
<a href="{template or url}">
<img src="{url}" width="500" style="padding: 5px;">
</a>
"""
)
if refresh:
lines.append(
r"""
<script>
setInterval(function() {
var images = document.images;
for (var i=0; i<images.length; i++) {
images[i].src = images[i].src.replace(
/\btime=[^&]*/, 'time=' + new Date().getTime()
);
}
}, 2000);
</script>
"""
)
return "\n".join(lines).replace("\n" + " " * 12, "\n")
|
Add element identifier in laralytics_custom table | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Class CreateLaralyticsCustomTable
*/
class CreateLaralyticsCustomTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('laralytics_custom', function (Blueprint $table) {
$engine = Config::get('database.default');
$table->increments('id');
$table->integer('user_id')->index()->nullable();
$table->string('hash', 64)->index();
$table->string('host', 255)->index();
$table->string('path', 255);
$table->string('version', 255)->index();
$table->string('event', 64)->index();
$table->string('element', 255)->index();
$table->text('data');
// Auto timestamp for postgreSQL and others
if ($engine === 'pgsql') {
$table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)'));
} else {
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
}
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('laralytics_custom');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Class CreateLaralyticsCustomTable
*/
class CreateLaralyticsCustomTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('laralytics_custom', function (Blueprint $table) {
$engine = Config::get('database.default');
$table->increments('id');
$table->integer('user_id')->index()->nullable();
$table->string('hash', 64)->index();
$table->string('host', 255)->index();
$table->string('path', 255);
$table->string('version', 255)->index();
$table->string('event', 64)->index();
$table->text('data');
// Auto timestamp for postgreSQL and others
if ($engine === 'pgsql') {
$table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)'));
} else {
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
}
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('laralytics_custom');
}
}
|
Enforce consistent artisan command tag namespacing | <?php
declare(strict_types=1);
namespace Rinvex\Attributes\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:publish:attributes {--f|force : Overwrite any existing files.} {--r|resource=all}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Rinvex Attributes Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
switch ($this->option('resource')) {
case 'config':
$this->call('vendor:publish', ['--tag' => 'rinvex/attributes::config', '--force' => $this->option('force')]);
break;
case 'migrations':
$this->call('vendor:publish', ['--tag' => 'rinvex/attributes::migrations', '--force' => $this->option('force')]);
break;
default:
$this->call('vendor:publish', ['--tag' => 'rinvex/attributes::config', '--force' => $this->option('force')]);
$this->call('vendor:publish', ['--tag' => 'rinvex/attributes::migrations', '--force' => $this->option('force')]);
break;
}
$this->line('');
}
}
| <?php
declare(strict_types=1);
namespace Rinvex\Attributes\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:publish:attributes {--f|force : Overwrite any existing files.} {--r|resource=all}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Rinvex Attributes Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
switch ($this->option('resource')) {
case 'config':
$this->call('vendor:publish', ['--tag' => 'rinvex-attributes-config', '--force' => $this->option('force')]);
break;
case 'migrations':
$this->call('vendor:publish', ['--tag' => 'rinvex-attributes-migrations', '--force' => $this->option('force')]);
break;
default:
$this->call('vendor:publish', ['--tag' => 'rinvex-attributes-config', '--force' => $this->option('force')]);
$this->call('vendor:publish', ['--tag' => 'rinvex-attributes-migrations', '--force' => $this->option('force')]);
break;
}
$this->line('');
}
}
|
Remove Message typehint for testing convenience | <?php
namespace CodeZero\Mailer;
use Illuminate\Contracts\Mail\MailQueue;
class LaravelMailer implements Mailer
{
/**
* Laravel Mail Queue
*
* @var MailQueue
*/
private $mail;
/**
* Create a new instance of LaravelMailer.
*
* @param MailQueue $mail
*/
public function __construct(MailQueue $mail)
{
$this->mail = $mail;
}
/**
* Send an e-mail.
*
* @param string $toEmail
* @param string $toName
* @param string $subject
* @param string $view
* @param array $data
* @param callable $options
*
* @return void
*/
public function send($toEmail, $toName, $subject, $view, array $data = array(), $options = null)
{
$this->mail->queue($view, $data, function ($message) use ($toEmail, $toName, $subject, $options) {
$message->to($toEmail, $toName)
->subject($subject);
// Allow the caller to run additional functions
// on the $msg SwiftMailer object (cc, bcc, attach, ...)
if ($options && is_callable($options)) {
call_user_func($options, $message);
}
});
}
}
| <?php
namespace CodeZero\Mailer;
use Illuminate\Contracts\Mail\MailQueue;
use Illuminate\Mail\Message;
class LaravelMailer implements Mailer
{
/**
* Laravel Mail Queue
*
* @var MailQueue
*/
private $mail;
/**
* Create a new instance of LaravelMailer.
*
* @param MailQueue $mail
*/
public function __construct(MailQueue $mail)
{
$this->mail = $mail;
}
/**
* Send an e-mail.
*
* @param string $toEmail
* @param string $toName
* @param string $subject
* @param string $view
* @param array $data
* @param callable $options
*
* @return void
*/
public function send($toEmail, $toName, $subject, $view, array $data = array(), $options = null)
{
$this->mail->queue($view, $data, function (Message $message) use ($toEmail, $toName, $subject, $options) {
$message->to($toEmail, $toName)
->subject($subject);
// Allow the caller to run additional functions
// on the $msg SwiftMailer object (cc, bcc, attach, ...)
if ($options && is_callable($options)) {
call_user_func($options, $message);
}
});
}
}
|
Change turn rest api endpoint. | var Https = require('https');
var Common = require('./common');
exports.main = {
handler: function (request, reply) {
var params = Common.getRoomParameters(request, null, null, null);
reply.view('index_template', params);
}
};
exports.turn = {
handler: function (request, reply) {
var getOptions = {
host: 'instant.io',
port: 443,
path: '/__rtcConfig__',
method: 'GET'
};
Https.get(getOptions, function (result) {
console.log(result.statusCode == 200);
var body = '';
result.on('data', function (data) {
body += data;
});
result.on('end', function () {
reply(body);
});
}).on('error', function (e) {
reply({
"username":"webrtc",
"password":"webrtc",
"uris":[
"stun:stun.l.google.com:19302",
"stun:stun1.l.google.com:19302",
"stun:stun2.l.google.com:19302",
"stun:stun3.l.google.com:19302",
"stun:stun4.l.google.com:19302",
"stun:stun.services.mozilla.com",
"turn:turn.anyfirewall.com:443?transport=tcp"
]
});
});
}
};
| var Https = require('https');
var Common = require('./common');
exports.main = {
handler: function (request, reply) {
var params = Common.getRoomParameters(request, null, null, null);
reply.view('index_template', params);
}
};
exports.turn = {
handler: function (request, reply) {
var getOptions = {
host: 'instant.io',
port: 443,
path: '/rtcConfig',
method: 'GET'
};
Https.get(getOptions, function (result) {
console.log(result.statusCode == 200);
var body = '';
result.on('data', function (data) {
body += data;
});
result.on('end', function () {
reply(body);
});
}).on('error', function (e) {
reply({
"username":"webrtc",
"password":"webrtc",
"uris":[
"stun:stun.l.google.com:19302",
"stun:stun1.l.google.com:19302",
"stun:stun2.l.google.com:19302",
"stun:stun3.l.google.com:19302",
"stun:stun4.l.google.com:19302",
"stun:stun.services.mozilla.com",
"turn:turn.anyfirewall.com:443?transport=tcp"
]
});
});
}
};
|
Make it more easy to compare locale | <?php
namespace Common;
use InvalidArgumentException;
use Serializable;
abstract class Locale implements Serializable
{
/**
* @var string
*/
protected $locale;
/**
* @param string $locale
*/
protected function __construct($locale)
{
$this->setLocale($locale);
}
/**
* @param $locale
*
* @return self
*/
public static function fromString($locale)
{
return new static($locale);
}
/**
* @return array
*/
abstract protected function getPossibleLanguages();
/**
* @param string $locale
*
* @throws InvalidArgumentException
*
* @return self
*/
protected function setLocale($locale)
{
if (!array_key_exists($locale, $this->getPossibleLanguages())) {
throw new InvalidArgumentException('Invalid language');
}
$this->locale = $locale;
return $this;
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->locale;
}
/**
* @return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* @return string
*/
public function serialize()
{
return $this->locale;
}
/**
* @param string $locale
*
* @return Locale
*/
public function unserialize($locale)
{
$this->locale = $locale;
}
public function equals(Locale $locale)
{
return $this->locale === $locale->locale;
}
}
| <?php
namespace Common;
use InvalidArgumentException;
use Serializable;
abstract class Locale implements Serializable
{
/**
* @var string
*/
protected $locale;
/**
* @param string $locale
*/
protected function __construct($locale)
{
$this->setLocale($locale);
}
/**
* @param $locale
*
* @return self
*/
public static function fromString($locale)
{
return new static($locale);
}
/**
* @return array
*/
abstract protected function getPossibleLanguages();
/**
* @param string $locale
*
* @throws InvalidArgumentException
*
* @return self
*/
protected function setLocale($locale)
{
if (!array_key_exists($locale, $this->getPossibleLanguages())) {
throw new InvalidArgumentException('Invalid language');
}
$this->locale = $locale;
return $this;
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->locale;
}
/**
* @return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* @return string
*/
public function serialize()
{
return $this->locale;
}
/**
* @param string $locale
*
* @return Locale
*/
public function unserialize($locale)
{
$this->locale = $locale;
}
}
|
Drop unnecessary reference to popped elements to allow finalization through GC (XSTR-264).
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@649 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
return value;
}
public void popSilently() {
stack[--pointer] = null;
}
public Object pop() {
final Object result = stack[--pointer];
stack[pointer] = null;
return result;
}
public Object peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public boolean hasStuff() {
return pointer > 0;
}
public Object get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Object[] newStack = new Object[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
public String toString() {
StringBuffer result = new StringBuffer("[");
for (int i = 0; i < pointer; i++) {
if (i > 0) {
result.append(", ");
}
result.append(stack[i]);
}
result.append(']');
return result.toString();
}
}
| package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
return value;
}
public void popSilently() {
pointer--;
}
public Object pop() {
return stack[--pointer];
}
public Object peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public boolean hasStuff() {
return pointer > 0;
}
public Object get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Object[] newStack = new Object[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
public String toString() {
StringBuffer result = new StringBuffer("[");
for (int i = 0; i < pointer; i++) {
if (i > 0) {
result.append(", ");
}
result.append(stack[i]);
}
result.append(']');
return result.toString();
}
}
|
Add a missing newline character | <?php
namespace Kevinrob\GuzzleCache;
class KeyValueHttpHeader
{
const REGEX_SPLIT = '/^([^=]*)=(.*)$/';
/**
* @var string[]
*/
protected $values = [];
/**
* @param array $values
*/
public function __construct(array $values)
{
foreach ($values as $value) {
$matches = [];
if (preg_match(self::REGEX_SPLIT, $value, $matches)) {
$this->values[trim($matches[1])] = trim($matches[2]);
} else {
$this->values[trim($value)] = true;
}
}
}
/**
* @param string $key
* @return bool
*/
public function has($key)
{
// For performance, we can use "isset()",
// but it will not match if value == 0
return isset($this->values[$key]) || array_key_exists($key, $this->values);
}
/**
* @param string $key
* @return string
*/
public function get($key)
{
if ($this->has($key)) {
return $this->values[$key];
}
return "";
}
}
| <?php
namespace Kevinrob\GuzzleCache;
class KeyValueHttpHeader
{
const REGEX_SPLIT = '/^([^=]*)=(.*)$/';
/**
* @var string[]
*/
protected $values = [];
/**
* @param array $values
*/
public function __construct(array $values)
{
foreach ($values as $value) {
$matches = [];
if (preg_match(self::REGEX_SPLIT, $value, $matches)) {
$this->values[trim($matches[1])] = trim($matches[2]);
} else {
$this->values[trim($value)] = true;
}
}
}
/**
* @param string $key
* @return bool
*/
public function has($key)
{
// For performance, we can use "isset()",
// but it will not match if value == 0
return isset($this->values[$key]) || array_key_exists($key, $this->values);
}
/**
* @param string $key
* @return string
*/
public function get($key)
{
if ($this->has($key)) {
return $this->values[$key];
}
return "";
}
} |
Remove defunct exchanges from example config | <?php
namespace CryptoMarketTest;
class ConfigDataExample
{
const MONGODB_URI = 'mongodb://localhost';
const MONGODB_DBNAME = 'coindata';
const ACCOUNTS_CONFIG = array(
// 'Btce' => array(
// 'key' => '',
// 'secret' => ''
// ),
'Bitfinex'=> array(
'key' => '',
'secret' => ''
),
'Bitstamp'=> array(
'key' => '',
'secret' => '',
'custid' => ''
),
// 'BitVC'=> array(
// 'key' => '',
// 'secret' => '',
// ),
// 'JPMChase' => array(
// 'name' => 'imapmailbox',
// 'username' => 'username',
// 'password' => 'password'
// ),
'Gdax'=> array(
'key' => '',
'secret' => '',
'passphrase' =>''
),
'Gemini'=> array(
'key' => '',
'secret' => ''
),
'Kraken'=> array(
'key' => '',
'secret' => ''
),
'Poloniex'=> array(
'key' => '',
'secret' => ''
),
// 'Yunbi'=> array(
// 'key' => '',
// 'secret' => '',
// ),
);
}
| <?php
namespace CryptoMarketTest;
class ConfigDataExample
{
const MONGODB_URI = 'mongodb://localhost';
const MONGODB_DBNAME = 'coindata';
const ACCOUNTS_CONFIG = array(
'Btce' => array(
'key' => '',
'secret' => ''
),
'Bitfinex'=> array(
'key' => '',
'secret' => ''
),
'Bitstamp'=> array(
'key' => '',
'secret' => '',
'custid' => ''
),
'BitVC'=> array(
'key' => '',
'secret' => '',
),
// 'JPMChase' => array(
// 'name' => 'imapmailbox',
// 'username' => 'username',
// 'password' => 'password'
// ),
'Gdax'=> array(
'key' => '',
'secret' => '',
'passphrase' =>''
),
'Gemini'=> array(
'key' => '',
'secret' => ''
),
'Kraken'=> array(
'key' => '',
'secret' => ''
),
'Poloniex'=> array(
'key' => '',
'secret' => ''
),
'Yunbi'=> array(
'key' => '',
'secret' => '',
),
);
}
|
Fix typo resulting in NameError | from functools import wraps
import subprocess
_SELECTIONS = {
'+': 'clipboard',
'*': 'primary',
}
def _store_selection(data, selection):
with subprocess.Popen(['xclip',
'-selection', selection],
stdin=subprocess.PIPE) as xclip:
xclip.stdin.write(str(data).encode())
def _load_selection(selection):
with subprocess.Popen(['xclip',
'-selection', selection,
'-o'], stdout=subprocess.PIPE) as xclip:
return xclip.stdout.read().decode()
class RPNError(Exception):
pass
def wrap_user_errors(fmt):
'''
Ugly hack decorator that converts exceptions to warnings.
Passes through RPNErrors.
'''
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except RPNError:
raise
except Exception as e:
raise RPNError(fmt.format(*args, **kwargs), e)
return wrapper
return decorator
| from functools import wraps
import subprocess
_SELECTIONS = {
'+': 'clipboard',
'*': 'primary',
}
def _store_selection(data, selection):
with subprocess.Popen(['xclip',
'-selection', selection],
stdin=subprocess.PIPE) as xclip:
xclip.stdin.write(str(data).encode())
def _load_selection(selection):
with subprocess.Popen(['xclip',
'-selection', selection,
'-o'], stdout=PIPE) as xclip:
return xclip.stdout.read().decode()
class RPNError(Exception):
pass
def wrap_user_errors(fmt):
'''
Ugly hack decorator that converts exceptions to warnings.
Passes through RPNErrors.
'''
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except RPNError:
raise
except Exception as e:
raise RPNError(fmt.format(*args, **kwargs), e)
return wrapper
return decorator
|
Update contact activity query to remove Incomplete registrations | const contactActivityQuery = (
from,
size,
email,
contactId,
objectTypes,
sortOrder
) => {
return {
from,
size,
query: {
bool: {
must: [
{
bool: {
should: [
{
bool: {
must: [
{
terms: {
'object.type': objectTypes,
},
},
{
terms: {
'object.attributedTo.id': [
`dit:DataHubContact:${contactId}`,
],
},
},
],
},
},
{
bool: {
must: [
{
terms: {
'object.type': [
'dit:aventri:Attendee',
'dit:maxemail:Email:Sent',
],
},
},
{
term: {
'object.dit:emailAddress': {
value: email,
case_insensitive: true,
},
},
},
{
terms: {
'object.dit:registrationStatus': [
'Attended',
'Confirmed',
'Cancelled',
'Registered',
],
},
},
],
},
},
],
},
},
],
},
},
sort: [
{
published: {
order: sortOrder,
unmapped_type: 'long',
},
},
],
}
}
module.exports = {
contactActivityQuery,
}
| const contactActivityQuery = (
from,
size,
email,
contactId,
objectTypes,
sortOrder
) => {
return {
from,
size,
query: {
bool: {
must: [
{
bool: {
should: [
{
bool: {
must: [
{
terms: {
'object.type': objectTypes,
},
},
{
terms: {
'object.attributedTo.id': [
`dit:DataHubContact:${contactId}`,
],
},
},
],
},
},
{
bool: {
must: [
{
terms: {
'object.type': [
'dit:aventri:Attendee',
'dit:maxemail:Email:Sent',
],
},
},
{
term: {
'object.dit:emailAddress': {
value: email,
case_insensitive: true,
},
},
},
],
},
},
],
},
},
],
},
},
sort: [
{
published: {
order: sortOrder,
unmapped_type: 'long',
},
},
],
}
}
module.exports = {
contactActivityQuery,
}
|
Fix the test 1 at case 5 | ;((rc) => {
'use strict';
var tagContent = 'router2-content';
var tagView = 'router2-view';
var div = document.createElement('div');
div.innerHTML = `
<${tagContent} id="case5-1" hash="case5-1">
Case 5-1
<div>
<div>
<div>
<${tagContent} id="case5-11" hash="case5-11">
Case 5-11
</${tagContent}>
</div>
</div>
</div>
</${tagContent}>
`;
var async1 = async_test('Case 5: hash changed to content[hash="case5-1/case5-11"]');
async1.next = async1.step_func(_ => {
var check_hash = async1.step_func((e) => {
window.removeEventListener('hashchange', check_hash);
var content1 = document.querySelector('#case5-1');
var content2 = document.querySelector('#case5-11');
assert_false(content1.hidden);
assert_false(content2.hidden);
document.body.removeChild(div);
async1.done();
rc.next();
});
window.addEventListener('hashchange', check_hash);
window.location.hash = "case5-1/case5-11";
});
rc.push(_ => {
async1.step(_ => {
document.body.appendChild(div);
async1.next();
});
})
})(window.routeCases);
| ;((rc) => {
'use strict';
var tagContent = 'router2-content';
var tagView = 'router2-view';
var div = document.createElement('div');
div.innerHTML = `
<${tagContent} id="case5-1" hash="case5-1">
Case 5-1
<div>
<div>
<div>
<${tagContent} id="case5-11" hash="case5-11">
Case 5-11
</${tagContent}>
</div>
</div>
</div>
</${tagContent}>
`;
var async1 = async_test('Case 5: hash changed to content[hash="case5-1/case5-11"]');
async1.next = async1.step_func(_ => {
var check_hash = async1.step_func((e) => {
window.removeEventListener('hashchange', check_hash);
var content1 = document.querySelector('#case5-1');
var content2 = document.querySelector('#case5-11');
//assert_false(content1.hidden);
//assert_false(content2.hidden);
//document.body.removeChild(div);
async1.done();
rc.next();
});
window.addEventListener('hashchange', check_hash);
window.location.hash = "case5-1/case5-11";
});
rc.push(_ => {
async1.step(_ => {
document.body.appendChild(div);
async1.next();
});
})
})(window.routeCases);
|
Remove extra label for user | import logging, urllib2
from lighter.util import merge, build_request
class HipChat(object):
def __init__(self, url, token):
self._url = url or 'https://api.hipchat.com'
self._token = token
self_rooms = []
self._sender = 'Lighter'
self._message_attribs = {
'color': 'green',
'notify': True,
'message_format': 'html'
}
def rooms(self, ids):
self._rooms = ids
return self
def notify(self, message):
for room in self._rooms:
self._call('/v2/room/%s/notification' % room, merge({'message': message}, self._message_attribs))
def _call(self, endpoint, data):
if self._url is None or self._token is None:
logging.debug('HipChat is not enabled')
return
try:
url = self._url.rstrip('/') + '/' + endpoint + '?auth_token=' + self._token
logging.debug('Calling HipChat endpoint %s', endpoint)
response = urllib2.urlopen(build_request(url, data, {}, 'POST'))
content = response.read()
except urllib2.URLError, e:
logging.warn(str(e))
return {}
| import logging, urllib2
from lighter.util import merge, build_request
class HipChat(object):
def __init__(self, url, token):
self._url = url or 'https://api.hipchat.com'
self._token = token
self_rooms = []
self._sender = 'Lighter'
self._message_attribs = {
'from': 'Lighter',
'color': 'green',
'notify': True,
'message_format': 'html'
}
def rooms(self, ids):
self._rooms = ids
return self
def notify(self, message):
for room in self._rooms:
self._call('/v2/room/%s/notification' % room, merge({'message': message}, self._message_attribs))
def _call(self, endpoint, data):
if self._url is None or self._token is None:
logging.debug('HipChat is not enabled')
return
try:
url = self._url.rstrip('/') + '/' + endpoint + '?auth_token=' + self._token
logging.debug('Calling HipChat endpoint %s', endpoint)
response = urllib2.urlopen(build_request(url, data, {}, 'POST'))
content = response.read()
except urllib2.URLError, e:
logging.warn(str(e))
return {}
|
Use raw string for Windows paths
This avoids:
DeprecationWarning: invalid escape sequence \P
_search_path.append('C:\Program Files') | import os
import platform
from .generic import MeshScript
from ..constants import log
from distutils.spawn import find_executable
_search_path = os.environ['PATH']
if platform.system() == 'Windows':
# split existing path by delimiter
_search_path = [i for i in _search_path.split(';') if len(i) > 0]
_search_path.append(r'C:\Program Files')
_search_path.append(r'C:\Program Files (x86)')
_search_path = ';'.join(_search_path)
log.debug('searching for vhacd in: %s', _search_path)
_vhacd_executable = None
for _name in ['vhacd', 'testVHACD']:
_vhacd_executable = find_executable(_name, path=_search_path)
if _vhacd_executable is not None:
break
exists = _vhacd_executable is not None
def convex_decomposition(mesh, **kwargs):
if not exists:
raise ValueError('No vhacd available!')
argstring = ' --input $mesh_0 --output $mesh_post --log $script'
# pass through extra arguments from the input dictionary
for key, value in kwargs.items():
argstring += ' --{} {}'.format(str(key),
str(value))
with MeshScript(meshes=[mesh],
script='',
tmpfile_ext='obj') as vhacd:
result = vhacd.run(_vhacd_executable + argstring)
return result
| import os
import platform
from .generic import MeshScript
from ..constants import log
from distutils.spawn import find_executable
_search_path = os.environ['PATH']
if platform.system() == 'Windows':
# split existing path by delimiter
_search_path = [i for i in _search_path.split(';') if len(i) > 0]
_search_path.append('C:\Program Files')
_search_path.append('C:\Program Files (x86)')
_search_path = ';'.join(_search_path)
log.debug('searching for vhacd in: %s', _search_path)
_vhacd_executable = None
for _name in ['vhacd', 'testVHACD']:
_vhacd_executable = find_executable(_name, path=_search_path)
if _vhacd_executable is not None:
break
exists = _vhacd_executable is not None
def convex_decomposition(mesh, **kwargs):
if not exists:
raise ValueError('No vhacd available!')
argstring = ' --input $mesh_0 --output $mesh_post --log $script'
# pass through extra arguments from the input dictionary
for key, value in kwargs.items():
argstring += ' --{} {}'.format(str(key),
str(value))
with MeshScript(meshes=[mesh],
script='',
tmpfile_ext='obj') as vhacd:
result = vhacd.run(_vhacd_executable + argstring)
return result
|
BAP-10985: Update the rules displaying autocomplete result for business unit owner field | <?php
namespace Oro\Bundle\OrganizationBundle\Form\Transformer;
use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;
class BusinessUnitTreeTransformer implements DataTransformerInterface
{
/** @var BusinessUnitManager */
protected $manager;
/** @var BusinessUnit */
protected $entity;
public function __construct($manager)
{
$this->manager = $manager;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
if (null === $value) {
return 0;
} elseif (is_array($value)) {
foreach ($value as &$val) {
if ($val === '') {
$val = 0;
}
}
return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
}
return $this->manager->getBusinessUnitRepo()->find($value);
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
if (null === $value) {
return 0;
}
if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
$result = [];
foreach ($value as $object) {
$result[] = $object->getId();
}
} elseif (is_object($value)) {
$result = $value->getId();
} else {
$result = $value;
}
return $result;
}
}
| <?php
namespace Oro\Bundle\OrganizationBundle\Form\Transformer;
use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;
class BusinessUnitTreeTransformer implements DataTransformerInterface
{
/** @var BusinessUnitManager */
protected $manager;
/** @var BusinessUnit */
protected $entity;
public function __construct($manager)
{
$this->manager = $manager;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
if (null == $value) {
return 0;
} elseif (is_array($value)) {
foreach ($value as &$val) {
if ($val === '') {
$val = 0;
}
}
return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
}
return $this->manager->getBusinessUnitRepo()->find($value);
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
if (null == $value) {
return 0;
}
if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
$result = [];
foreach ($value as $object) {
$result[] = $object->getId();
}
} elseif (is_object($value)) {
$result = $value->getId();
} else {
$result = $value;
}
return $result;
}
}
|
Fix new NASM number regexp | Prism.languages.nasm = {
'comment': /;.*$/m,
'string': /("|'|`)(\\?.)*?\1/gm,
'label': {
pattern: /^\s*[A-Za-z\._\?\$][\w\.\?\$@~#]*:/m,
alias: 'function'
},
'keyword': [
/\[?BITS (16|32|64)\]?/m,
/^\s*section\s*[a-zA-Z\.]+:?/im,
/(?:extern|global)[^;]*/im,
/(?:CPU|FLOAT|DEFAULT).*$/m
],
'register': {
pattern: /\b(?:st\d|[xyz]mm\d\d?|[cdt]r\d|r\d\d?[bwd]?|[er]?[abcd]x|[abcd][hl]|[er]?(bp|sp|si|di)|[cdefgs]s)\b/gi,
alias: 'variable'
},
'number': /(\b|-|(?=\$))(0[hx][\da-f]*\.?[\da-f]+(p[+-]?\d+)?|\d[\da-f]+[hx]|\$\d[\da-f]*|0[oq][0-7]+|[0-7]+[oq]|0[by][01]+|[01]+[by]|0[dt]\d+|\d*\.?\d+(\.?e[+-]?\d+)?[dt]?)\b/i,
'operator': /[\[\]\*+\-\/%<>=&|\$!]/gm
};
| Prism.languages.nasm = {
'comment': /;.*$/m,
'string': /("|'|`)(\\?.)*?\1/gm,
'label': {
pattern: /^\s*[A-Za-z\._\?\$][\w\.\?\$@~#]*:/m,
alias: 'function'
},
'keyword': [
/\[?BITS (16|32|64)\]?/m,
/^\s*section\s*[a-zA-Z\.]+:?/im,
/(?:extern|global)[^;]*/im,
/(?:CPU|FLOAT|DEFAULT).*$/m
],
'register': {
pattern: /\b(?:st\d|[xyz]mm\d\d?|[cdt]r\d|r\d\d?[bwd]?|[er]?[abcd]x|[abcd][hl]|[er]?(bp|sp|si|di)|[cdefgs]s)\b/gi,
alias: 'variable'
},
'number': /(\b|-|(?=\$))(0[hx][\da-f]*\.?[\da-f]+(p[+-]?\d+)?|\d[\da-f]+[hx]|\\$\d[\da-f]*|0[oq][0-7]+|[0-7]+[oq]|0[by][01]+|[01]+[by]|0[dt]\d+|\d*\.?\d+(\.?e[+-]?\d+)?[dt]?)\b/i,
'operator': /[\[\]\*+\-\/%<>=&|\$!]/gm
};
|
Fix title+artists check in event-add-form | <?php
class Denkmal_FormAction_EventAdd_Create extends CM_FormAction_Abstract {
protected function _getRequiredFields() {
return array('venue', 'date', 'fromTime');
}
protected function _checkData(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
$event = Denkmal_Form_EventAdd::getEventFromData($params);
$now = new DateTime();
if ($event->getFrom() < $now && !$event->getUntil()) {
$response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
}
if ($event->getUntil() < $now && $event->getUntil()) {
$response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
}
if (!$params->has('title') && !$params->has('artists')) {
$response->addError($response->getRender()->getTranslation('Bitte Titel oder KรผnstlerInnen angeben'), 'title');
}
}
protected function _process(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
$venue = Denkmal_Form_EventAdd::getVenueFromData($params);
$venue->commit();
$event = Denkmal_Form_EventAdd::getEventFromData($params);
$event->setVenue($venue);
$event->commit();
}
}
| <?php
class Denkmal_FormAction_EventAdd_Create extends CM_FormAction_Abstract {
protected function _getRequiredFields() {
return array('venue', 'date', 'fromTime');
}
protected function _checkData(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
$event = Denkmal_Form_EventAdd::getEventFromData($params);
$now = new DateTime();
if ($event->getFrom() < $now && !$event->getUntil()) {
$response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
}
if ($event->getUntil() < $now && $event->getUntil()) {
$response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
}
if (!$params->has('title') && !$params->has('description')) {
$response->addError($response->getRender()->getTranslation('Bitte Titel oder KรผnstlerInnen angeben'), 'title');
}
}
protected function _process(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
$venue = Denkmal_Form_EventAdd::getVenueFromData($params);
$venue->commit();
$event = Denkmal_Form_EventAdd::getEventFromData($params);
$event->setVenue($venue);
$event->commit();
}
}
|
Use values_list instead of iterating over | from corehq.apps.products.models import SQLProduct
from custom.ewsghana.handlers import HELP_TEXT
from custom.ilsgateway.tanzania.handlers.keyword import KeywordHandler
class HelpHandler(KeywordHandler):
def help(self):
self.respond(HELP_TEXT)
def handle(self):
topic = self.args[0].lower()
if topic == 'stock':
self.respond("Please send your receipts in the format "
"' <Commodity code> <stock on hand > . <quantity received>'")
elif topic == 'stop':
self.respond("Text 'stop' to stop receiving text message reminders.")
elif topic == 'start':
self.respond("Text 'start' to get text message reminders every week to submit your stock reports.")
elif 'code' in topic:
codes = SQLProduct.by_domain(self.domain).order_by('code').values_list('code', flat=True)
self.respond("Available commodity codes: %(codes)s", codes=", ".join(codes))
else:
try:
sql_product = SQLProduct.objects.get(domain=self.domain, code=topic)
msg = "%s is the commodity code for %s" % (topic, sql_product.name)
if sql_product.units:
msg += " (%s)" % sql_product.units
if sql_product.description and sql_product.description not in sql_product.name:
msg += " %s" % sql_product.description
self.respond(msg)
except SQLProduct.DoesNotExist:
self.help()
| from corehq.apps.products.models import SQLProduct
from custom.ewsghana.handlers import HELP_TEXT
from custom.ilsgateway.tanzania.handlers.keyword import KeywordHandler
class HelpHandler(KeywordHandler):
def help(self):
self.respond(HELP_TEXT)
def handle(self):
topic = self.args[0].lower()
if topic == 'stock':
self.respond("Please send your receipts in the format "
"' <Commodity code> <stock on hand > . <quantity received>'")
elif topic == 'stop':
self.respond("Text 'stop' to stop receiving text message reminders.")
elif topic == 'start':
self.respond("Text 'start' to get text message reminders every week to submit your stock reports.")
elif 'code' in topic:
codes = [c.code for c in SQLProduct.by_domain(self.domain).order_by('code')]
self.respond("Available commodity codes: %(codes)s", codes=", ".join(codes))
else:
try:
sql_product = SQLProduct.objects.get(domain=self.domain, code=topic)
msg = "%s is the commodity code for %s" % (topic, sql_product.name)
if sql_product.units:
msg += " (%s)" % sql_product.units
if sql_product.description and sql_product.description not in sql_product.name:
msg += " %s" % sql_product.description
self.respond(msg)
except SQLProduct.DoesNotExist:
self.help()
|
Return null instead of setting content to null | import React from 'react'
import { Box, Grid, Typography, Card, CardContent } from '@material-ui/core'
import { Edit, Delete } from '@material-ui/icons'
export default function TravelObject(props) {
let content = null;
switch (props.type) {
case 'event':
content = <Typography variant="h4" gutterBottom>Event!</Typography>
break;
case 'flight':
content = <Typography variant="h4" gutterBottom>Flight!</Typography>
break;
case 'hotel':
content = <Typography variant="h4" gutterBottom>Hotel!</Typography>
break;
default:
return null;
}
return (
<Card>
<CardContent>
<Grid container direction="row" justify="flex-end" alignItems="center">
<Box mr={10} width="100%" height="100%">
{content}
</Box>
<Grid item>
<Grid container direction="column">
<Edit
onClick={() => console.log("editing")}
/>
<Delete
onClick={() => console.log("deleting")}
/>
</Grid>
</Grid>
</Grid>
</CardContent>
</Card>
)
} | import React from 'react'
import { Box, Grid, Typography, Card, CardContent } from '@material-ui/core'
import { Edit, Delete } from '@material-ui/icons'
export default function TravelObject(props) {
let content = null;
switch (props.type) {
case 'event':
content = <Typography variant="h4" gutterBottom>Event!</Typography>
break;
case 'flight':
content = <Typography variant="h4" gutterBottom>Flight!</Typography>
break;
case 'hotel':
content = <Typography variant="h4" gutterBottom>Hotel!</Typography>
break;
default:
console.log("Invalid type");
break;
}
return (
<Card>
<CardContent>
<Grid container direction="row" justify="flex-end" alignItems="center">
<Box mr={10} width="100%" height="100%">
{content}
</Box>
<Grid item>
<Grid container direction="column">
<Edit
onClick={() => console.log("editing")}
/>
<Delete
onClick={() => console.log("deleting")}
/>
</Grid>
</Grid>
</Grid>
</CardContent>
</Card>
)
} |
Revert version update made for our mirror. | import os
from setuptools import setup, find_packages
version = '1.5.0'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas-client',
version=version,
description="Django Cas Client",
long_description=read('README.md'),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Framework :: Django :: 1.5",
"Framework :: Django :: 1.6",
"Framework :: Django :: 1.7",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='django cas',
author='Derek Stegelman, Garrett Pennington',
author_email='[email protected], [email protected]',
url='http://github.com/kstateome/django-cas/',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=True,
)
| import os
from setuptools import setup, find_packages
version = '1.5.0_patch1'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas-client',
version=version,
description="Django Cas Client",
long_description=read('README.md'),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Framework :: Django :: 1.5",
"Framework :: Django :: 1.6",
"Framework :: Django :: 1.7",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='django cas',
author='Derek Stegelman, Garrett Pennington',
author_email='[email protected], [email protected]',
url='http://github.com/kstateome/django-cas/',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=True,
)
|
Work around phpcs fail while unpacking $msg for debug purposes | <?php
/**
* Consumes RabbitMQ messages and dumps them.
*/
namespace Graviton\MessageBundle\Service;
use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;
/**
* Consumes RabbitMQ messages and dumps them.
*
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
class DumpConsumer implements ConsumerInterface
{
/**
* Callback executed when a message is received. Dumps the message body, delivery_info and properties.
*
* @param AMQPMessage $msg The received message.
*
* @return void
*/
public function execute(AMQPMessage $msg)
{
echo 'Message received at ' . date('c') . ': ' . $msg->body . "\n";
echo "\t" . 'Delivery Info: ' . "\n";
foreach ($msg->{'delivery_info'} as $key => $value) {
if (is_scalar($value)) {
echo "\t\t" . $key . ': ' . $value . "\n";
}
}
echo "\t" . 'Properties: ' . "\n";
foreach ($msg->get_properties() as $property => $value) {
if (is_scalar($value)) {
echo "\t\t" . $property . ': ' . $value . "\n";
}
}
}
}
| <?php
/**
* Consumes RabbitMQ messages and dumps them.
*/
namespace Graviton\MessageBundle\Service;
use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;
/**
* Consumes RabbitMQ messages and dumps them.
*
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
class DumpConsumer implements ConsumerInterface
{
/**
* Callback executed when a message is received. Dumps the message body, delivery_info and properties.
*
* @param AMQPMessage $msg The received message.
*
* @return void
*/
public function execute(AMQPMessage $msg)
{
echo 'Message received at ' . date('c') . ': ' . $msg->body . "\n";
echo "\t" . 'Delivery Info: ' . "\n";
foreach ($msg->delivery_info as $key => $value) {
if (is_scalar($value)) {
echo "\t\t" . $key . ': ' . $value . "\n";
}
}
echo "\t" . 'Properties: ' . "\n";
foreach ($msg->get_properties() as $property => $value) {
if (is_scalar($value)) {
echo "\t\t" . $property . ': ' . $value . "\n";
}
}
}
}
|
Add find by class name support for IE8
If you'd like to support IE8, with the class selector, this should do it. | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else {
root.ess = factory();
}
}(this, function () {
function s(selector, context) {
var elements = [];
if (selector.indexOf(' ') !== -1) {
var parts = selector.split(' '),
thisSelector = parts.shift(),
nextSelector = parts.join(' '),
results = s(thisSelector, context);
if (results) {
if (typeof results.length !== 'undefined') {
for (var i=0, l=results.length; i < l; i++) {
elements = elements.concat(s(nextSelector, results[i]));
}
} else {
elements = elements.concat(s(nextSelector, results));
}
}
} else {
context = context || document;
var type = selector.substring(0, 1);
if ('#' === type) {
return context.getElementById(selector.substring(1));
} else {
var list;
if ('.' === type) {
if (document.getElementsByClassName) {
list = context.getElementsByClassName(selector.substring(1));
} else {
list = context.querySelectorAll(selector);
}
} else {
list = context.getElementsByTagName(selector);
}
var listLength = list.length;
for (var i = 0; i < listLength; i++) {
elements.push(list[i]);
}
}
}
return elements;
}
return s;
}));
| (function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else {
root.ess = factory();
}
}(this, function () {
function s(selector, context) {
var elements = [];
if (selector.indexOf(' ') !== -1) {
var parts = selector.split(' '),
thisSelector = parts.shift(),
nextSelector = parts.join(' '),
results = s(thisSelector, context);
if (results) {
if (typeof results.length !== 'undefined') {
for (var i=0, l=results.length; i < l; i++) {
elements = elements.concat(s(nextSelector, results[i]));
}
} else {
elements = elements.concat(s(nextSelector, results));
}
}
} else {
context = context || document;
var type = selector.substring(0, 1);
if ('#' === type) {
return context.getElementById(selector.substring(1));
} else {
var list;
if ('.' === type) {
list = context.getElementsByClassName(selector.substring(1));
} else {
list = context.getElementsByTagName(selector);
}
var listLength = list.length;
for (var i = 0; i < listLength; i++) {
elements.push(list[i]);
}
}
}
return elements;
}
return s;
}));
|
Test for sleep(dt) without extra arg. | """Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
| """Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
Set max condition depth to 3 due to limited width | module.exports = {
DEBUG: <%= DEBUG %>,
INPUT_DELAY_BEFORE_SAVE: 500, // in milliseconds
SITE_TITLE: 'Sana Protocol Builder',
APP_NAMESPACE: 'spb',
API_BASE: '<%= API_BASE %>',
LOCALES_SUPPORTED: [
{
code: 'en',
name: 'English',
}, {
code: 'fr',
name: 'Franรงais',
}
],
DEFAULT_LOCALE: 'en',
NON_AUTH_PAGES: [
'login',
'signup',
'terms',
'privacy',
],
ELEMENT_TYPES: [
'DATE',
'ENTRY',
'SELECT',
'MULTI_SELECT',
'RADIO',
'PICTURE',
'PLUGIN',
'ENTRY_PLUGIN',
],
CHOICE_ELEMENT_TYPES: [
'SELECT',
'MULTI_SELECT',
'RADIO',
],
PLUGIN_ELEMENT_TYPES: [
'PLUGIN',
'ENTRY_PLUGIN',
],
MAX_CONDITIONAL_DEPTH: 3, // i.e. max number of logical connective nesting
};
| module.exports = {
DEBUG: <%= DEBUG %>,
INPUT_DELAY_BEFORE_SAVE: 500, // in milliseconds
SITE_TITLE: 'Sana Protocol Builder',
APP_NAMESPACE: 'spb',
API_BASE: '<%= API_BASE %>',
LOCALES_SUPPORTED: [
{
code: 'en',
name: 'English',
}, {
code: 'fr',
name: 'Franรงais',
}
],
DEFAULT_LOCALE: 'en',
NON_AUTH_PAGES: [
'login',
'signup',
'terms',
'privacy',
],
ELEMENT_TYPES: [
'DATE',
'ENTRY',
'SELECT',
'MULTI_SELECT',
'RADIO',
'PICTURE',
'PLUGIN',
'ENTRY_PLUGIN',
],
CHOICE_ELEMENT_TYPES: [
'SELECT',
'MULTI_SELECT',
'RADIO',
],
PLUGIN_ELEMENT_TYPES: [
'PLUGIN',
'ENTRY_PLUGIN',
],
};
|
Rename returned interface to control and init to inView | import Registry from './registry';
const inView = () => {
const getElements = (selector) =>
[].slice.call(document.querySelectorAll(selector));
const inViewport = (element, offset = 0) => {
let bounds = element.getBoundingClientRect();
return bounds.bottom > offset
&& bounds.right > offset
&& window.innerWidth - bounds.left > offset
&& window.innerHeight - bounds.top > offset;
};
const throttle = (fn, threshold, context) => {
let prev = 0;
return () => {
let now = new Date().getTime();
if (now - prev > threshold) {
fn.call(context);
prev = now;
}
};
};
let catalog = { history: [] };
let control = (selector) => {
let elements = getElements(selector);
if (catalog.history.indexOf(selector) > -1) {
catalog[selector].elements = elements;
} else {
catalog[selector] = new Registry(elements);
catalog.history.push(selector);
}
return catalog[selector];
};
control.is = inViewport;
return control;
};
export default inView();
| import Registry from './registry';
const initInView = () => {
const getElements = (selector) =>
[].slice.call(document.querySelectorAll(selector));
const inViewport = (element, offset = 0) => {
let bounds = element.getBoundingClientRect();
return bounds.bottom > offset
&& bounds.right > offset
&& window.innerWidth - bounds.left > offset
&& window.innerHeight - bounds.top > offset;
};
const throttle = (fn, threshold, context) => {
let prev = 0;
return () => {
let now = new Date().getTime();
if (now - prev > threshold) {
fn.call(context);
prev = now;
}
};
};
let catalog = { history: [] };
let inView = (selector) => {
let elements = getElements(selector);
if (catalog.history.indexOf(selector) > -1) {
catalog[selector].elements = elements;
} else {
catalog[selector] = new Registry(elements);
catalog.history.push(selector);
}
return catalog[selector];
};
inView.is = inViewport;
return inView;
};
export default initInView();
|
Refactor test case into two classes | import os
import unittest
import tempfile
# Local modules
import library.server as server
class ServerTestCase(unittest.TestCase):
@classmethod
def setUp(self):
self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
server.app.config['TESTING'] = True
self.app = server.app.test_client()
with server.app.app_context():
server.init_db()
@classmethod
def tearDown(self):
os.close(self.db_fd)
os.unlink(server.app.config['DATABASE'])
class RootTestCase(ServerTestCase):
def test_root(self):
rv = self.app.get('/')
self.assertEqual(rv.status_code, 200)
class BookTestCase(ServerTestCase):
def test_book_post(self):
rv = self.app.put('/books', data={'isbn': 1234})
self.assertEqual(rv.status_code, 200)
rv = self.app.get('/books')
self.assertEqual(rv.data, '1234')
rv = self.app.put('/books', data={'isbn': 5678})
self.assertEqual(rv.status_code, 200)
rv = self.app.get('/books')
self.assertEqual(rv.data, '5678 1234')
def test_book_get(self):
rv = self.app.get('/books')
self.assertEqual(rv.status_code, 200)
if __name__ == '__main__':
unittest.main()
| import os
import unittest
import tempfile
# Local modules
import library.server as server
class ServerTestCase(unittest.TestCase):
@classmethod
def setUp(self):
self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
server.app.config['TESTING'] = True
self.app = server.app.test_client()
with server.app.app_context():
server.init_db()
@classmethod
def tearDown(self):
os.close(self.db_fd)
os.unlink(server.app.config['DATABASE'])
def test_root(self):
rv = self.app.get('/')
self.assertEqual(rv.status_code, 200)
def test_book_post(self):
rv = self.app.put('/books', data={'isbn': 1234})
self.assertEqual(rv.status_code, 200)
rv = self.app.get('/books')
self.assertEqual(rv.data, '1234')
rv = self.app.put('/books', data={'isbn': 5678})
self.assertEqual(rv.status_code, 200)
rv = self.app.get('/books')
self.assertEqual(rv.data, '5678 1234')
def test_book_get(self):
rv = self.app.get('/books')
self.assertEqual(rv.status_code, 200)
if __name__ == '__main__':
unittest.main()
|
Update email address confirmation subject | <?php namespace Flarum\Core\Handlers\Events;
use Illuminate\Mail\Mailer;
use Flarum\Core\Events\UserWasRegistered;
use Flarum\Core\Events\EmailWasChanged;
use Config;
use Illuminate\Contracts\Events\Dispatcher;
class EmailConfirmationMailer
{
protected $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Register the listeners for the subscriber.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen('Flarum\Core\Events\UserWasRegistered', __CLASS__.'@whenUserWasRegistered');
$events->listen('Flarum\Core\Events\EmailWasChanged', __CLASS__.'@whenEmailWasChanged');
}
public function whenUserWasRegistered(UserWasRegistered $event)
{
$user = $event->user;
$forumTitle = Config::get('flarum::forum_title');
$data = [
'username' => $user->username,
'forumTitle' => $forumTitle,
'url' => route('flarum.forum.confirm', ['id' => $user->id, 'token' => $user->confirmation_token])
];
$this->mailer->send(['text' => 'flarum::emails.confirm'], $data, function ($message) use ($user) {
$message->to($user->email);
$message->subject('Confirm Your Email Address');
});
}
public function whenEmailWasChanged(EmailWasChanged $event)
{
}
}
| <?php namespace Flarum\Core\Handlers\Events;
use Illuminate\Mail\Mailer;
use Flarum\Core\Events\UserWasRegistered;
use Flarum\Core\Events\EmailWasChanged;
use Config;
use Illuminate\Contracts\Events\Dispatcher;
class EmailConfirmationMailer
{
protected $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Register the listeners for the subscriber.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen('Flarum\Core\Events\UserWasRegistered', __CLASS__.'@whenUserWasRegistered');
$events->listen('Flarum\Core\Events\EmailWasChanged', __CLASS__.'@whenEmailWasChanged');
}
public function whenUserWasRegistered(UserWasRegistered $event)
{
$user = $event->user;
$forumTitle = Config::get('flarum::forum_title');
$data = [
'username' => $user->username,
'forumTitle' => $forumTitle,
'url' => route('flarum.forum.confirm', ['id' => $user->id, 'token' => $user->confirmation_token])
];
$this->mailer->send(['text' => 'flarum::emails.confirm'], $data, function ($message) use ($user) {
$message->to($user->email);
$message->subject('Email Address Confirmation');
});
}
public function whenEmailWasChanged(EmailWasChanged $event)
{
}
}
|
Disable notification in browser-sync as it caused issues with layout | var gulp = require('gulp');
var elm = require('gulp-elm');
var plumber = require('gulp-plumber');
var del = require('del');
var browserSync = require('browser-sync');
// builds elm files and static resources (i.e. html and css) from src to dist folder
var paths = {
dest: 'dist',
elm: 'src/*.elm',
staticAssets: 'src/*.{html,css}'
};
gulp.task('clean', function(cb) {
del([paths.dest], cb);
});
gulp.task('elm-init', elm.init);
gulp.task('elm', ['elm-init'], function() {
return gulp.src(paths.elm)
.pipe(plumber())
.pipe(elm())
.pipe(gulp.dest(paths.dest))
.pipe(browserSync.stream());
});
gulp.task('staticAssets', function() {
return gulp.src(paths.staticAssets)
.pipe(plumber())
.pipe(gulp.dest(paths.dest))
.pipe(browserSync.stream());
});
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "dist/"
},
notify: false
});
});
gulp.task('watch', function() {
gulp.watch(paths.elm, ['elm']);
gulp.watch(paths.staticAssets, ['staticAssets']);
});
gulp.task('build', ['elm', 'staticAssets']);
gulp.task('dev', ['build', 'browser-sync', 'watch']);
gulp.task('default', ['build']);
| var gulp = require('gulp');
var elm = require('gulp-elm');
var plumber = require('gulp-plumber');
var del = require('del');
var browserSync = require('browser-sync');
// builds elm files and static resources (i.e. html and css) from src to dist folder
var paths = {
dest: 'dist',
elm: 'src/*.elm',
staticAssets: 'src/*.{html,css}'
};
gulp.task('clean', function(cb) {
del([paths.dest], cb);
});
gulp.task('elm-init', elm.init);
gulp.task('elm', ['elm-init'], function() {
return gulp.src(paths.elm)
.pipe(plumber())
.pipe(elm())
.pipe(gulp.dest(paths.dest))
.pipe(browserSync.stream());
});
gulp.task('staticAssets', function() {
return gulp.src(paths.staticAssets)
.pipe(plumber())
.pipe(gulp.dest(paths.dest))
.pipe(browserSync.stream());
});
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "dist/"
}
});
});
gulp.task('watch', function() {
gulp.watch(paths.elm, ['elm']);
gulp.watch(paths.staticAssets, ['staticAssets']);
});
gulp.task('build', ['elm', 'staticAssets']);
gulp.task('dev', ['build', 'browser-sync', 'watch']);
gulp.task('default', ['build']);
|
Bump version for stip_binary flag | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.16.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'confpy',
'ordereddict',
'semver',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cli:main',
],
'rpmvenv.extensions': [
'core = rpmvenv.extensions.core:Extension',
'file_permissions = rpmvenv.extensions.files.permissions:Extension',
'file_extras = rpmvenv.extensions.files.extras:Extension',
'python_venv = rpmvenv.extensions.python.venv:Extension',
'blocks = rpmvenv.extensions.blocks.generic:Extension',
]
},
package_data={
"rpmvenv": ["templates/*"],
},
)
| """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.15.1',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="[email protected]",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'confpy',
'ordereddict',
'semver',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cli:main',
],
'rpmvenv.extensions': [
'core = rpmvenv.extensions.core:Extension',
'file_permissions = rpmvenv.extensions.files.permissions:Extension',
'file_extras = rpmvenv.extensions.files.extras:Extension',
'python_venv = rpmvenv.extensions.python.venv:Extension',
'blocks = rpmvenv.extensions.blocks.generic:Extension',
]
},
package_data={
"rpmvenv": ["templates/*"],
},
)
|
Add dicts and models to package | # coding: utf-8
from __future__ import unicode_literals
from setuptools import (
setup,
find_packages,
)
setup(
name='natasha',
version='0.8.1',
description='Named-entity recognition for russian language',
url='https://github.com/natasha/natasha',
author='Natasha contributors',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Text Processing :: Linguistic',
],
keywords='natural language processing, russian morphology, named entity recognition, tomita',
packages=find_packages(),
package_data={
'natasha': [
'data/dicts/*',
'data/models/*',
]
},
install_requires=[
'yargy'
],
)
| # coding: utf-8
from __future__ import unicode_literals
from setuptools import (
setup,
find_packages,
)
setup(
name='natasha',
version='0.8.1',
description='Named-entity recognition for russian language',
url='https://github.com/natasha/natasha',
author='Natasha contributors',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Text Processing :: Linguistic',
],
keywords='natural language processing, russian morphology, named entity recognition, tomita',
packages=find_packages(),
package_data={
'natasha': [
'data/*',
]
},
install_requires=[
'yargy'
],
)
|
Remove skippable key in local storage on reset | // @flow
import UserState from './UserState';
import Raven from 'raven-js';
import storageService from '../storageService';
class UserStateService {
userState: UserState;
constructor() {
const data = this.load();
const name = data && data.name;
const age = data && data.age;
this.userState = new UserState(name, age);
this.updateUserContext();
}
getUserState(): UserState {
return this.userState;
}
hasNameAndAge(): boolean {
return !!this.userState.name && !!this.userState.age;
}
save() {
storageService.set('UserState', this.userState);
this.updateUserContext();
}
load(): ?Object {
return storageService.get('UserState');
}
reset() {
this.userState.name = null;
this.userState.age = null;
storageService.remove('UserState');
storageService.remove('splash.skippable');
}
updateUserContext() {
const { name, age } = this.userState;
if (name) {
Raven.setUserContext({
username: this.userState.name
});
}
if (age) {
Raven.setExtraContext({
age: this.userState.age
});
}
}
}
export default new UserStateService(); | // @flow
import UserState from './UserState';
import Raven from 'raven-js';
import storageService from '../storageService';
class UserStateService {
userState: UserState;
constructor() {
const data = this.load();
const name = data && data.name;
const age = data && data.age;
this.userState = new UserState(name, age);
this.updateUserContext();
}
getUserState(): UserState {
return this.userState;
}
hasNameAndAge(): boolean {
return !!this.userState.name && !!this.userState.age;
}
save() {
storageService.set('UserState', this.userState);
this.updateUserContext();
}
load(): ?Object {
return storageService.get('UserState');
}
reset() {
this.userState.name = null;
this.userState.age = null;
storageService.remove('UserState');
}
updateUserContext() {
const { name, age } = this.userState;
if (name) {
Raven.setUserContext({
username: this.userState.name
});
}
if (age) {
Raven.setExtraContext({
age: this.userState.age
});
}
}
}
export default new UserStateService(); |
Change to _.each that is awesome!!!. | define([
'underscore',
'views/proto/paged-collection',
'views/event/box',
'text!templates/event-collection.html'
], function (_, PagedCollection, EventBox, html) {
return PagedCollection.extend({
template: _.template(html),
tag: 'div',
listSelector: '.events-list',
generateItem: function (model) {
return new EventBox({ model: model });
},
events: {
"click .filter": "filter"
},
filter: function () {
var types=[];
$('.filter:checked').each(function() {
types.push($(this).val());
});
var filterString = types.join();
this.options.types = types;
this.collection.setTypes(types);
/* Set queryString to URL */
var url = '/feed';
if ( types.length > 0 ) {
url += '?types=' + filterString;
}
Backbone.trigger('pp:navigate', url, { replace: true });
},
serialize: function() {
var types = this.options.types || [];
var filterList = [
{
value: 'add-comment',
description: 'add-comment',
},
{
value: 'add-quest',
description: 'add-quest',
}
]
/* Add status for each filter */
_.each( filterList, function(list){
if( types.indexOf(list.value) != -1 ){
list.status = 'checked';
}else{
list.status = '';
}
});
return { filterList: filterList };
}
});
});
| define([
'underscore',
'views/proto/paged-collection',
'views/event/box',
'text!templates/event-collection.html'
], function (_, PagedCollection, EventBox, html) {
return PagedCollection.extend({
template: _.template(html),
tag: 'div',
listSelector: '.events-list',
generateItem: function (model) {
return new EventBox({ model: model });
},
events: {
"click .filter": "filter"
},
filter: function () {
var types=[];
$('.filter:checked').each(function() {
types.push($(this).val());
});
var filterString = types.join();
this.options.types = types;
this.collection.setTypes(types);
/* Set queryString to URL */
var url = '/feed';
if ( types.length > 0 ) {
url += '?types=' + filterString;
}
Backbone.trigger('pp:navigate', url, { replace: true });
},
serialize: function() {
var types = this.options.types || [];
var filterList = [
{
value: 'add-comment',
description: 'add-comment',
},
{
value: 'add-quest',
description: 'add-quest',
}
]
/* Add status for each filter */
for( var i = 0; i < filterList.length ; i++ ){
if( types.indexOf(filterList[i].value) != -1 ){
filterList[i].status = 'checked';
}else{
filterList[i].status = '';
}
}
return { filterList: filterList };
}
});
});
|
Fix issue where non localhost headless clouds werent calling finish
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com> | from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controller(controller) is not None
def finish(self):
if app.argv.model:
app.provider.model = app.argv.model
else:
app.provider.model = utils.gen_model()
return controllers.use('credentials').render()
async def _check_lxd_compat(self):
utils.info(
"Summoning {} to {}".format(app.argv.spell, app.provider.cloud))
if app.provider.cloud_type == cloud_types.LOCALHOST:
try:
app.provider._set_lxd_dir_env()
client_compatible = await app.provider.is_client_compatible()
server_compatible = await app.provider.is_server_compatible()
if client_compatible and server_compatible:
self.finish()
else:
utils.error("LXD Server or LXC client not compatible")
events.Shutdown.set(1)
except app.provider.LocalhostError:
raise
self.finish()
def render(self):
app.loop.create_task(self._check_lxd_compat())
_controller_class = CloudsController
| from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controller(controller) is not None
def finish(self):
if app.argv.model:
app.provider.model = app.argv.model
else:
app.provider.model = utils.gen_model()
return controllers.use('credentials').render()
async def _check_lxd_compat(self):
utils.info(
"Summoning {} to {}".format(app.argv.spell, app.provider.cloud))
if app.provider.cloud_type == cloud_types.LOCALHOST:
try:
app.provider._set_lxd_dir_env()
client_compatible = await app.provider.is_client_compatible()
server_compatible = await app.provider.is_server_compatible()
if client_compatible and server_compatible:
self.finish()
else:
utils.error("LXD Server or LXC client not compatible")
events.Shutdown.set(1)
except app.provider.LocalhostError:
raise
def render(self):
app.loop.create_task(self._check_lxd_compat())
_controller_class = CloudsController
|
Update request status to 'accepted' | Projects = new Mongo.Collection('projects');
Meteor.methods({
insertProject: function(projectAttributes) {
check(Meteor.userId(), String);
check(projectAttributes, {
name: Match.Where(function(val) {
check(val, String);
return val.length > 0;
}),
description: String
});
var ownerAttributes = {
userId: Meteor.userId(),
username: Meteor.user().username
};
var project = _.extend(projectAttributes, {
owner: ownerAttributes,
members: [],
tasks: [],
createdAt: new Date()
});
var projectId = Projects.insert(project);
return {
_id: projectId
};
},
addUserToProject: function(requestAttributes) {
check(Meteor.userId(), String);
check(requestAttributes, {
userId: String,
requestingUserId: String,
requestId: String,
projectId: String,
notificationId: String
});
Projects.update({
_id : requestAttributes.projectId
}, {
$addToSet: {
members: requestAttributes.requestingUserId
}
});
Requests.update({_id: requestAttributes.requestId}, {
status: 'accepted'
});
Meteor.call('setNotificationAsRead', requestAttributes.notificationId, function(err, result) {
if (err) {
console.log(err);
}
});
}
});
| Projects = new Mongo.Collection('projects');
Meteor.methods({
insertProject: function(projectAttributes) {
check(Meteor.userId(), String);
check(projectAttributes, {
name: Match.Where(function(val) {
check(val, String);
return val.length > 0;
}),
description: String
});
var ownerAttributes = {
userId: Meteor.userId(),
username: Meteor.user().username
};
var project = _.extend(projectAttributes, {
owner: ownerAttributes,
members: [],
tasks: [],
createdAt: new Date()
});
var projectId = Projects.insert(project);
return {
_id: projectId
};
},
addUserToProject: function(requestAttributes) {
check(Meteor.userId(), String);
check(requestAttributes, {
userId: String,
requestingUserId: String,
requestId: String,
projectId: String,
notificationId: String
});
Projects.update({
_id : requestAttributes.projectId
}, {
$addToSet: {
members: requestAttributes.requestingUserId
}
});
Meteor.call('setNotificationAsRead', requestAttributes.notificationId, function(err, result) {
if (err) {
console.log(err);
}
});
}
});
|
Fix stray zmq import in egg_info | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import glob
import os
import copy
from distutils.core import Extension
def get_extensions(**kwargs):
"""Get the Cython extensions"""
import zmq
this_directory = os.path.dirname(__file__)
this_name = __name__.split(".")[:-1]
extension_args = {
'include_dirs' : ['numpy'] + zmq.get_includes(),
'libraries' : [],
'sources' : []
}
extension_args.update(kwargs)
extensions = []
for component in glob.iglob(os.path.join(this_directory, "*.pyx")):
# Component name and full module name.
this_extension_args = copy.deepcopy(extension_args)
cname = os.path.splitext(os.path.basename(component))[0]
if cname.startswith("_"):
cname = cname[1:]
name = ".".join(this_name + ["_{0:s}".format(cname)])
else:
name = ".".join(this_name + [cname])
this_extension_args['sources'].append(component)
# Extension object.
extension = Extension(name, **this_extension_args)
extensions.append(extension)
return extensions | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import glob
import os
import copy
import zmq
from distutils.core import Extension
def get_extensions(**kwargs):
"""Get the Cython extensions"""
this_directory = os.path.dirname(__file__)
this_name = __name__.split(".")[:-1]
extension_args = {
'include_dirs' : ['numpy'] + zmq.get_includes(),
'libraries' : [],
'sources' : []
}
extension_args.update(kwargs)
extensions = []
for component in glob.iglob(os.path.join(this_directory, "*.pyx")):
# Component name and full module name.
this_extension_args = copy.deepcopy(extension_args)
cname = os.path.splitext(os.path.basename(component))[0]
if cname.startswith("_"):
cname = cname[1:]
name = ".".join(this_name + ["_{0:s}".format(cname)])
else:
name = ".".join(this_name + [cname])
this_extension_args['sources'].append(component)
# Extension object.
extension = Extension(name, **this_extension_args)
extensions.append(extension)
return extensions |
Allow coverage version 6+ . | from setuptools import setup
long_description = "".join(open("README.rst").readlines())
setup(
name="pytest-testmon",
description="selects tests affected by changed files and methods",
long_description=long_description,
version="1.1.2",
license="AGPL",
platforms=["linux", "osx", "win32"],
packages=[
"testmon",
],
url="https://testmon.org",
author_email="[email protected]",
author="Tibor Arpas, Tomas Matlovic, Daniel Hahler, Martin Racak",
entry_points={
"pytest11": [
"testmon = testmon.pytest_testmon",
],
"tox": [
"testmon = testmon.tox_testmon",
],
},
python_requires=">=3.6",
install_requires=["pytest>=5,<7", "coverage>=4,<7"],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Operating System :: Microsoft :: Windows",
"Operating System :: MacOS :: MacOS X",
"Topic :: Software Development :: Testing",
"Topic :: Software Development :: Libraries",
"Topic :: Utilities",
"Programming Language :: Python",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
)
| from setuptools import setup
long_description = "".join(open("README.rst").readlines())
setup(
name="pytest-testmon",
description="selects tests affected by changed files and methods",
long_description=long_description,
version="1.1.2",
license="AGPL",
platforms=["linux", "osx", "win32"],
packages=[
"testmon",
],
url="https://testmon.org",
author_email="[email protected]",
author="Tibor Arpas, Tomas Matlovic, Daniel Hahler, Martin Racak",
entry_points={
"pytest11": [
"testmon = testmon.pytest_testmon",
],
"tox": [
"testmon = testmon.tox_testmon",
],
},
python_requires=">=3.6",
install_requires=["pytest>=5,<7", "coverage>=4,<6"],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Operating System :: Microsoft :: Windows",
"Operating System :: MacOS :: MacOS X",
"Topic :: Software Development :: Testing",
"Topic :: Software Development :: Libraries",
"Topic :: Utilities",
"Programming Language :: Python",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
)
|
Fix georgian locale syntax error | /**
* Select2 Georgian (Kartuli) translation.
*
* Author: Dimitri Kurashvili [email protected]
*/
(function ($) {
"use strict";
$.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "แแแ แแแแซแแแแ"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "แแแฎแแแ แจแแแงแแแแแ แแแแแ " + n + " แกแแแแแแ"; },
formatInputTooLong: function (input, max) { var n = input.length - max; return "แแแฎแแแ แฌแแจแแแแ " + n + " แกแแแแแแ"; },
formatSelectionTooBig: function (limit) { return "แแฅแแแ แจแแแแซแแแแ แแฎแแแแ " + limit + " แฉแแแแฌแแ แแก แแแแแจแแแ"; },
formatLoadMore: function (pageNumber) { return "แจแแแแแแก แฉแแขแแแ แแแ..."; },
formatSearching: function () { return "แซแแแแ..."; }
});
})(jQuery);
| /**
* Select2 Georgian (Kartuli) translation.
*
* Author: Dimitri Kurashvili [email protected]
*/
(function ($) {
"use strict";
$.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "แแแ แแแแซแแแแ"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "แแแฎแแแ แจแแแงแแแแแ แแแแแ " + n + " แกแแแแแแ"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "แแแฎแแแ แฌแแจแแแแ " + n + " แกแแแแแแ"); },
formatSelectionTooBig: function (limit) { return "แแฅแแแ แจแแแแซแแแแ แแฎแแแแ " + limit + " แฉแแแแฌแแ แแก แแแแแจแแแ"); },
formatLoadMore: function (pageNumber) { return "แจแแแแแแก แฉแแขแแแ แแแ..."; },
formatSearching: function () { return "แซแแแแ..."; }
});
})(jQuery);
|
Unify handling of arrival and departure prognosis
In response to #113 | <?php
namespace Transport\Entity\Schedule;
class Prognosis
{
public $platform;
public $arrival;
public $departure;
public $capacity1st;
public $capacity2nd;
static public function createFromXml(\SimpleXMLElement $xml, \DateTime $date, $isArrival, Prognosis $obj = null)
{
if (!$obj) {
$obj = new Prognosis();
}
if ($isArrival) {
if ($xml->Arr) {
if ($xml->Arr->Platform) {
$obj->platform = (string) $xml->Arr->Platform->Text;
}
}
} else {
if ($xml->Dep) {
if ($xml->Dep->Platform) {
$obj->platform = (string) $xml->Dep->Platform->Text;
}
}
}
if ($xml->Arr) {
if ($xml->Arr->Time) {
$obj->arrival = Stop::calculateDateTime((string) $xml->Arr->Time, $date)->format(\DateTime::ISO8601);
}
}
if ($xml->Dep) {
if ($xml->Dep->Time) {
$obj->departure = Stop::calculateDateTime((string) $xml->Dep->Time, $date)->format(\DateTime::ISO8601);
}
}
if ($xml->Capacity1st) {
$obj->capacity1st = (int) $xml->Capacity1st;
}
if ($xml->Capacity2nd) {
$obj->capacity2nd = (int) $xml->Capacity2nd;
}
return $obj;
}
}
| <?php
namespace Transport\Entity\Schedule;
class Prognosis
{
public $platform;
public $arrival;
public $departure;
public $capacity1st;
public $capacity2nd;
static public function createFromXml(\SimpleXMLElement $xml, \DateTime $date, $isArrival, Prognosis $obj = null)
{
if (!$obj) {
$obj = new Prognosis();
}
if ($isArrival) {
if ($xml->Arr) {
if ($xml->Arr->Platform) {
$obj->platform = (string) $xml->Arr->Platform->Text;
}
if ($xml->Arr->Time) {
$obj->arrival = Stop::calculateDateTime((string) $xml->Arr->Time, $date)->format(\DateTime::ISO8601);
}
}
} else {
if ($xml->Dep) {
if ($xml->Dep->Platform) {
$obj->platform = (string) $xml->Dep->Platform->Text;
}
}
}
if ($xml->Dep) {
if ($xml->Dep->Time) {
$obj->departure = Stop::calculateDateTime((string) $xml->Dep->Time, $date)->format(\DateTime::ISO8601);
}
}
if ($xml->Capacity1st) {
$obj->capacity1st = (int) $xml->Capacity1st;
}
if ($xml->Capacity2nd) {
$obj->capacity2nd = (int) $xml->Capacity2nd;
}
return $obj;
}
}
|
Remove console.log from GifMe module | // $ GifMe
// $ Authors: victorgama
// $ Created on: Mon Mar 14 15:29:14 BRT 2016
// - Gif( me) <categoria>: Pesquisa por gifs contendo a categoria especificada
// no giphy.com e retorna um resultado aleatรณrio.
var Base = require('../src/base_module');
var GifMe = function(bot) {
Base.call(this, bot);
this.respond(/gif( me)? ([\w\??| ]+)$/i, (response) => {
var tag = response.match[2];
this.http({
uri: 'http://api.gifme.io/v1/search',
qs: {
sfw: 'true',
key: 'rX7kbMzkGu7WJwvG',
query: tag
},
json: true
})
.then(d => {
if(d.status !== 200) {
response.reply('Nรฃo consegui pesquisar o termo. Talvez a internet esteja quebrada. :stuck_out_tongue:');
} else {
if(!d.data.length) {
response.reply('Nรฃo conheรงo essa reaรงรฃo... :disappointed:');
} else {
response.reply(this.random(d.data.filter(i => !i.nsfw)).link);
}
}
});
});
};
Base.setup(GifMe);
module.exports = GifMe;
| // $ GifMe
// $ Authors: victorgama
// $ Created on: Mon Mar 14 15:29:14 BRT 2016
// - Gif( me) <categoria>: Pesquisa por gifs contendo a categoria especificada
// no giphy.com e retorna um resultado aleatรณrio.
var Base = require('../src/base_module');
var GifMe = function(bot) {
Base.call(this, bot);
this.respond(/gif( me)? ([\w\??| ]+)$/i, (response) => {
var tag = response.match[2];
this.http({
uri: 'http://api.gifme.io/v1/search',
qs: {
sfw: 'true',
key: 'rX7kbMzkGu7WJwvG',
query: tag
},
json: true
})
.then(d => {
console.log(d);
if(d.status !== 200) {
response.reply('Nรฃo consegui pesquisar o termo. Talvez a internet esteja quebrada. :stuck_out_tongue:');
} else {
if(!d.data.length) {
response.reply('Nรฃo conheรงo essa reaรงรฃo... :disappointed:');
} else {
response.reply(this.random(d.data.filter(i => !i.nsfw)).link);
}
}
});
});
};
Base.setup(GifMe);
module.exports = GifMe;
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.