text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add new external event for pause/resume bundle | /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.notification.plugin.api;
/**
* The enum {@code ExtBusEventType} represents the user visible bus event types.
*/
public enum ExtBusEventType {
ACCOUNT_CREATION,
ACCOUNT_CHANGE,
SUBSCRIPTION_CREATION,
SUBSCRIPTION_PHASE,
SUBSCRIPTION_CHANGE,
SUBSCRIPTION_CANCEL,
SUBSCRIPTION_UNCANCEL,
BUNDLE_PAUSE,
BUNDLE_RESUME,
OVERDUE_CHANGE,
INVOICE_CREATION,
INVOICE_ADJUSTMENT,
PAYMENT_SUCCESS,
PAYMENT_FAILED,
TAG_CREATION,
TAG_DELETION,
CUSTOM_FIELD_CREATION,
CUSTOM_FIELD_DELETION;
}
| /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.notification.plugin.api;
/**
* The enum {@code ExtBusEventType} represents the user visible bus event types.
*/
public enum ExtBusEventType {
ACCOUNT_CREATION,
ACCOUNT_CHANGE,
SUBSCRIPTION_CREATION,
SUBSCRIPTION_PHASE,
SUBSCRIPTION_CHANGE,
SUBSCRIPTION_CANCEL,
SUBSCRIPTION_UNCANCEL,
OVERDUE_CHANGE,
INVOICE_CREATION,
INVOICE_ADJUSTMENT,
PAYMENT_SUCCESS,
PAYMENT_FAILED,
TAG_CREATION,
TAG_DELETION,
CUSTOM_FIELD_CREATION,
CUSTOM_FIELD_DELETION;
}
|
Move zoom control on bottom right | var satAttr = 'Modified <a href="https://scihub.copernicus.eu/">Copernicus</a>' +
' Sentinel data 2016 by ' +
'<a href="https://www.sentinelmap.eu">SentinelMap</a>' ;
var osmAttr = ' | © <a href="https://openstreetmap.org/copyright">OSM</a>' +
' contributors data by ' +
'<a href="https://mapzen.com">Mapzen</a>' ;
var Attr = satAttr + osmAttr ;
var scLayer = Tangram.leafletLayer({
scene: 'scene@1.1.yaml',
attribution: Attr,
});
var map = L.map('map' , {
center: [ 48.92, 11.25],
//center: [ 47.04, 8.44],
zoom: 6,
maxZoom: 16,
minZoom: 5,
layers: [scLayer],
zoomControl: false
});
var baseLayers = {
"Sentinel-2": scLayer,
};
L.control.zoom({position: 'bottomright'}).addTo(map);
var hash = new L.Hash(map);
var sidebar = L.control.sidebar('sidebar').addTo(map);
// DEBUG
/*
scLayer.scene.subscribe({
load: function (e) {
console.log('scene loaded:', e);
}
});
scLayer.scene.subscribe({
view_complete: function () {
console.log('scene view complete');
}
});
*/
| var satAttr = 'Modified <a href="https://scihub.copernicus.eu/">Copernicus</a>' +
' Sentinel data 2016 by ' +
'<a href="https://www.sentinelmap.eu">SentinelMap</a>' ;
var osmAttr = ' | © <a href="https://openstreetmap.org/copyright">OSM</a>' +
' contributors data by ' +
'<a href="https://mapzen.com">Mapzen</a>' ;
var Attr = satAttr + osmAttr ;
var scLayer = Tangram.leafletLayer({
scene: 'scene@1.1.yaml',
attribution: Attr,
});
var map = L.map('map' , {
center: [ 48.92, 11.25],
//center: [ 47.04, 8.44],
zoom: 6,
maxZoom: 16,
minZoom: 5,
layers: [scLayer],
zoomControl: false
});
var baseLayers = {
"Sentinel-2": scLayer,
};
L.control.zoom({position: 'topright'}).addTo(map);
var hash = new L.Hash(map);
var sidebar = L.control.sidebar('sidebar').addTo(map);
// DEBUG
/*
scLayer.scene.subscribe({
load: function (e) {
console.log('scene loaded:', e);
}
});
scLayer.scene.subscribe({
view_complete: function () {
console.log('scene view complete');
}
});
*/
|
Use common object for csvio calls | """
Hacker News Top:
-Get top stories from Hacker News' official API
-Record all users who comment on those stories
Author: Rylan Santinon
"""
from api_connector import *
from csv_io import *
def main():
conn = ApiConnector()
csvio = CsvIo()
article_list = conn.get_top()
stories = []
for i in article_list:
try:
story = conn.get_item(i)
if story.get("deleted"):
continue
print csvio.story_to_csv(story)
stories.append(story)
except NetworkError as e:
print e
csvio.write_stories_csv(stories)
for story in stories:
try:
conn.get_kids(story)
except NetworkError as e:
print e
users = []
for u in sorted(conn.user_dict.keys()):
try:
userjson = conn.get_user(u)
users.append(userjson)
print u
except NetworkError as e:
print e
csvio.write_users_csv(users)
if __name__ == '__main__':
csvio = CsvIo()
main()
csvio.concat_users()
csvio.concat_stories()
| """
Hacker News Top:
-Get top stories from Hacker News' official API
-Record all users who comment on those stories
Author: Rylan Santinon
"""
from api_connector import *
from csv_io import *
def main():
conn = ApiConnector()
csvio = CsvIo()
article_list = conn.get_top()
stories = []
for i in article_list:
try:
story = conn.get_item(i)
if story.get("deleted"):
continue
print csvio.story_to_csv(story)
stories.append(story)
except NetworkError as e:
print e
csvio.write_stories_csv(stories)
for story in stories:
try:
conn.get_kids(story)
except NetworkError as e:
print e
users = []
for u in sorted(conn.user_dict.keys()):
try:
userjson = conn.get_user(u)
users.append(userjson)
print u
except NetworkError as e:
print e
csvio.write_users_csv(users)
if __name__ == '__main__':
main()
CsvIo().concat_users()
CsvIo().concat_stories()
|
Fix tests: Allow for celery not to be running when doing in-memory celery for tests. | """
Methods for interfacing with the Celery task queue management library.
"""
from errno import errorcode
from celery.task.control import inspect
from django.conf import settings
CELERY_ERROR_KEY = 'ERROR'
def get_celery_worker_status():
"""Checks whether celery is running and reports the error if not.
Source: http://stackoverflow.com/questions/8506914/detect-whether-celery-is-available-running
"""
if settings.BROKER_BACKEND == 'memory':
# We are testing with in-memory celery. Celery is effectively running.
return {}
try:
insp = inspect()
d = insp.stats()
if not d:
d = { CELERY_ERROR_KEY: 'No running Celery workers were found.' }
except IOError as e:
msg = "Error connecting to the backend: " + str(e)
if len(e.args) > 0 and errorcode.get(e.args[0]) == 'ECONNREFUSED':
msg += ' Check that the RabbitMQ server is running.'
d = { CELERY_ERROR_KEY: msg }
except ImportError as e:
d = { CELERY_ERROR_KEY: str(e)}
return d
| """
Methods for interfacing with the Celery task queue management library.
"""
from errno import errorcode
from celery.task.control import inspect
CELERY_ERROR_KEY = 'ERROR'
def get_celery_worker_status():
"""Checks whether celery is running and reports the error if not.
Source: http://stackoverflow.com/questions/8506914/detect-whether-celery-is-available-running
"""
try:
insp = inspect()
d = insp.stats()
if not d:
d = { CELERY_ERROR_KEY: 'No running Celery workers were found.' }
except IOError as e:
msg = "Error connecting to the backend: " + str(e)
if len(e.args) > 0 and errorcode.get(e.args[0]) == 'ECONNREFUSED':
msg += ' Check that the RabbitMQ server is running.'
d = { CELERY_ERROR_KEY: msg }
except ImportError as e:
d = { CELERY_ERROR_KEY: str(e)}
return d
|
Change webpack config import path | import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../../../config/webpack.dev.js';
const webpackCompiler = webpack(webpackConfig);
// enable webpack middleware for hot-reloads in development
export default function useWebpackMiddleware(app) {
app.use(webpackDevMiddleware(webpackCompiler, {
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true,
chunks: false,
'errors-only': true
}
}));
app.use(webpackHotMiddleware(webpackCompiler, {
log: console.log
}));
return app;
}
| import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../../webpack.config.js';
const webpackCompiler = webpack(webpackConfig);
// enable webpack middleware for hot-reloads in development
export default function useWebpackMiddleware(app) {
app.use(webpackDevMiddleware(webpackCompiler, {
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true,
chunks: false,
'errors-only': true
}
}));
app.use(webpackHotMiddleware(webpackCompiler, {
log: console.log
}));
return app;
}
|
Add test event and adjust URL to proxy config | const express = require('express')
const socketio = require('socket.io')
const http = require('http')
const config = require('./config')
const app = express()
const server = http.Server(app)
const io = socketio(server, { path: '/ws' })
const host = config.host || '0.0.0.0'
const port = config.port || 8080
let connections = 0
let timer = 0
io.on('connection', function(connection) {
const socket = connection
++connections
process.stdout.write('[Server] A websocket client connected.\n')
if (connections && !timer) {
timer = setInterval(() => {
socket.emit('testTimer', { timestamp: Date.now() })
}, 1000)
}
socket.on('disconnect', () => {
--connections
process.stdout.write('[Server] A websocket client disconnected.\n')
if (!connections && timer) {
clearInterval(timer)
timer = null
}
})
})
app.get('/api/v1/hello-world', (req, res) => {
return res.status(200).json({ message: 'Hello World!' })
})
app.use((req, res, next) => {
return res
.status(404)
.jsonp({ message: 'This API endpoint is not supported.' })
})
app.use((err, req, res, next) => {
return res.status(500).json({ message: 'An unknown error occured.' })
})
server.listen(port, host, () => {
process.stdout.write(`[Server] Listening on ${host}:${port}\n`)
})
| const express = require('express')
const socketio = require('socket.io')
const http = require('http')
const config = require('./config')
const app = express()
const server = http.Server(app)
const io = socketio(server)
const host = config.host || '0.0.0.0'
const port = config.port || 8080
app.get('/', (req, res) => {
res.status(200).json({ message: 'Hello World!' })
})
io.on('connection', function(socket) {
socket.on('sendWifiSignalStrength', data => {
io.emit('updateWifiSignalStrength', data)
})
})
app.use((err, req, res, next) => {
return res.status(500).json({ message: 'An unknown error occured.', err })
})
server.listen(port, host, () => {
process.stdout.write(`[Server] Listening on ${host}:${port}\n`)
})
|
Allow running jobsteps to be deallocated | from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(self, step_id):
to_deallocate = JobStep.query.get(step_id)
if to_deallocate is None:
return '', 404
if to_deallocate.status not in (Status.in_progress, Status.allocated):
return {
"error": "Only allocated and running job steps may be deallocated.",
"actual_status": to_deallocate.status.name
}, 400
to_deallocate.status = Status.pending_allocation
to_deallocate.date_started = None
to_deallocate.date_finished = None
db.session.add(to_deallocate)
db.session.commit()
sync_job_step.delay(
step_id=to_deallocate.id.hex,
task_id=to_deallocate.id.hex,
parent_task_id=to_deallocate.job_id.hex,
)
return self.respond(to_deallocate)
| from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(self, step_id):
to_deallocate = JobStep.query.get(step_id)
if to_deallocate is None:
return '', 404
if to_deallocate.status != Status.allocated:
return {
"error": "Only {0} job steps may be deallocated.",
"actual_status": to_deallocate.status.name
}, 400
to_deallocate.status = Status.pending_allocation
to_deallocate.date_started = None
to_deallocate.date_finished = None
db.session.add(to_deallocate)
db.session.commit()
sync_job_step.delay(
step_id=to_deallocate.id.hex,
task_id=to_deallocate.id.hex,
parent_task_id=to_deallocate.job_id.hex,
)
return self.respond(to_deallocate)
|
Add a callback parameter to Tanura's events. | 'use strict';
/*
* Tanura main script.
*
* This script defines Tanura's high level features.
*/
/*
* Check if an event exists.
*
* When given an event name, this function will check, if there is an entry in
* tanura.eventHandler.events for that name, that has the methods required.
*/
tanura.eventHandler.check = function(_) {
return !! this[_] && Array.isArray(this[_]);
}.bind(tanura.eventHandler.events)
/*
* Safely perform something on an event.
*
* This will check if a given event exists and call a given function on it, if
* it does. The return value indicates if the event was found.
*/
tanura.eventHandler.safe = function(_, f) {
return this.check(_) && ! f(this.events[_]) || true;
}.bind(tanura.eventHandler)
/*
* Fire an event.
*
* When given an event name, this function will run all callbacks for that
* event. A single parameter for the callback may be passed. Exit is true on
* success, false otherwise.
*/
tanura.eventHandler.fire = (_, x) =>
tanura.eventHandler.safe(_, (_) => _.forEach((i) => i(x)));
/*
* Register a callback for an event.
*
* This will add a function to be called whenever a given event occurs. Exit is
* true on success, false otherwise.
*/
tanura.eventHandler.register = (_, f) =>
tanura.eventHandler.safe(_, (_) => _.push(f));
| 'use strict';
/*
* Tanura main script.
*
* This script defines Tanura's high level features.
*/
/*
* Check if an event exists.
*
* When given an event name, this function will check, if there is an entry in
* tanura.eventHandler.events for that name, that has the methods required.
*/
tanura.eventHandler.check = function(_) {
return !! this[_] && Array.isArray(this[_]);
}.bind(tanura.eventHandler.events)
/*
* Safely perform something on an event.
*
* This will check if a given event exists and call a given function on it, if
* it does. The return value indicates if the event was found.
*/
tanura.eventHandler.safe = function(_, f) {
return this.check(_) && ! f(this.events[_]) || true;
}.bind(tanura.eventHandler)
/*
* Fire an event.
*
* When given an event name, this function will run all callbacks for that
* event. Exit is true on success, false otherwise.
*/
tanura.eventHandler.fire = (_) =>
tanura.eventHandler.safe(_, (_) => _.forEach((i) => i()));
/*
* Register a callback for an event.
*
* This will add a function to be called whenever a given event occurs. Exit is
* true on success, false otherwise.
*/
tanura.eventHandler.register = (_, f) =>
tanura.eventHandler.safe(_, (_) => _.push(f));
|
Test for flaky/ornery whois.pir.org server | package whois
import (
"os"
"testing"
"github.com/domainr/whoistest"
"github.com/nbio/st"
)
func TestReadMIME(t *testing.T) {
fns, err := whoistest.ResponseFiles()
st.Assert(t, err, nil)
for _, fn := range fns {
// fmt.Printf("%s\n", fn)
res, err := readMIMEFile(fn)
st.Refute(t, res, nil)
st.Assert(t, err, nil)
// fmt.Printf("%#v\n\n", res)
}
}
func readMIMEFile(fn string) (*Response, error) {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
defer f.Close()
return ReadMIME(f)
}
func TestRateLimit(t *testing.T) {
req, err := Resolve("google.org")
st.Assert(t, err, nil)
res, err := req.Fetch()
st.Assert(t, err, nil)
st.Expect(t, res.MediaType, "text/plain")
st.Expect(t, res.Charset, "iso-8859-1")
res.Body = []byte("WHOIS LIMIT EXCEEDED - SEE WWW.PIR.ORG/WHOIS FOR DETAILS\n")
res.DetectContentType("")
st.Expect(t, res.MediaType, "text/plain")
st.Expect(t, res.Charset, "windows-1252")
h := res.Header()
st.Expect(t, h.Get("Content-Type"), "text/plain; charset=windows-1252")
}
| package whois
import (
"fmt"
"os"
"testing"
"github.com/domainr/whoistest"
"github.com/nbio/st"
)
func TestReadMIME(t *testing.T) {
fns, err := whoistest.ResponseFiles()
st.Assert(t, err, nil)
for _, fn := range fns {
fmt.Printf("%s\n", fn)
res, err := readMIMEFile(fn)
if res != nil && err != nil {
fmt.Fprintf(os.Stderr, "Error reading MIME file: %s\n", err.Error())
res.DetectContentType("")
}
// st.Assert(t, err, nil)
res.Body = make([]byte, 0)
fmt.Printf("%#v\n\n", res)
}
}
func readMIMEFile(fn string) (*Response, error) {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
defer f.Close()
return ReadMIME(f)
}
|
Fix bug some log output showing on screen not present in log file by changing logging file handler mode from 'w' write to 'a' append. | # https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial
import logging
import sys
def get_logger(name):
"""
https://stackoverflow.com/questions/28330317/print-timestamp-for-logging-in-python
https://docs.python.org/3/library/logging.html#formatter-objects
https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial
https://docs.python.org/3.6/howto/logging.html#logging-to-a-file
:param name: logger name
:return: a configured logger
"""
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(funcName)s line:%(lineno)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# add one or more handlers
# log to file
# mode 'a' append, not 'w' write
handler = logging.FileHandler('./data/output/fib.log', mode='a')
handler.setFormatter(formatter)
logger.addHandler(handler)
# log to terminal stdout
screen_handler = logging.StreamHandler(stream=sys.stdout)
screen_handler.setFormatter(formatter)
logger.addHandler(screen_handler)
return logger
| # https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial
import logging
import sys
def get_logger(name):
"""
https://stackoverflow.com/questions/28330317/print-timestamp-for-logging-in-python
https://docs.python.org/3/library/logging.html#formatter-objects
https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial
https://docs.python.org/3.6/howto/logging.html#logging-to-a-file
:param name: logger name
:return: a configured logger
"""
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(funcName)s line:%(lineno)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# add one or more handlers
# log to file
handler = logging.FileHandler('./data/output/fib.log', mode='w')
handler.setFormatter(formatter)
logger.addHandler(handler)
# log to terminal stdout
screen_handler = logging.StreamHandler(stream=sys.stdout)
screen_handler.setFormatter(formatter)
logger.addHandler(screen_handler)
return logger
|
Print tasks with manifest with no execution field
I think all should have it but possibly not? | import fs from 'fs';
import fetchAllPages from './fetchAllPages.js';
const token = process.argv[2];
if (!token) {
throw new Error('Provide a PAT as a CLI argument!');
}
const issues = await fetchAllPages(token, 'repos/microsoft/azure-pipelines-tasks/issues', { labels: 'node-migration', state: 'all' });
console.log('Found', issues.length, 'Node migration issues');
let errors = 0;
for (const entry of await fs.promises.readdir('../../Tasks', { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === 'Common') {
continue;
}
const manifest = JSON.parse(await fs.promises.readFile('../../Tasks/' + entry.name + '/task.json'));
if (!manifest.execution) {
console.log(entry.name);
console.log(manifest);
errors++;
continue;
}
const keys = Object.keys(manifest.execution).filter(key => key.startsWith('Node'));
if (keys.length === 0) {
continue;
}
console.log(entry.name, 'uses', keys);
}
if (errors.length > 0) {
console.log(errors.length, 'errors encountered');
}
process.exit(errors);
| import fs from 'fs';
import fetchAllPages from './fetchAllPages.js';
const token = process.argv[2];
if (!token) {
throw new Error('Provide a PAT as a CLI argument!');
}
const issues = await fetchAllPages(token, 'repos/microsoft/azure-pipelines-tasks/issues', { labels: 'node-migration', state: 'all' });
console.log('Found', issues.length, 'Node migration issues');
for (const entry of await fs.promises.readdir('../../Tasks', { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === 'Common') {
continue;
}
const manifest = JSON.parse(await fs.promises.readFile('../../Tasks/' + entry.name + '/task.json'));
const keys = Object.keys(manifest.execution).filter(key => key.startsWith('Node'));
if (keys.length === 0) {
continue;
}
console.log(entry.name, 'uses', keys);
}
|
Fix action bar color in 2.3 (typo)
Change-Id: I188538b58d9e0235be964c1a509dc1117585b439 | package org.wikipedia;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
public class ThemedActionBarActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(WikipediaApp.getInstance().getCurrentTheme());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
//this only seems to be necessary to support 2.3:
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(Utils.getThemedAttributeId(this, R.attr.actionbar_background_color)));
}
}
}
| package org.wikipedia;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
public class ThemedActionBarActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(WikipediaApp.getInstance().getCurrentTheme());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//this only seems to be necessary to support 2.3:
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(Utils.getThemedAttributeId(this, R.attr.actionbar_background_color)));
}
}
}
|
Add a discovery format hint for date fields in SearchEngine UIs
Summary:
See PHI316. Maniphest and other applications currently have controls like `Created After: [_____]` where you just get an empty text field.
Although most formats work -- including relative formats like "3 days ago" -- and we validate inputs so you get an error if you enter something nonsensical, this still isn't very user friendly.
T8060 or some other approach is likely the long term of this control.
In the meantime, add placeholder text to suggest that `YYYY-MM-DD` or `X days ago` will work.
Test Plan: Viewed date inputs, saw placeholder text.
Reviewers: amckinley
Reviewed By: amckinley
Differential Revision: https://secure.phabricator.com/D18942 | <?php
final class PhabricatorSearchDateField
extends PhabricatorSearchField {
protected function newControl() {
return id(new AphrontFormTextControl())
->setPlaceholder(pht('"2022-12-25" or "7 days ago"...'));
}
protected function getValueFromRequest(AphrontRequest $request, $key) {
return $request->getStr($key);
}
public function getValueForQuery($value) {
return $this->parseDateTime($value);
}
protected function validateControlValue($value) {
if (!strlen($value)) {
return;
}
$epoch = $this->parseDateTime($value);
if ($epoch) {
return;
}
$this->addError(
pht('Invalid'),
pht('Date value for "%s" can not be parsed.', $this->getLabel()));
}
protected function parseDateTime($value) {
if (!strlen($value)) {
return null;
}
// If this appears to be an epoch timestamp, just return it unmodified.
// This assumes values like "2016" or "20160101" are "Ymd".
if (is_int($value) || ctype_digit($value)) {
if ((int)$value > 30000000) {
return (int)$value;
}
}
return PhabricatorTime::parseLocalTime($value, $this->getViewer());
}
protected function newConduitParameterType() {
return new ConduitEpochParameterType();
}
}
| <?php
final class PhabricatorSearchDateField
extends PhabricatorSearchField {
protected function newControl() {
return new AphrontFormTextControl();
}
protected function getValueFromRequest(AphrontRequest $request, $key) {
return $request->getStr($key);
}
public function getValueForQuery($value) {
return $this->parseDateTime($value);
}
protected function validateControlValue($value) {
if (!strlen($value)) {
return;
}
$epoch = $this->parseDateTime($value);
if ($epoch) {
return;
}
$this->addError(
pht('Invalid'),
pht('Date value for "%s" can not be parsed.', $this->getLabel()));
}
protected function parseDateTime($value) {
if (!strlen($value)) {
return null;
}
// If this appears to be an epoch timestamp, just return it unmodified.
// This assumes values like "2016" or "20160101" are "Ymd".
if (is_int($value) || ctype_digit($value)) {
if ((int)$value > 30000000) {
return (int)$value;
}
}
return PhabricatorTime::parseLocalTime($value, $this->getViewer());
}
protected function newConduitParameterType() {
return new ConduitEpochParameterType();
}
}
|
Switch to mock builder as it works across all PHPUnit versions. | <?php
namespace React\Tests\EventLoop;
class TestCase extends \PHPUnit_Framework_TestCase
{
protected function expectCallableExactly($amount)
{
$mock = $this->createCallableMock();
$mock
->expects($this->exactly($amount))
->method('__invoke');
return $mock;
}
protected function expectCallableOnce()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke');
return $mock;
}
protected function expectCallableNever()
{
$mock = $this->createCallableMock();
$mock
->expects($this->never())
->method('__invoke');
return $mock;
}
protected function createCallableMock()
{
return $this->getMockBuilder('React\Tests\EventLoop\CallableStub')->getMock();
}
}
| <?php
namespace React\Tests\EventLoop;
class TestCase extends \PHPUnit_Framework_TestCase
{
protected function expectCallableExactly($amount)
{
$mock = $this->createCallableMock();
$mock
->expects($this->exactly($amount))
->method('__invoke');
return $mock;
}
protected function expectCallableOnce()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke');
return $mock;
}
protected function expectCallableNever()
{
$mock = $this->createCallableMock();
$mock
->expects($this->never())
->method('__invoke');
return $mock;
}
protected function createCallableMock()
{
$stub = 'React\Tests\EventLoop\CallableStub';
if (method_exists($this, 'createMock')) {
return $this->createMock($stub);
}
return $this->getMock($stub);
}
}
|
Fix issue pipe covered recipes using wool are not displayed in JEI | package jp.crafterkina.pipes.plugin.jei.crafting;
import mezz.jei.api.recipe.IRecipeHandler;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.api.recipe.VanillaRecipeCategoryUid;
import javax.annotation.Nonnull;
/**
* Created by Kina on 2016/12/25.
*/
public class CoverPipeWithWoolRecipeHandler implements IRecipeHandler<CoverPipeWithWoolRecipeWrapper>{
@Nonnull
@Override
public Class<CoverPipeWithWoolRecipeWrapper> getRecipeClass(){
return CoverPipeWithWoolRecipeWrapper.class;
}
@Nonnull
@Override
public String getRecipeCategoryUid(@Nonnull CoverPipeWithWoolRecipeWrapper recipe){
return VanillaRecipeCategoryUid.CRAFTING;
}
@Nonnull
@Override
public IRecipeWrapper getRecipeWrapper(@Nonnull CoverPipeWithWoolRecipeWrapper recipe){
return recipe;
}
@Override
public boolean isRecipeValid(@Nonnull CoverPipeWithWoolRecipeWrapper recipe){
return true;
}
}
| package jp.crafterkina.pipes.plugin.jei.crafting;
import mezz.jei.api.recipe.IRecipeHandler;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.api.recipe.VanillaRecipeCategoryUid;
import javax.annotation.Nonnull;
/**
* Created by Kina on 2016/12/25.
*/
public class CoverPipeWithWoolRecipeHandler implements IRecipeHandler<CoverPipeWithCarpetRecipeWrapper>{
@Nonnull
@Override
public Class<CoverPipeWithCarpetRecipeWrapper> getRecipeClass(){
return CoverPipeWithCarpetRecipeWrapper.class;
}
@Nonnull
@Override
public String getRecipeCategoryUid(@Nonnull CoverPipeWithCarpetRecipeWrapper recipe){
return VanillaRecipeCategoryUid.CRAFTING;
}
@Nonnull
@Override
public IRecipeWrapper getRecipeWrapper(@Nonnull CoverPipeWithCarpetRecipeWrapper recipe){
return recipe;
}
@Override
public boolean isRecipeValid(@Nonnull CoverPipeWithCarpetRecipeWrapper recipe){
return true;
}
}
|
:memo: Fix link typo in docs | import {rule, group} from '../../typography-fixer'
import html from '../html'
let frFR_HTML
/**
* The ruleset for HTML improvement on french typography
*
* It includes rules for:
*
* - Wrapping ends of common abbreviation in a `<sup>` tag so that `Mmes`
* becomes `M<sup>mes</sup>`
* - Wrapping ordinal number suffix in a `<sup>` tag
*
* Finally, the following rulesets are also included:
*
* - {@link src/rules/html.js~html}
*
* @type {Array<Object>}
*/
export default frFR_HTML = createRuleset().concat(html)
function createRuleset () {
return group('fr-FR.html', [
rule('abbrWithSuperText', /Mmes|Mme|Mlles|Mlle|Me|Mgr|Dr|cie|Cie|Sté/, (m) => {
return `${m[0]}<sup>${m.slice(1, m.length)}</sup>`
}),
rule('ordinalNumbers', /(\d)(res|re|es|e|èmes)/, '$1<sup class="ord">$2</sup>')
])
}
| import {rule, group} from '../../typography-fixer'
import html from '../html'
let frFR_HTML
/**
* The ruleset for HTML improvement on french typography
*
* It includes rules for:
*
* - Wrapping ends of common abbreviation in a `<sup>` tag so that `Mmes`
* becomes `M<sup>mes</sup>`
* - Wrapping ordinal number suffix in a `<sup>` tag
*
* Finally, the following rulesets are also included:
*
* - {@link src/rules/html.js~htmlRuleset}
*
* @type {Array<Object>}
*/
export default frFR_HTML = createRuleset().concat(html)
function createRuleset () {
return group('fr-FR.html', [
rule('abbrWithSuperText', /Mmes|Mme|Mlles|Mlle|Me|Mgr|Dr|cie|Cie|Sté/, (m) => {
return `${m[0]}<sup>${m.slice(1, m.length)}</sup>`
}),
rule('ordinalNumbers', /(\d)(res|re|es|e|èmes)/, '$1<sup class="ord">$2</sup>')
])
}
|
Set version for 2.0.2 release | # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
__version__ = '2.0.2'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ = 'https://spacy.io'
__author__ = 'Explosion AI'
__email__ = 'contact@explosion.ai'
__license__ = 'MIT'
__release__ = True
__docs_models__ = 'https://spacy.io/usage/models'
__download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
__compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
__shortcuts__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json'
| # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
__version__ = '2.0.2.dev1'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ = 'https://spacy.io'
__author__ = 'Explosion AI'
__email__ = 'contact@explosion.ai'
__license__ = 'MIT'
__release__ = False
__docs_models__ = 'https://spacy.io/usage/models'
__download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
__compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
__shortcuts__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json'
|
Change the position parameter in the constructor | /*
* Copyright (c) 2012 Evolveum
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* http://www.opensource.org/licenses/cddl1 or
* CDDLv1.0.txt file in the source code distribution.
* See the License for the specific language governing
* permission and limitations under the License.
*
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
*
* Portions Copyrighted 2012 [name of copyright owner]
*/
package com.evolveum.midpoint.web.page.admin.configuration.dto;
import java.io.Serializable;
/**
* @author lazyman
*/
public class ObjectViewDto implements Serializable {
private String oid;
private String name;
private String xml;
public ObjectViewDto() {
}
public ObjectViewDto(String oid, String name, String xml) {
this.name = name;
this.oid = oid;
this.xml = xml;
}
public String getName() {
return name;
}
public String getOid() {
return oid;
}
public String getXml() {
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
}
| /*
* Copyright (c) 2012 Evolveum
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* http://www.opensource.org/licenses/cddl1 or
* CDDLv1.0.txt file in the source code distribution.
* See the License for the specific language governing
* permission and limitations under the License.
*
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
*
* Portions Copyrighted 2012 [name of copyright owner]
*/
package com.evolveum.midpoint.web.page.admin.configuration.dto;
import java.io.Serializable;
/**
* @author lazyman
*/
public class ObjectViewDto implements Serializable {
private String oid;
private String name;
private String xml;
public ObjectViewDto() {
}
public ObjectViewDto(String name, String oid, String xml) {
this.name = name;
this.oid = oid;
this.xml = xml;
}
public String getName() {
return name;
}
public String getOid() {
return oid;
}
public String getXml() {
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
}
|
Add fragment class for final date | package de.fau.amos.virtualledger.android.views.savings.add;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.fau.amos.virtualledger.R;
import de.fau.amos.virtualledger.dtos.AddSavingsAccountData;
public class AddSavingsAccountFinalDateFragment extends AddSavingsAccountPage {
@SuppressWarnings("unused")
private static final String TAG = AddSavingsAccountFinalDateFragment.class.getSimpleName();
@BindView(R.id.add_savings_account_date_picker_enter_final_date)
DatePicker datePicker;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.saving_accounts_add_fragment_final_date, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void fillInData(final AddSavingsAccountData addSavingsAccountResult) {
}
}
| package de.fau.amos.virtualledger.android.views.savings.add;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import org.apache.commons.lang3.math.NumberUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.fau.amos.virtualledger.R;
import de.fau.amos.virtualledger.dtos.AddSavingsAccountData;
public class AddSavingsAccountAmountFragment extends AddSavingsAccountPage {
@SuppressWarnings("unused")
private static final String TAG = AddSavingsAccountAmountFragment.class.getSimpleName();
@BindView(R.id.add_savings_account_edit_text_amount)
EditText editText;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.saving_accounts_add_fragment_amount, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void fillInData(final AddSavingsAccountData addSavingsAccountResult) {
addSavingsAccountResult.goalBalance = NumberUtils.toDouble(editText.getText().toString());
}
}
|
Fix tests to match ember-test-helpers 0.3.0. | import { moduleFor, test } from 'ember-qunit';
import { setResolverRegistry } from 'tests/test-support/resolver';
function setupRegistry() {
setResolverRegistry({
'component:x-foo': Ember.Component.extend()
});
}
var callbackOrder, setupContext, teardownContext, beforeSetupContext, afterTeardownContext;
moduleFor('component:x-foo', 'TestModule callbacks', {
beforeSetup: function() {
beforeSetupContext = this;
callbackOrder = [ 'beforeSetup' ];
setupRegistry();
},
setup: function() {
setupContext = this;
callbackOrder.push('setup');
ok(setupContext !== beforeSetupContext);
},
teardown: function() {
teardownContext = this;
callbackOrder.push('teardown');
deepEqual(callbackOrder, [ 'beforeSetup', 'setup', 'teardown']);
equal(setupContext, teardownContext);
},
afterTeardown: function() {
afterTeardownContext = this;
callbackOrder.push('afterTeardown');
deepEqual(callbackOrder, [ 'beforeSetup', 'setup', 'teardown', 'afterTeardown']);
equal(afterTeardownContext, beforeSetupContext);
ok(afterTeardownContext !== teardownContext);
}
});
test("setup callbacks called in the correct order", function() {
deepEqual(callbackOrder, [ 'beforeSetup', 'setup' ]);
});
| import { moduleFor, test } from 'ember-qunit';
import { setResolverRegistry } from 'tests/test-support/resolver';
function setupRegistry() {
setResolverRegistry({
'component:x-foo': Ember.Component.extend()
});
}
var a = 0;
var b = 0;
var beforeSetupOk = false;
var beforeTeardownOk = false;
moduleFor('component:x-foo', 'TestModule callbacks', {
beforeSetup: function() {
setupRegistry();
beforeSetupOk = (a === 0);
b += 1;
},
setup: function() {
a += 1;
},
beforeTeardown: function() {
beforeTeardownOk = (a === 1);
b -= 1;
},
teardown: function() {
a -= 1;
}
});
test("beforeSetup callback is called prior to any test setup", function() {
ok(beforeSetupOk);
equal(b, 1);
});
test("setup callback is called prior to test", function() {
equal(a, 1);
});
test("teardown callback is called after test", function() {
equal(a, 1);
});
test("beforeTeardown callback is called prior to any test teardown", function() {
ok(beforeTeardownOk);
equal(b, 1);
});
|
Add a test for get_available_markups() function | # This file is part of python-markups test suite
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2015
import markups
import unittest
class APITest(unittest.TestCase):
def test_api(self):
all_markups = markups.get_all_markups()
self.assertIn(markups.MarkdownMarkup, all_markups)
self.assertIn(markups.ReStructuredTextMarkup, all_markups)
markup_class = markups.find_markup_class_by_name('restructuredtext')
self.assertEqual(markups.ReStructuredTextMarkup, markup_class)
markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True)
self.assertEqual(markups.MarkdownMarkup, markup_class)
@unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available')
def test_api_instance(self):
markup = markups.get_markup_for_file_name('myfile.mkd')
self.assertIsInstance(markup, markups.MarkdownMarkup)
@unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available')
def test_available_markups(self):
available_markups = markups.get_available_markups()
self.assertIn(markups.MarkdownMarkup, available_markups)
if __name__ == '__main__':
unittest.main()
| # This file is part of python-markups test suite
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2015
import markups
import unittest
class APITest(unittest.TestCase):
def test_api(self):
all_markups = markups.get_all_markups()
self.assertIn(markups.MarkdownMarkup, all_markups)
self.assertIn(markups.ReStructuredTextMarkup, all_markups)
markup_class = markups.find_markup_class_by_name('restructuredtext')
self.assertEqual(markups.ReStructuredTextMarkup, markup_class)
markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True)
self.assertEqual(markups.MarkdownMarkup, markup_class)
@unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available')
def test_api_instance(self):
markup = markups.get_markup_for_file_name('myfile.mkd')
self.assertIsInstance(markup, markups.MarkdownMarkup)
if __name__ == '__main__':
unittest.main()
|
Change "required" field type option (true -> false) | <?php
/**
* ContentType
*/
namespace Wizin\Bundle\SimpleCmsBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ContentType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden');
$builder->add('pathInfo');
$builder->add('title');
$builder->add('parameters', 'collection', ['type' => 'textarea', 'required' => false]);
$builder->add('templateFile', 'text', ['read_only' => true]);
$builder->add('active', 'checkbox', ['required' => false]);
}
/**
* @return string
*/
public function getName()
{
return 'Content';
}
}
| <?php
/**
* ContentType
*/
namespace Wizin\Bundle\SimpleCmsBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ContentType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden');
$builder->add('pathInfo');
$builder->add('title');
$builder->add('parameters', 'collection', ['type' => 'textarea']);
$builder->add('templateFile', 'text', ['read_only' => true]);
$builder->add('active', 'checkbox', ['required' => false]);
}
/**
* @return string
*/
public function getName()
{
return 'Content';
}
}
|
[FIX] portal_sale_distributor: Adjust to avoid bugs with other values in context
closes ingadhoc/sale#493
X-original-commit: 441d30af0c3fa8cbbe129893107436ea69cca740
Signed-off-by: Juan José Scarafía <1d1652a8631a1f5a0ea40ef8dcad76f737ce6379@adhoc.com.ar> | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api
from odoo.tools.safe_eval import safe_eval
class ActWindowView(models.Model):
_inherit = 'ir.actions.act_window'
def read(self, fields=None, load='_classic_read'):
result = super().read(fields, load=load)
for value in result:
if value.get('context') and 'portal_products' in value.get('context'):
eval_ctx = dict(self.env.context)
try:
ctx = safe_eval(value.get('context', '{}'), eval_ctx)
except:
ctx = {}
pricelist = self.env.user.partner_id.property_product_pricelist
ctx.update({'pricelist': pricelist.id, 'partner': self.env.user.partner_id.id})
value.update({'context': str(ctx)})
return result
| ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, api
from odoo.tools.safe_eval import safe_eval
class ActWindowView(models.Model):
_inherit = 'ir.actions.act_window'
def read(self, fields=None, load='_classic_read'):
result = super().read(fields, load=load)
if result and result[0].get('context'):
ctx = safe_eval(result[0].get('context', '{}'))
if ctx.get('portal_products'):
pricelist = self.env.user.partner_id.property_product_pricelist
ctx.update({'pricelist': pricelist.id, 'partner': self.env.user.partner_id})
result[0].update({'context': ctx})
return result
|
BAP-11622: Optimize email body cleanup process | <?php
namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_28;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroEmailBundle implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
static::oroEmailFolderChangeColumn($schema);
}
/**
* @param Schema $schema
*/
public static function oroEmailFolderChangeColumn(Schema $schema)
{
$table = $schema->getTable('oro_email_folder');
if ($table->hasColumn('failed_count')) {
$table->getColumn('failed_count')->setDefault("0");
}
}
}
| <?php
namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_28;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroEmailBundle implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
static::oroEmailFolderChangeColumn($schema);
}
/**
* @param Schema $schema
*/
public static function oroEmailFolderChangeColumn(Schema $schema)
{
$table = $schema->getTable('oro_email_folder');
if ($table->hasColumn('failed_count')) {
$table->getColumn('failed_count')->setDefault("0");
}
}
} |
Make anonymous user distinguishable from Django's AnonymousUser
Django uses a special object---the AnonymousUser---for requests that are not
bound to a logged in user. Since we use guardian we replace this object with an
actual user object (with the ID set in ANONYMOUS_USER_ID, usually -1) in a
middleware class. So far this user had its is_anonymous() function set to return
False. This however imposes a problem if one wants to have permissions for this
users (e.g. testing them with user.has_perm()). As it turns out, permissions are
not checked if is_anonymous() returns True. The Django documentation says this
method is only used to distinguish real user objects from the AnonymousUser
object. Our anonymous user is a real user and therefore this commit changes this
function of the anonymous user to return False. | import json
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.conf import settings
from traceback import format_exc
class AnonymousAuthenticationMiddleware(object):
""" This middleware class tests whether the current user is the
anonymous user. If so, it replaces the request.user object with
Guardian's anonymous user and monkey patchs it to behave like
Django's anonymou user.
"""
def process_request(self, request):
if request.user.is_anonymous() and settings.ANONYMOUS_USER_ID:
request.user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
request.user.is_anonymous = lambda: False
request.user.is_authenticated = lambda: False
return None
class AjaxExceptionMiddleware(object):
def process_exception(self, request, exception):
response = {
'error': str(exception),
'detail': format_exc(),
}
if settings.DEBUG:
import sys, traceback
(exc_type, exc_info, tb) = sys.exc_info()
response['type'] = exc_type.__name__
response['info'] = str(exc_info)
response['traceback'] = ''.join(traceback.format_tb(tb))
return HttpResponse(json.dumps(response))
| import json
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.conf import settings
from traceback import format_exc
class AnonymousAuthenticationMiddleware(object):
""" This middleware class tests whether the current user is the
anonymous user. If so, it replaces the request.user object with
Guardian's anonymous user and monkey patchs it to behave like
Django's anonymou user.
"""
def process_request(self, request):
if request.user.is_anonymous() and settings.ANONYMOUS_USER_ID:
request.user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
request.user.is_anonymous = lambda: True
request.user.is_authenticated = lambda: False
return None
class AjaxExceptionMiddleware(object):
def process_exception(self, request, exception):
response = {
'error': str(exception),
'detail': format_exc(),
}
if settings.DEBUG:
import sys, traceback
(exc_type, exc_info, tb) = sys.exc_info()
response['type'] = exc_type.__name__
response['info'] = str(exc_info)
response['traceback'] = ''.join(traceback.format_tb(tb))
return HttpResponse(json.dumps(response))
|
Implement high def pictures for python tutorials. | #! /usr/bin/env python
import ROOT
import shutil
import os
def makeimage(MacroName, ImageName, OutDir, cp, py, batch):
'''Generates the ImageName output of the macro MacroName'''
ROOT.gStyle.SetImageScaling(3.)
if batch:
ROOT.gROOT.SetBatch(1)
if py: execfile(MacroName)
else: ROOT.gInterpreter.ProcessLine(".x " + MacroName)
if cp:
MN = MacroName.split("(")[0]
MNBase = os.path.basename(MN)
shutil.copyfile("%s" %MN,"%s/macros/%s" %(OutDir,MNBase))
s = open ("ImagesSizes.dat","w")
canvases = ROOT.gROOT.GetListOfCanvases()
for ImageNum,can in enumerate(canvases):
ImageNum += 1
can.SaveAs("%s/html/pict%d_%s" %(OutDir,ImageNum,ImageName))
cw = can.GetWindowWidth()
s.write("%d\n" %cw)
s.close()
f = open ("NumberOfImages.dat","w")
f.write("%d\n" %ImageNum)
f.close()
if __name__ == "__main__":
from sys import argv
makeimage(argv[1], argv[2], argv[3], bool(argv[4]), bool(argv[5]), bool(argv[6])) | #! /usr/bin/env python
import ROOT
import shutil
import os
def makeimage(MacroName, ImageName, OutDir, cp, py, batch):
'''Generates the ImageName output of the macro MacroName'''
if batch:
ROOT.gROOT.SetBatch(1)
if py: execfile(MacroName)
else: ROOT.gInterpreter.ProcessLine(".x " + MacroName)
if cp:
MN = MacroName.split("(")[0]
MNBase = os.path.basename(MN)
shutil.copyfile("%s" %MN,"%s/macros/%s" %(OutDir,MNBase))
canvases = ROOT.gROOT.GetListOfCanvases()
for ImageNum,can in enumerate(canvases):
ImageNum += 1
can.SaveAs("%s/html/pict%d_%s" %(OutDir,ImageNum,ImageName))
f = open ("NumberOfImages.dat","w")
f.write("%d\n" %ImageNum)
f.close()
if __name__ == "__main__":
from sys import argv
makeimage(argv[1], argv[2], argv[3], bool(argv[4]), bool(argv[5]), bool(argv[6])) |
Create angular only when undefined | window.angular = window.angular || {};
window._ngTrace = false;
Object.observe(window.angular, function(changes){
if (!window._ngTrace && enabled()) {
window._ngTrace = true;
inject();
}
});
function enabled() {
return window.sessionStorage.getItem('ng-trace') == 'true';
}
function inject() {
angular.module('ng').config(['$provide', function($provide) {
$provide.decorator('$q', ['$delegate', function($delegate) {
$delegate.when = decorate($delegate);
return $delegate;
}]);
}]);
}
function decorate(q) {
var _when = q.when;
return function(v) {
if (v && v.url && enabled() && !/\.html$/.test(v.url)) {
console.groupCollapsed(v.method, v.url);
console.trace('ng-trace');
console.groupEnd();
}
return _when.apply(this, arguments);
}
}
| window.angular = {};
window._ngTrace = false;
Object.observe(window.angular, function(changes){
if (!window._ngTrace && enabled()) {
window._ngTrace = true;
inject();
}
});
function enabled() {
return window.sessionStorage.getItem('ng-trace') == 'true';
}
function inject() {
angular.module('ng').config(['$provide', function($provide) {
$provide.decorator('$q', ['$delegate', function($delegate) {
$delegate.when = decorate($delegate);
return $delegate;
}]);
}]);
}
function decorate(q) {
var _when = q.when;
return function(v) {
if (v && v.url && enabled() && !/\.html$/.test(v.url)) {
console.groupCollapsed(v.method, v.url);
console.trace('ng-trace');
console.groupEnd();
}
return _when.apply(this, arguments);
}
}
|
Add Log to debug error | /**
* @file This is a tweetable quotes tag plugin for the Hexo static site generator.
* @copyright Chathu Vishwajith 2015-2016
* @author Chathu Vishwajith
* @license MIT
*/
const path = require('path');
const nunjucks = require('nunjucks');
const querystring = require('querystring');
nunjucks.configure(__dirname, {watch: false});
hexo.extend.tag.register('tweetableQuote', function(args) {
let quote = arg[0];
console.log(quote);
let author = arg[1];
console.log(author);
const url = 'https://twitter.com/intent/tweet?text='+querystring.stringify(quote+"-"+author);
const data = {"quote": quote, "author": author,"url":url};
return new Promise(function (resolve, reject) {
nunjucks.render('tweetable-quote.njk', data, function (err, res) {
if (err) {
console.log(err);
return reject(err);
}
resolve(res);
});
});
},{async: true});
| /**
* @file This is a tweetable quotes tag plugin for the Hexo static site generator.
* @copyright Chathu Vishwajith 2015-2016
* @author Chathu Vishwajith
* @license MIT
*/
const path = require('path');
const nunjucks = require('nunjucks');
const querystring = require('querystring');
nunjucks.configure(__dirname, {watch: false});
hexo.extend.tag.register('tweetableQuote', function(args) {
let quote = arg[0];
let author = arg[1];
const url = 'https://twitter.com/intent/tweet?text='+querystring.stringify(quote+"-"+author);
const data = {"quote": quote, "author": author,"url":url};
return new Promise(function (resolve, reject) {
nunjucks.render('tweetable-quote.njk', data, function (err, res) {
if (err) {
return reject(err);
}
resolve(res);
});
});
},{async: true});
|
Correct enum equality for ComprableOperatos (see isComparable() method) | /*
* Copyright 2019 Immutables Authors and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.immutables.criteria.expression;
import java.util.Arrays;
import java.util.Objects;
/**
* List of operator for {@link Comparable}
*/
public enum ComparableOperators implements Operator {
GREATER_THAN(Arity.BINARY),
GREATER_THAN_OR_EQUAL(Arity.BINARY),
LESS_THAN(Arity.BINARY),
LESS_THAN_OR_EQUAL(Arity.BINARY);
private final Arity arity;
ComparableOperators(Arity arity) {
this.arity = arity;
}
@Override
public Arity arity() {
return arity;
}
public static boolean isComparable(Operator operator) {
if (!(operator instanceof ComparableOperators)) {
return false;
}
return Arrays.asList(values()).contains(operator);
}
}
| /*
* Copyright 2019 Immutables Authors and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.immutables.criteria.expression;
import java.util.Arrays;
import java.util.Objects;
/**
* List of operator for {@link Comparable}
*/
public enum ComparableOperators implements Operator {
GREATER_THAN(Arity.BINARY),
GREATER_THAN_OR_EQUAL(Arity.BINARY),
LESS_THAN(Arity.BINARY),
LESS_THAN_OR_EQUAL(Arity.BINARY);
private final Arity arity;
ComparableOperators(Arity arity) {
this.arity = arity;
}
@Override
public Arity arity() {
return arity;
}
public static boolean isComparable(Operator operator) {
Objects.requireNonNull(operator, "operator");
return Arrays.stream(values()).anyMatch(v -> v.name().equals(operator.name()));
}
}
|
Deal with invalid http POST more gracefully. | var http = require('http')
, url = require('url')
, express = require('express')
, rest = express()
, path = require('path')
, server = http.createServer(rest)
, ap = require('argparse').ArgumentParser
, colors = require('colors')
, appium = require('./app/appium')
, parser = require('./app/parser');
rest.configure(function() {
var bodyParser = express.bodyParser()
, parserWrap = function(req, res, next) {
// wd.js sends us http POSTs with empty body which will make bodyParser fail.
if (parseInt(req.get('content-length'), 10) <= 0) {
return next();
}
bodyParser(req, res, next);
};
rest.use(express.favicon());
rest.use(express.static(path.join(__dirname, '/app/static')));
rest.use(express.logger('dev'));
rest.use(parserWrap);
rest.use(express.methodOverride());
rest.use(rest.router);
});
// Parse the command line arguments
var args = parser().parseArgs();
// Instantiate the appium instance
var appium = appium(args.app, args.UDID, args.verbose);
// Hook up REST http interface
appium.attachTo(rest);
// Start the web server that receives all the commands
server.listen(args.port, args.address, function() {
var logMessage = "Appium REST http interface listener started on "+args.address+":"+args.port;
console.log(logMessage.cyan);
});
| var http = require('http')
, url = require('url')
, express = require('express')
, rest = express()
, path = require('path')
, server = http.createServer(rest)
, ap = require('argparse').ArgumentParser
, colors = require('colors')
, appium = require('./app/appium')
, parser = require('./app/parser');
rest.configure(function() {
rest.use(express.favicon());
rest.use(express.static(path.join(__dirname, '/app/static')));
rest.use(express.logger('dev'));
rest.use(express.bodyParser());
rest.use(express.methodOverride());
rest.use(rest.router);
});
// Parse the command line arguments
var args = parser().parseArgs();
// Instantiate the appium instance
var appium = appium(args.app, args.UDID, args.verbose);
// Hook up REST http interface
appium.attachTo(rest);
// Start the web server that receives all the commands
server.listen(args.port, args.address, function() {
var logMessage = "Appium REST http interface listener started on "+args.address+":"+args.port;
console.log(logMessage.cyan);
});
|
Return string from array of macro configuration in applyMacro | const nunjucks = require('nunjucks')
const { assign, omit, isFunction, isArray, map } = require('lodash')
const queryString = require('query-string')
module.exports = {
serviceTitle: 'Data Hub',
projectPhase: 'alpha',
description: 'Data Hub is a customer relationship, project management and analytical tool for Department for International Trade.',
feedbackLink: '/support',
callAsMacro (name) {
const macro = this.ctx[name]
if (!isFunction(macro)) { return }
return macro
},
// Constructs macro from a specially formatted object or array of objects:
// { MacroName: { prop1: 'A', prop2: 'B' } }
applyMacro (config) {
function renderMacro (macroConfig) {
return map(macroConfig, (props, name) => {
const macro = this.env.globals.callAsMacro.call(this, name)
return macro(props)
})[0]
}
if (isArray(config)) {
const macroOutpus = config.map(renderMacro.bind(this))
return new nunjucks.runtime.SafeString(macroOutpus.join('\r'))
}
return renderMacro.call(this, config)
},
buildQuery (query = {}, include = {}, excludeKeys = []) {
return queryString.stringify(
assign(
include,
omit(query, [...excludeKeys], 'page'),
)
)
},
}
| const { assign, omit, isFunction, isArray, map } = require('lodash')
const queryString = require('query-string')
module.exports = {
serviceTitle: 'Data Hub',
projectPhase: 'alpha',
description: 'Data Hub is a customer relationship, project management and analytical tool for Department for International Trade.',
feedbackLink: '/support',
callAsMacro (name) {
const macro = this.ctx[name]
if (!isFunction(macro)) { return }
return macro
},
// Constructs macro from a specially formatted object or array of objects:
// { MacroName: { prop1: 'A', prop2: 'B' } }
applyMacro (config) {
function renderMacro (macroConfig) {
return map(macroConfig, (props, name) => {
const macro = this.env.globals.callAsMacro.call(this, name)
return macro(props)
})[0]
}
if (isArray(config)) {
return config.map(renderMacro.bind(this))
}
return renderMacro.call(this, config)
},
buildQuery (query = {}, include = {}, excludeKeys = []) {
return queryString.stringify(
assign(
include,
omit(query, [...excludeKeys], 'page'),
)
)
},
}
|
Add stats command to help | const Path = require('path')
const action = process.argv[2]
var args = process.argv.slice(3)
var env, bin
switch (action) {
case 'build':
bin = 'webpack'
env = 'production'
break
case 'dist':
case 'stats':
bin = 'webpack'
env = 'production'
args.push('-p')
break
case 'dev':
case 'start':
bin = 'webpack-dev-server'
env = 'development'
args.push('--hot')
break
case '--version':
case '-v':
console.log(require('../package.json').version)
process.exit(1)
return
default:
console.log('missing command: build, dev, dist or stats')
process.exit(1)
}
var cmd = []
if (!process.env.NODE_ENV) {
cmd.push(`NODE_ENV=${env}`) // add NODE_ENV only if not already defined
}
cmd.push(require.resolve(`.bin/${bin}`))
cmd.push('--config')
cmd.push(Path.resolve(__dirname, '../webpackfile.js'))
cmd.push('--progress')
if (action === 'stats') {
cmd.push('--profile', '--json')
} else if (bin === 'webpack') {
cmd.push('--hide-modules') // webpack-dev-server does not have hide-modules
}
cmd.push(...args)
console.log(cmd.join(' '))
| const Path = require('path')
const action = process.argv[2]
var args = process.argv.slice(3)
var env, bin
switch (action) {
case 'build':
bin = 'webpack'
env = 'production'
break
case 'dist':
case 'stats':
bin = 'webpack'
env = 'production'
args.push('-p')
break
case 'dev':
case 'start':
bin = 'webpack-dev-server'
env = 'development'
args.push('--hot')
break
case '--version':
case '-v':
console.log(require('../package.json').version)
process.exit(1)
return
default:
console.log('missing command: build, dev or dist')
process.exit(1)
}
var cmd = []
if (!process.env.NODE_ENV) {
cmd.push(`NODE_ENV=${env}`) // add NODE_ENV only if not already defined
}
cmd.push(require.resolve(`.bin/${bin}`))
cmd.push('--config')
cmd.push(Path.resolve(__dirname, '../webpackfile.js'))
cmd.push('--progress')
if (action === 'stats') {
cmd.push('--profile', '--json')
} else if (bin === 'webpack') {
cmd.push('--hide-modules') // webpack-dev-server does not have hide-modules
}
cmd.push(...args)
console.log(cmd.join(' '))
|
Add 'search' action to action_list | <?php
class ShortenUrlEasily {
public static $action_list = array(
'creativecommons',
'credits',
'delete',
'deletetrackback',
'dublincore',
'edit',
'history',
'info',
'markpatrolled',
'print',
'protect',
'purge',
'raw',
'render',
'revert',
'rollback',
'search',
'submit',
'unprotect',
'unwatch',
'varidate',
'view',
'viewsource',
'watch',
);
public static function init($article = 'wiki', $action = 'w') {
global $wgArticlePath, $wgActionPaths;
$wgArticlePath = "/$article/$1";
foreach(self::$action_list as $a) $wgActionPaths[$a] = "/$action/$a/$1";
}
}
ShortenUrlEasily::init();
| <?php
class ShortenUrlEasily {
public static $action_list = array(
'creativecommons',
'credits',
'delete',
'deletetrackback',
'dublincore',
'edit',
'history',
'info',
'markpatrolled',
'print',
'protect',
'purge',
'raw',
'render',
'revert',
'rollback',
'submit',
'unprotect',
'unwatch',
'varidate',
'view',
'viewsource',
'watch',
);
public static function init($article = 'wiki', $action = 'w') {
global $wgArticlePath, $wgActionPaths;
$wgArticlePath = "/$article/$1";
foreach(self::$action_list as $a) $wgActionPaths[$a] = "/$action/$a/$1";
}
}
ShortenUrlEasily::init();
|
Add new WHOWAS keys when upgrading the data to 0.5 | # This file upgrades data.db from the 0.4 format data to 0.5 format data.
# SETUP: Open data.db
import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
# SECTION: Upgrade whowas time format and add real host and IP keys
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
whowasEntry["realhost"] = whowasEntry["host"]
whowasEntry["ip"] = "0.0.0.0"
# SHUTDOWN: Close data.db
storage.close() | # This file upgrades data.db from the 0.4 format data to 0.5 format data.
# SETUP: Open data.db
import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
# SECTION: Upgrade whowas time format
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
# SHUTDOWN: Close data.db
storage.close() |
Remove reference to Spanish document ID | <?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
*
* @var WC_Aplazame $aplazame
*/
global $aplazame;
if ( ! $aplazame->enabled ) {
return;
}
/**
*
* @var WooCommerce $woocommerce
*/
global $woocommerce;
?>
<p>
Aplaza o fracciona tu compra con <a href="https://aplazame.com" target="_blank">Aplazame</a>.<br>
Obtén financiación al instante sólo con tu Nombre y Apellidos, Teléfono y tarjeta de débito o crédito.<br>
Sin comisiones ocultas ni letra pequeña.<br>
</p>
<script>
(window.aplazame = window.aplazame || []).push(function (aplazame) {
aplazame.button({
selector: <?php echo json_encode( $aplazame->settings['button'] ); ?>,
amount: <?php echo json_encode( Aplazame_Sdk_Serializer_Decimal::fromFloat( $woocommerce->cart->total )->jsonSerialize() ); ?>,
currency: <?php echo json_encode( get_woocommerce_currency() ); ?>
})
})
</script>
| <?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
*
* @var WC_Aplazame $aplazame
*/
global $aplazame;
if ( ! $aplazame->enabled ) {
return;
}
/**
*
* @var WooCommerce $woocommerce
*/
global $woocommerce;
?>
<p>
Aplaza o fracciona tu compra con <a href="https://aplazame.com" target="_blank">Aplazame</a>.<br>
Obtén financiación al instante sólo con tu Nombre y Apellidos, DNI/NIE, Teléfono y tarjeta de débito o crédito.<br>
Sin comisiones ocultas ni letra pequeña.<br>
</p>
<script>
(window.aplazame = window.aplazame || []).push(function (aplazame) {
aplazame.button({
selector: <?php echo json_encode( $aplazame->settings['button'] ); ?>,
amount: <?php echo json_encode( Aplazame_Sdk_Serializer_Decimal::fromFloat( $woocommerce->cart->total )->jsonSerialize() ); ?>,
currency: <?php echo json_encode( get_woocommerce_currency() ); ?>
})
})
</script>
|
Update for M2 after testing. Correction of some bugs in the context tests.
git-svn-id: 959c5dc4f35e0484f067e28fe24ef05c41faf244@773731 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package javax.interceptor;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.annotation.Stereotype;
@Retention(RUNTIME)
@Target({TYPE,METHOD,FIELD})
@Stereotype
@Inherited
public @interface Interceptor
{
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package javax.interceptor;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.annotation.Stereotype;
@Retention(RUNTIME)
@Target(TYPE)
@Stereotype
@Inherited
public @interface Interceptor
{
}
|
Allow adminRole argument; create role if needed | Meteor.methods({
'addFirstUserToAdminRole': function (adminRole) {
/*
Look for existing users and set initial user as admin
*/
// Set default admin role if none provided
var adminRole = adminRole || 'admin';
// Create admin role if not existing
Meteor.call('createRoleIfNotExisting', adminRole);
// Count registered users
var userCount = Meteor.users().count();
// If there is only one user
if (userCount === 1) {
// Get the only user
var user = Meteor.users.findOne();
// Get the user's roles
var userRoles = Roles.getRolesForUser(user);
// Check if current user is admin
var userIsAdmin = _.contains(userRoles, adminRole);
// If user is not admin
if (!userIsAdmin) {
// Add user to admin role
Roles.addUsersToRoles(userId, [adminRole]);
console.log("Added first user as admin.");
} else {
console.log("First user already has admin role.")
}
}
}
});
| Meteor.methods({
'addFirstUserToAdminRole': function () {
/*
Look for existing users and set initial user as admin
*/
// Count registered users
var userCount = Meteor.users().count();
// If there is only one user
if (userCount === 1) {
// Get the only user
var user = Meteor.users.findOne();
// Get the user's roles
var userRoles = Roles.getRolesForUser(user);
// Define the admin role
// TODO: refactor this to take the role name as input parameter
// TODO: create role if it doesnt exist
var adminRole = 'admin';
// Check if current user is admin
var userIsAdmin = _.contains(userRoles, adminRole);
// If user is not admin
if (!userIsAdmin) {
// Add user to admin role
Roles.addUsersToRoles(userId, ['admin']);
console.log("Added first user as admin.");
} else {
console.log("First user already has admin role.")
}
}
}
});
|
Refactor component:
- remove unnecessary use of state;
- create auxiliary variables in the render function. | import React from 'react'
import styles from './event-heading.module.styl'
export default function EventHeading (props) {
const {
event
} = props
const date = new Date(event.date * 1000)
const dateDate = formatDate(date)
const dateTime = formatTime(date)
const eventName = `${event.home} X ${event.away}`
return (
<h4>
<span className={styles.red}>{event.code}</span>
{
` - ${dateDate}, ${dateTime}
- ${eventName}
- ${event.sport}
- ${event.country}
- ${event.competition}`
}
</h4>
)
}
function formatDate (date) {
const now = new Date()
return date.getDate() === now.getDate() ? 'Hoje'
: date.getDate() === (now.getDate() + 1) ? 'Amanhã'
: date.toLocaleDateString()
}
function formatTime (date) {
const time = date.toLocaleTimeString()
// Remove seconds from return string
return time.replace(/:00/, '')
}
| import React from 'react'
import styles from './event-heading.module.styl'
export default class EventHeading extends React.Component {
constructor (props) {
super(props)
const date = new Date(props.event.date * 1000)
this.state = {
dateDate: formatDate(date),
dateTime: formatTime(date),
eventName: `${props.event.home} X ${props.event.away}`
}
}
render () {
const event = this.props.event
return (
<h4>
<span className={styles.red}>{event.code}</span>
{
` - ${this.state.dateDate}, ${this.state.dateTime}
- ${this.state.eventName}
- ${event.sport}
- ${event.country}
- ${event.competition}`
}
</h4>
)
}
}
function formatDate (date) {
const now = new Date()
return date.getDate() === now.getDate() ? 'Hoje'
: date.getDate() === (now.getDate() + 1) ? 'Amanhã'
: date.toLocaleDateString()
}
function formatTime (date) {
const time = date.toLocaleTimeString()
// Remove seconds from return string
return time.replace(/:00/, '')
}
|
Change map emoji to pushpin | var Botkit = require('botkit')
var request = require('request')
var mapsToken = process.env.GOOGLE_MAPS_TOKEN
// Expect a SLACK_TOKEN environment variable
var slackToken = process.env.SLACK_TOKEN
if (!slackToken) {
console.error('SLACK_TOKEN is required!')
process.exit(1)
}
var controller = Botkit.slackbot()
var bot = controller.spawn({
token: slackToken
})
bot.startRTM(function (err, bot, payload) {
if (err) {
throw new Error('Could not connect to Slack')
}
})
controller.hears(['where'], ['direct_message', 'direct_mention'], function (bot, message) {
request('http://tracker.brandonevans.ca/points/latest', function(error, response, body) {
var point = JSON.parse(body);
var prefix = point.inside ? " in " : " near ";
var location = point.name;
var text = 'I\'m' + prefix + location
var imageURL = 'https://maps.googleapis.com/maps/api/staticmap?center=' + encodeURIComponent(location) + '&zoom=6&size=600x300&maptype=roadmap&key=' + mapsToken
var attachments = [{
fallback: text,
pretext: ':round_pushpin: ' + text,
image_url: imageURL
}]
bot.reply(message, {attachments: attachments});
});
})
| var Botkit = require('botkit')
var request = require('request')
var mapsToken = process.env.GOOGLE_MAPS_TOKEN
// Expect a SLACK_TOKEN environment variable
var slackToken = process.env.SLACK_TOKEN
if (!slackToken) {
console.error('SLACK_TOKEN is required!')
process.exit(1)
}
var controller = Botkit.slackbot()
var bot = controller.spawn({
token: slackToken
})
bot.startRTM(function (err, bot, payload) {
if (err) {
throw new Error('Could not connect to Slack')
}
})
controller.hears(['where'], ['direct_message', 'direct_mention'], function (bot, message) {
request('http://tracker.brandonevans.ca/points/latest', function(error, response, body) {
var point = JSON.parse(body);
var prefix = point.inside ? " in " : " near ";
var location = point.name;
var text = 'I\'m' + prefix + location
var imageURL = 'https://maps.googleapis.com/maps/api/staticmap?center=' + encodeURIComponent(location) + '&zoom=6&size=600x300&maptype=roadmap&key=' + mapsToken
var attachments = [{
fallback: text,
pretext: ':world_map: ' + text,
image_url: imageURL
}]
bot.reply(message, {attachments: attachments});
});
})
|
Expand the article content in full view mode | /*jslint browser:true */
function decorate() {
"use strict";
var ad, nav, content, header, body,
navWidth, contentWidth,
cssNode,
MutationObserver, observer;
body = document.body;
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
observer = new MutationObserver(function (mutationRecord, observer) {
mutationRecord.forEach(function (mutation) {
if (body.classList.contains('ready')) {
ad = document.getElementById('reader-ad-container');
nav = document.getElementsByTagName('nav');
content = document.getElementById('reader-container');
header = document.getElementById('feed-details');
nav = nav[0];
navWidth = nav.offsetWidth;
// Hide ads
ad.style.width = 0;
ad.style.display = 'none';
contentWidth = window.innerWidth - navWidth;
cssNode = document.createElement('style');
cssNode.innerHTML = '#reader-container{width:' + contentWidth.toString() + 'px;}' +
'#feed-details{width:' + contentWidth.toString() + 'px;}' +
'.article-item-full .article-content{width:95%;}';
document.body.appendChild(cssNode);
observer.disconnect();
}
});
});
observer.observe(body, {attributes: true});
}
window.onload = decorate;
| /*jslint browser:true */
function decorate() {
"use strict";
var ad, nav, content, header, body,
navWidth, contentWidth,
cssNode,
MutationObserver, observer;
body = document.body;
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
observer = new MutationObserver(function (mutationRecord, observer) {
mutationRecord.forEach(function (mutation) {
if (body.classList.contains('ready')) {
ad = document.getElementById('reader-ad-container');
nav = document.getElementsByTagName('nav');
content = document.getElementById('reader-container');
header = document.getElementById('feed-details');
nav = nav[0];
navWidth = nav.offsetWidth;
// Hide ads
ad.style.width = 0;
ad.style.display = 'none';
contentWidth = window.innerWidth - navWidth;
cssNode = document.createElement('style');
cssNode.innerHTML = '#reader-container{width:' + contentWidth.toString() + 'px;}' +
'#feed-details{width:' + contentWidth.toString() + 'px;}';
document.body.appendChild(cssNode);
observer.disconnect();
}
});
});
observer.observe(body, {attributes: true});
}
window.onload = decorate;
|
Change calculateReserves minimum value to zero | import {
fromPairs,
isEmpty,
head,
last,
max,
mapObjIndexed,
sortBy,
toPairs,
} from 'ramda'
export function calculateReserves (cumulative, reserveData, mineral, column, series) {
const reserves = getReserves(reserveData, mineral)
if (!reserves) {
// console.debug('No reserves!')
return {}
}
const [reserveYear, reserveAmount] = last(sortBy(head, toPairs(reserves)))
const cumulativeOnReserveYear = cumulative.data[reserveYear][column]
return mapObjIndexed((row, year) => {
return fromPairs([
['Year', year],
[series, max(0, reserveAmount - (row[column] - cumulativeOnReserveYear))]
])
}, cumulative.data)
}
export function getReserves (reserves, mineral) {
return reserves.data && reserves.data[mineral]
}
| import {
fromPairs,
isEmpty,
head,
last,
max,
mapObjIndexed,
sortBy,
toPairs,
} from 'ramda'
export function calculateReserves (cumulative, reserveData, mineral, column, series) {
const reserves = getReserves(reserveData, mineral)
if (!reserves) {
// console.debug('No reserves!')
return {}
}
const [reserveYear, reserveAmount] = last(sortBy(head, toPairs(reserves)))
const cumulativeOnReserveYear = cumulative.data[reserveYear][column]
return mapObjIndexed((row, year) => {
return fromPairs([
['Year', year],
[series, max(1, reserveAmount - (row[column] - cumulativeOnReserveYear))]
])
}, cumulative.data)
}
export function getReserves (reserves, mineral) {
return reserves.data && reserves.data[mineral]
}
|
Set current instance as root object
Signed-off-by: Sebastian Hoß <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@shoss.de> | /*
* Copyright © 2012 Sebastian Hoß <mail@shoss.de>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.github.sebhoss.contract.verifier;
import com.github.sebhoss.contract.annotation.SpEL;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
* SpEL-based implementation of the {@link ContractContextFactory}.
*/
@SpEL
public class SpELBasedContractContextFactory implements ContractContextFactory {
@Override
public ContractContext createContext(final Object instance, final Object[] arguments, final String[] parameterNames) {
final ExpressionParser parser = new SpelExpressionParser();
final EvaluationContext context = new StandardEvaluationContext(instance);
for (int index = 0; index < arguments.length; index++) {
context.setVariable(parameterNames[index], arguments[index]);
}
return new SpELContractContext(parser, context);
}
}
| /*
* Copyright © 2012 Sebastian Hoß <mail@shoss.de>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.github.sebhoss.contract.verifier;
import com.github.sebhoss.contract.annotation.Clause;
import com.github.sebhoss.contract.annotation.SpEL;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
* SpEL-based implementation of the {@link ContractContextFactory}.
*/
@SpEL
public class SpELBasedContractContextFactory implements ContractContextFactory {
@Override
public ContractContext createContext(final Object instance, final Object[] arguments, final String[] parameterNames) {
final ExpressionParser parser = new SpelExpressionParser();
final EvaluationContext context = new StandardEvaluationContext();
for (int index = 0; index < arguments.length; index++) {
context.setVariable(parameterNames[index], arguments[index]);
}
context.setVariable(Clause.THIS, instance);
return new SpELContractContext(parser, context);
}
}
|
xkcd: Change name of the template. | function ddg_spice_xkcd_display(api_result) {
if (!api_result.img || !api_result.alt) return;
//calls our endpoint to get the number of the latest comic
$.getJSON('/js/spice/xkcd/latest/', function(data){
//if we are looking at the latest comic, don't display the 'next' link
api_result.has_next = parseInt(data.num) > parseInt(api_result.num);
Spice.render({
data : api_result,
header1 : api_result.safe_title + " (xkcd)",
source_url : 'http://xkcd.com/' + api_result.num,
source_name : 'xkcd',
template_normal : 'xkcd_display',
force_big_header : true,
force_no_fold : true
});
});
}
//gets the number for the previous comic
Handlebars.registerHelper("previousNum", function(num, options) {
if(num > 1) {
return options.fn({num: num - 1});
}
});
//gets the number for the next comic
Handlebars.registerHelper("nextNum", function(num, options) {
return options.fn({num: num + 1});
});
| function ddg_spice_xkcd_display(api_result) {
if (!api_result.img || !api_result.alt) return;
//calls our endpoint to get the number of the latest comic
$.getJSON('/js/spice/xkcd/latest/', function(data){
//if we are looking at the latest comic, don't display the 'next' link
api_result.has_next = parseInt(data.num) > parseInt(api_result.num);
Spice.render({
data : api_result,
header1 : api_result.safe_title + " (xkcd)",
source_url : 'http://xkcd.com/' + api_result.num,
source_name : 'xkcd',
template_normal : 'xkcd',
force_big_header : true,
force_no_fold : true,
});
});
}
//gets the number for the previous comic
Handlebars.registerHelper("previousNum", function(num, options) {
if(num > 1) {
return options.fn({num: num - 1});
}
});
//gets the number for the next comic
Handlebars.registerHelper("nextNum", function(num, options) {
return options.fn({num: num + 1});
});
|
Allow specifying modules to be mocked | from typing import List
from typing import Optional
import sys
from unittest.mock import MagicMock
class MockAnkiModules:
"""
I'd like to get rid of the situation when this is required, but for now this helps with the situation that
anki modules are not available during test runtime.
"""
module_names_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki.decks', 'anki.utils', 'anki.cards', 'anki.models',
'anki.notes', 'aqt', 'aqt.qt', 'aqt.exporting', 'aqt.utils']
def __init__(self, module_names_list: Optional[List[str]] = None):
if module_names_list is None:
module_names_list = self.module_names_list
self.shadowed_modules = {}
for module_name in module_names_list:
self.shadowed_modules[module_name] = sys.modules.get(module_name)
sys.modules[module_name] = MagicMock()
def unmock(self):
for module_name, module in self.shadowed_modules.items():
if module is not None:
sys.modules[module_name] = module
else:
if module_name in sys.modules:
del sys.modules[module_name]
| import sys
from unittest.mock import MagicMock
class MockAnkiModules:
"""
I'd like to get rid of the situation when this is required, but for now this helps with the situation that
anki modules are not available during test runtime.
"""
modules_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki.decks', 'anki.utils', 'anki.cards', 'anki.models',
'anki.notes', 'aqt', 'aqt.qt', 'aqt.exporting', 'aqt.utils']
def __init__(self):
self.shadowed_modules = {}
for module in self.modules_list:
self.shadowed_modules[module] = sys.modules.get(module)
sys.modules[module] = MagicMock()
def unmock(self):
for module in self.modules_list:
shadowed_module = self.shadowed_modules[module]
if shadowed_module is not None:
sys.modules[module] = shadowed_module
else:
if module in sys.modules:
del sys.modules[module]
|
Change asset naming of Webpack | 'use strict';
let webpack = require('webpack');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: [`${__dirname}/src/main.js`],
output: {
path: `${__dirname}/dist`,
publicPath: '/dist/',
filename: 'all.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015']
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css?sourceMap!autoprefixer!sass?sourceMap')
},
{
test: /\.(ttf|eot|svg|woff)(\?[a-z0-9#-]+)?$/,
loader: 'file-loader?name=[name]-[sha512:hash:base64:7].[ext]'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('all.css', {
allChunks: true
})
]
};
| 'use strict';
let webpack = require('webpack');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: [`${__dirname}/src/main.js`],
output: {
path: `${__dirname}/dist`,
publicPath: '/dist/',
filename: 'all.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015']
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css?sourceMap!autoprefixer!sass?sourceMap')
},
{
test: /\.(ttf|eot|svg|woff)(\?[a-z0-9#-]+)?$/,
loader: 'file-loader'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('all.css', {
allChunks: true
})
]
};
|
Use a constant for URL
Additionally, added a comment about why it is using 2016 | /* eslint new-cap: [2, {capIsNewExceptions: ["Given", "When", "Then"]}]*/
/**
* Holds steps related to the events feature.
* @module website/events
*/
import {Given, When, Then} from 'cypress-cucumber-preprocessor/steps';
/**
* The URL for the events page.
* @private
*/
const EVENTS_PAGE = 'website/event/';
/**
* A step to navigate to the events page.
* @example
* Given I navigate to the events page
*/
const navigateToEventsPage = () => {
// using 2016 since guaranteed about its events
cy.visit({url: EVENTS_PAGE + 2016, method: 'GET'});
};
Given(`I navigate to the events page`, navigateToEventsPage);
/**
* A step to view a given event.
* @param {string} event - the name of event to view
* @example
* When viewing the event "Mystery Bus"
*/
const viewGivenEvent = (event) => {
cy.get('a').contains(event).click();
};
When(`viewing the event {string}`, viewGivenEvent);
/**
* A step to assert the event contains the given details.
* @param {string} expectedDetails - the expected details of the event
* @example
* Then I see details relating to "school buses"
*/
const assertEventDetails = (expectedDetails) => {
cy.get('p').contains(expectedDetails).should('be.visible');
};
Then(`I see details relating to {string}`, assertEventDetails);
| /* eslint new-cap: [2, {capIsNewExceptions: ["Given", "When", "Then"]}]*/
/**
* Holds steps related to the events feature.
* @module website/events
*/
import {Given, When, Then} from 'cypress-cucumber-preprocessor/steps';
/**
* A step to navigate to the events page.
* @example
* Given I navigate to the events page
*/
const navigateToEventsPage = () => {
cy.visit({url: 'website/event/2016', method: 'GET'});
};
Given(`I navigate to the events page`, navigateToEventsPage);
/**
* A step to view a given event.
* @param {string} event - the name of event to view
* @example
* When viewing the event "Mystery Bus"
*/
const viewGivenEvent = (event) => {
cy.get('a').contains(event).click();
};
When(`viewing the event {string}`, viewGivenEvent);
/**
* A step to assert the event contains the given details.
* @param {string} expectedDetails - the expected details of the event
* @example
* Then I see details relating to "school buses"
*/
const assertEventDetails = (expectedDetails) => {
cy.get('p').contains(expectedDetails).should('be.visible');
};
Then(`I see details relating to {string}`, assertEventDetails);
|
Make fix to use process.env as a global variable and not process.env.KEY | const dotenv = require('dotenv-safe');
const fs = require('fs');
const DefinePlugin = require('webpack').DefinePlugin;
module.exports = DotenvPlugin;
function DotenvPlugin(options) {
options = options || {};
if (!options.sample) options.sample = './.env.default';
if (!options.path) options.path = './.env';
dotenv.config(options);
this.example = dotenv.parse(fs.readFileSync(options.sample));
this.env = dotenv.parse(fs.readFileSync(options.path));
}
DotenvPlugin.prototype.apply = function(compiler) {
const definitions = Object.keys(this.example).reduce((definitions, key) => {
const existing = process.env[key];
if (existing) {
definitions[key] = JSON.stringify(existing);
return definitions;
}
const value = this.env[key];
if (value) definitions[key] = JSON.stringify(value);
return definitions;
}, {});
const plugin = {
'process.env': definitions,
};
compiler.apply(new DefinePlugin(plugin));
};
| const dotenv = require('dotenv-safe');
const fs = require('fs');
const DefinePlugin = require('webpack').DefinePlugin;
module.exports = DotenvPlugin;
function DotenvPlugin(options) {
options = options || {};
if (!options.sample) options.sample = './.env.default';
if (!options.path) options.path = './.env';
dotenv.config(options);
this.example = dotenv.parse(fs.readFileSync(options.sample));
this.env = dotenv.parse(fs.readFileSync(options.path));
}
DotenvPlugin.prototype.apply = function(compiler) {
const plugin = Object.keys(this.example).reduce((definitions, key) => {
const existing = process.env[key];
if (existing) {
definitions[`process.env.${key}`] = JSON.stringify(existing);
return definitions;
}
const value = this.env[key];
if (value) definitions[`process.env.${key}`] = JSON.stringify(value);
return definitions;
}, {});
compiler.apply(new DefinePlugin(plugin));
};
|
Media: Use time duration of test to measure the success
Signed-off-by: Vaibhav Singh <c267fbcdc94c01eb807238c388b92f321583d99b@samsung.com> | /* Global Includes */
var testCase = require('mocha').describe;
var pre = require('mocha').before;
var preEach = require('mocha').beforeEach;
var post = require('mocha').after;
var postEach = require('mocha').afterEach;
var assertions = require('mocha').it;
var assert = require('chai').assert;
var validator = require('validator');
var exec = require('child_process').execSync;
var artik = require('../lib/artik-sdk');
/* Test Specific Includes */
var media = artik.media();
var sound_file = '/usr/share/sounds/alsa/Front_Center.wav';
var start, end;
/* Test Case Module */
testCase('Media', function() {
pre(function() {
});
testCase('#play_sound_file', function() {
this.timeout(5000);
start = new Date();
assertions('Play the sound file', function(done) {
media.play_sound_file(sound_file, function(response, status) {
end = new Date();
var timeOfPlay = (end.getTime() - start.getTime())/1000;
console.log('Finished playing. Seconds ' + timeOfPlay);
assert.isAtLeast(timeOfPlay, 1);
done();
});
});
});
post(function() {
});
});
| /* Global Includes */
var testCase = require('mocha').describe;
var pre = require('mocha').before;
var preEach = require('mocha').beforeEach;
var post = require('mocha').after;
var postEach = require('mocha').afterEach;
var assertions = require('mocha').it;
var assert = require('chai').assert;
var validator = require('validator');
var exec = require('child_process').execSync;
var artik = require('../lib/artik-sdk');
/* Test Specific Includes */
var media = artik.media();
var sound_file = '/usr/share/sounds/alsa/Front_Center.wav';
/* Test Case Module */
testCase('Media', function() {
pre(function() {
});
testCase('#play_sound_file', function() {
assertions('Play the sound file', function() {
media.play_sound_file(sound_file, function(response, status) {
console.log('Finished playing');
});
});
});
post(function() {
});
});
|
Add more thorough testing of day of week. | from datetime import datetime, timedelta
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
now = datetime(2015, 6, 20, 16, 7)
for i in range(0, 7):
# Test day matching from Sunday onwards...
now += timedelta(days=1)
assert pycron.is_now('* * * * %i' % (i), now)
# Test weekdays
assert pycron.is_now('* * * * 1,2,3,4,5', now) is (True if i not in [0, 6] else False)
# Test weekends
assert pycron.is_now('* * * * 0,6', now) is (True if i in [0, 6] else False)
| from datetime import datetime
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
now = datetime(2015, 6, 21, 16, 7)
assert pycron.is_now('* * * * 0', now)
|
Change sitemap.db path to module root | 'use strict';
var fs = require('fs');
var Promise = require('es6-promise').Promise;
var sqlite3 = require('sqlite3');
var file = __dirname + '/../sitemap.db';
var dbExists = fs.existsSync(file);
var db = new sqlite3.Database(file);
module.exports = {
initialize: function () {
db.serialize(function() {
if (!dbExists) {
db.exec('CREATE TABLE Urls (url TEXT UNIQUE, lastmod TEXT)');
}
});
},
get: function (url) {
return new Promise(function (resolve, reject) {
db.get('SELECT * FROM Urls WHERE url="' + url + '";', function (err, row) {
resolve(row);
});
});
},
update: function (url, lastMod) {
return new Promise(function (resolve, reject) {
// add or update
var sqlStatement = 'INSERT OR IGNORE INTO Urls (url, lastmod) VALUES("' + url + '", "' + lastMod + '");' +
'UPDATE Urls SET lastmod = "' + lastMod + '" WHERE url="' + url+ '";';
db.exec(sqlStatement, resolve);
});
},
};
| 'use strict';
var fs = require('fs');
var Promise = require('es6-promise').Promise;
var sqlite3 = require('sqlite3');
var file = 'sitemap.db';
var dbExists = fs.existsSync(file);
var db = new sqlite3.Database(file);
module.exports = {
initialize: function () {
db.serialize(function() {
if (!dbExists) {
db.exec('CREATE TABLE Urls (url TEXT UNIQUE, lastmod TEXT)');
}
});
},
get: function (url) {
return new Promise(function (resolve, reject) {
db.get('SELECT * FROM Urls WHERE url="' + url + '";', function (err, row) {
resolve(row);
});
});
},
update: function (url, lastMod) {
return new Promise(function (resolve, reject) {
// add or update
var sqlStatement = 'INSERT OR IGNORE INTO Urls (url, lastmod) VALUES("' + url + '", "' + lastMod + '");' +
'UPDATE Urls SET lastmod = "' + lastMod + '" WHERE url="' + url+ '";';
db.exec(sqlStatement, resolve);
});
},
};
|
[Build] Write source maps out to a separate directory
Rather than inlining them, write them to build/sourcemaps | var gulp = require('gulp');
var babel = require('gulp-babel');
var coffee = require('gulp-coffee');
var sourcemaps = require('gulp-sourcemaps');
var paths = {
dest: 'build',
sourceMaps: 'sourcemaps',
};
gulp.task('babel', function() {
return gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel({
stage: 1,
blacklist: [
'es6.constants',
'es6.forOf',
'es6.spec.symbols',
'es6.spec.templateLiterals',
'es6.templateLiterals',
],
optional: [
'asyncToGenerator',
'runtime',
],
}))
.pipe(sourcemaps.write(paths.sourceMaps))
.pipe(gulp.dest(paths.dest));
});
gulp.task('coffee', function() {
return gulp.src('src/**/*.coffee')
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
.pipe(sourcemaps.write(paths.sourceMaps))
.pipe(gulp.dest(paths.dest));
});
gulp.task('default', ['babel', 'coffee']);
| var gulp = require('gulp');
var babel = require('gulp-babel');
var coffee = require('gulp-coffee');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('babel', function() {
return gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel({
stage: 1,
blacklist: [
'es6.constants',
'es6.forOf',
'es6.spec.symbols',
'es6.spec.templateLiterals',
'es6.templateLiterals',
],
optional: [
'asyncToGenerator',
'runtime',
],
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('build'));
});
gulp.task('coffee', function() {
return gulp.src('src/**/*.coffee')
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('build'));
});
gulp.task('default', ['babel', 'coffee']);
|
Include *.txt in package data, since lithium.contact has a txt template | #!/usr/bin/env python
from distutils.core import setup
import lithium
packages = ['lithium',]
core = ['conf', 'views',]
apps = ['blog', 'contact',]
templatetags = ['blog',]
package_data = {}
for item in templatetags:
packages.append('lithium.%s.templatetags' % item)
for item in apps + core + templatetags:
packages.append('lithium.%s' % item)
for app in apps:
package_data['lithium.%s' % app] = ['templates/%s/*.html' % app, 'templates/%s/*.txt' % app]
setup(
name='lithium',
version='%s' % lithium.__version__,
description="A set of applications for writing a Django website's, it includes a blog, a forum, and many other useful applications.",
author='Kyle Fuller',
author_email='inbox@kylefuller.co.uk',
url='http://github.com/kylef/lithium/',
download_url='http://github.com/kylef/lithium/zipball/%s' % lithium.__version__,
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
| #!/usr/bin/env python
from distutils.core import setup
import lithium
packages = ['lithium',]
core = ['conf', 'views',]
apps = ['blog', 'contact',]
templatetags = ['blog',]
package_data = {}
for item in templatetags:
packages.append('lithium.%s.templatetags' % item)
for item in apps + core + templatetags:
packages.append('lithium.%s' % item)
for app in apps:
package_data['lithium.%s' % app] = [('templates/%s/*.html' % app),]
setup(
name='lithium',
version='%s' % lithium.__version__,
description="A set of applications for writing a Django website's, it includes a blog, a forum, and many other useful applications.",
author='Kyle Fuller',
author_email='inbox@kylefuller.co.uk',
url='http://github.com/kylef/lithium/',
download_url='http://github.com/kylef/lithium/zipball/%s' % lithium.__version__,
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
Use dummy Message object to be compatible with new ApiDifference API | package net.sf.clirr.ant;
import junit.framework.TestCase;
import net.sf.clirr.event.ApiDifference;
import net.sf.clirr.event.Severity;
import net.sf.clirr.event.Message;
public class ChangeCounterTest extends TestCase
{
public void testCorrectCounting()
{
// a dummy message object
Message msg = new Message(0, false);
ChangeCounter counter = new ChangeCounter();
counter.reportDiff(new ApiDifference(msg, Severity.WARNING, "Test", null, null, null));
counter.reportDiff(new ApiDifference(msg, Severity.ERROR, "Test", null, null, null));
counter.reportDiff(new ApiDifference(msg, Severity.INFO, "Test", null, null, null));
counter.reportDiff(new ApiDifference(msg, Severity.ERROR, "Test", null, null, null));
counter.reportDiff(new ApiDifference(msg, Severity.ERROR, "Test", null, null, null));
counter.reportDiff(new ApiDifference(msg, Severity.WARNING, "Test", null, null, null));
assertEquals("number of expected errors", 3, counter.getBinErrors());
assertEquals("number of expected warnings", 2, counter.getBinWarnings());
assertEquals("number of expected infos", 1, counter.getBinInfos());
}
} | package net.sf.clirr.ant;
import junit.framework.TestCase;
import net.sf.clirr.event.ApiDifference;
import net.sf.clirr.event.Severity;
public class ChangeCounterTest extends TestCase
{
public void testCorrectCounting()
{
ChangeCounter counter = new ChangeCounter();
counter.reportDiff(new ApiDifference("blah", Severity.WARNING, "Test", null, null));
counter.reportDiff(new ApiDifference("blah", Severity.ERROR, "Test", null, null));
counter.reportDiff(new ApiDifference("blah", Severity.INFO, "Test", null, null));
counter.reportDiff(new ApiDifference("blah", Severity.ERROR, "Test", null, null));
counter.reportDiff(new ApiDifference("blah", Severity.ERROR, "Test", null, null));
counter.reportDiff(new ApiDifference("blah", Severity.WARNING, "Test", null, null));
assertEquals("number of expected errors", 3, counter.getBinErrors());
assertEquals("number of expected warnings", 2, counter.getBinWarnings());
assertEquals("number of expected infos", 1, counter.getBinInfos());
}
} |
Fix 'cache' variable doc comment
The comment referenced a non-existing function from during the
development; the affected sentence is removed. | /*jshint node: true */
var Promise = require("bluebird");
var fs = require("fs");
/**
* Maps file paths to their contents
*/
var cache = {};
/**
* Reads the template file at the given path and returns its contents as a
* Promise. The second parameter is optional; if it is set to true, the string
* that was read will not be cached for another access in the future.
*/
module.exports = function load(path, disableCache) {
var prom;
if (!disableCache && cache[path]) {
// load from cache
prom = Promise.resolve(cache[path]);
} else {
// read file
prom = read(path);
}
if (!disableCache) {
// store in cache
prom = prom.then(function (template) {
cache[path] = template;
return template;
});
}
return prom;
};
/**
* Reads the file at the given path and returns its contents as a string.
*/
function read(path) {
return new Promise(function (fulfill, reject) {
fs.readFile(path, "utf8", function (err, template) {
if (err) reject(err);
else fulfill(template);
});
});
}
| /*jshint node: true */
var Promise = require("bluebird");
var fs = require("fs");
/**
* Maps file paths to their contents. Filled in by readTemplate() if the
* disableCache argument is not set to true.
*/
var cache = {};
/**
* Reads the template file at the given path and returns its contents as a
* Promise. The second parameter is optional; if it is set to true, the string
* that was read will not be cached for another access in the future.
*/
module.exports = function load(path, disableCache) {
var prom;
if (!disableCache && cache[path]) {
// load from cache
prom = Promise.resolve(cache[path]);
} else {
// read file
prom = read(path);
}
if (!disableCache) {
// store in cache
prom = prom.then(function (template) {
cache[path] = template;
return template;
});
}
return prom;
};
/**
* Reads the file at the given path and returns its contents as a string.
*/
function read(path) {
return new Promise(function (fulfill, reject) {
fs.readFile(path, "utf8", function (err, template) {
if (err) reject(err);
else fulfill(template);
});
});
}
|
Add tests for loading binaries with malformed sections | import nose
import StringIO
import os
import cle
tests_path = os.path.join(os.path.dirname(__file__), '..', '..', 'binaries', 'tests')
def test_patched_stream():
stream = StringIO.StringIO('0123456789abcdef')
stream1 = cle.PatchedStream(stream, [(2, 'AA')])
stream1.seek(0)
nose.tools.assert_equal(stream1.read(), '01AA456789abcdef')
stream2 = cle.PatchedStream(stream, [(2, 'AA')])
stream2.seek(0)
nose.tools.assert_equal(stream2.read(3), '01A')
stream3 = cle.PatchedStream(stream, [(2, 'AA')])
stream3.seek(3)
nose.tools.assert_equal(stream3.read(3), 'A45')
stream4 = cle.PatchedStream(stream, [(-1, 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')])
stream4.seek(0)
nose.tools.assert_equal(stream4.read(), 'A'*0x10)
def test_malformed_sections():
ld = cle.Loader(os.path.join(tests_path, 'i386', 'oxfoo1m3'))
nose.tools.assert_equal(len(ld.main_object.segments), 1)
nose.tools.assert_equal(len(ld.main_object.sections), 0)
| import nose
import StringIO
import cle
def test_patched_stream():
stream = StringIO.StringIO('0123456789abcdef')
stream1 = cle.PatchedStream(stream, [(2, 'AA')])
stream1.seek(0)
nose.tools.assert_equal(stream1.read(), '01AA456789abcdef')
stream2 = cle.PatchedStream(stream, [(2, 'AA')])
stream2.seek(0)
nose.tools.assert_equal(stream2.read(3), '01A')
stream3 = cle.PatchedStream(stream, [(2, 'AA')])
stream3.seek(3)
nose.tools.assert_equal(stream3.read(3), 'A45')
stream4 = cle.PatchedStream(stream, [(-1, 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')])
stream4.seek(0)
nose.tools.assert_equal(stream4.read(), 'A'*0x10)
|
Disable routes require when command is 'init' | import path from "path";
import chalk from "chalk";
import mergeOptions from "./mergeOptions"
import findOptionsInFiles from "./findOptionsInFiles"
import defaultOptions from "./defaultOptions"
import ConfigurationError from "./ConfigurationError"
/* eslint-disable consistent-return */
export default function run(options = {}) {
// for the option properties that weren't sent in, look for a config file
// (either .reactserverrc or a reactServer section in a package.json). for
// options neither passed in nor in a config file, use the defaults.
options = mergeOptions(defaultOptions, findOptionsInFiles() || {}, options);
const {
routesFile,
jsUrl,
jsPort,
host,
httpsOptions,
} = options;
options.routesPath = path.resolve(process.cwd(), routesFile);
options.routesDir = path.dirname(options.routesPath);
if (options.command !== 'init') options.routes = require(options.routesPath);
options.outputUrl = jsUrl || `${httpsOptions ? "https" : "http"}://${host}:${jsPort}/`;
try {
return require("./" + path.join("commands", options.command))(options);
} catch (e) {
if (e instanceof ConfigurationError) {
console.error(chalk.red(e.message));
} else {
throw e;
}
}
}
| import path from "path";
import chalk from "chalk";
import mergeOptions from "./mergeOptions"
import findOptionsInFiles from "./findOptionsInFiles"
import defaultOptions from "./defaultOptions"
import ConfigurationError from "./ConfigurationError"
/* eslint-disable consistent-return */
export default function run(options = {}) {
// for the option properties that weren't sent in, look for a config file
// (either .reactserverrc or a reactServer section in a package.json). for
// options neither passed in nor in a config file, use the defaults.
options = mergeOptions(defaultOptions, findOptionsInFiles() || {}, options);
const {
routesFile,
jsUrl,
jsPort,
host,
httpsOptions,
} = options;
options.routesPath = path.resolve(process.cwd(), routesFile);
options.routesDir = path.dirname(options.routesPath);
options.routes = require(options.routesPath);
options.outputUrl = jsUrl || `${httpsOptions ? "https" : "http"}://${host}:${jsPort}/`;
try {
return require("./" + path.join("commands", options.command))(options);
} catch (e) {
if (e instanceof ConfigurationError) {
console.error(chalk.red(e.message));
} else {
throw e;
}
}
}
|
Make sure function runs even if one of the promise fails | $(document).ready(function () {
let zone;
let district;
let getZone = $.get('/inputs/geojson/zone', function (data) {
zone = data;
});
let getDistrict = $.get('/inputs/geojson/district', function (data) {
district = data;
});
$.when(getZone, getDistrict).always(function () {
let map = new MapClass('map-div');
map.init({
data:{
zone: zone,
district: district
},
extrude: true
});
});
});
| $(document).ready(function () {
let zone;
let district;
let getZone = $.get('/inputs/geojson/zone', function (data) {
zone = data;
});
let getDistrict = $.get('/inputs/geojson/district', function (data) {
district = data;
});
$.when(getZone, getDistrict).done(function () {
let map = new MapClass('map-div');
map.init({
data:{
zone: zone,
district: district
},
extrude: true
});
});
});
|
Add a test for using card docstrings as names | from hearthstone.enums import CardType, GameTag, Rarity
import utils
CARDS = utils.fireplace.cards.db
def test_all_tags_known():
"""
Iterate through the card database and check that all specified GameTags
are known in hearthstone.enums.GameTag
"""
unknown_tags = set()
known_tags = list(GameTag)
known_rarities = list(Rarity)
# Check the db loaded correctly
assert utils.fireplace.cards.db
for card in CARDS.values():
for tag in card.tags:
# We have fake tags in fireplace.enums which are always negative
if tag not in known_tags and tag > 0:
unknown_tags.add(tag)
# Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...)
assert card.rarity in known_rarities
assert not unknown_tags
def test_play_scripts():
for card in CARDS.values():
if card.scripts.activate:
assert card.type == CardType.HERO_POWER
elif card.scripts.play:
assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
def test_card_docstrings():
for card in CARDS.values():
c = utils.fireplace.utils.get_script_definition(card.id)
name = c.__doc__
if name is not None:
if name.endswith(")"):
continue
assert name == card.name
| from hearthstone.enums import CardType, GameTag, Rarity
import utils
CARDS = utils.fireplace.cards.db
def test_all_tags_known():
"""
Iterate through the card database and check that all specified GameTags
are known in hearthstone.enums.GameTag
"""
unknown_tags = set()
known_tags = list(GameTag)
known_rarities = list(Rarity)
# Check the db loaded correctly
assert utils.fireplace.cards.db
for card in CARDS.values():
for tag in card.tags:
# We have fake tags in fireplace.enums which are always negative
if tag not in known_tags and tag > 0:
unknown_tags.add(tag)
# Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...)
assert card.rarity in known_rarities
assert not unknown_tags
def test_play_scripts():
for card in CARDS.values():
if card.scripts.activate:
assert card.type == CardType.HERO_POWER
elif card.scripts.play:
assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
|
Add django-zero-downtime-migrations Postgres DB engine
From the repo:
https://github.com/tbicr/django-pg-zero-downtime-migrations | # -*- coding: utf-8 -*-
import os
from django.conf import settings
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
REPLACEMENTS = getattr(settings, 'EXTENSIONS_REPLACEMENTS', {})
DEFAULT_SQLITE_ENGINES = (
'django.db.backends.sqlite3',
'django.db.backends.spatialite',
)
DEFAULT_MYSQL_ENGINES = (
'django.db.backends.mysql',
'django.contrib.gis.db.backends.mysql',
'mysql.connector.django',
)
DEFAULT_POSTGRESQL_ENGINES = (
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
'django.db.backends.postgis',
'django.contrib.gis.db.backends.postgis',
'psqlextra.backend',
'django_zero_downtime_migrations.backends.postgres',
'django_zero_downtime_migrations.backends.postgis',
)
SQLITE_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_SQLITE_ENGINES', DEFAULT_SQLITE_ENGINES)
MYSQL_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_MYSQL_ENGINES', DEFAULT_MYSQL_ENGINES)
POSTGRESQL_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_POSTGRESQL_ENGINES', DEFAULT_POSTGRESQL_ENGINES)
| # -*- coding: utf-8 -*-
import os
from django.conf import settings
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
REPLACEMENTS = getattr(settings, 'EXTENSIONS_REPLACEMENTS', {})
DEFAULT_SQLITE_ENGINES = (
'django.db.backends.sqlite3',
'django.db.backends.spatialite',
)
DEFAULT_MYSQL_ENGINES = (
'django.db.backends.mysql',
'django.contrib.gis.db.backends.mysql',
'mysql.connector.django',
)
DEFAULT_POSTGRESQL_ENGINES = (
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
'django.db.backends.postgis',
'django.contrib.gis.db.backends.postgis',
'psqlextra.backend',
)
SQLITE_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_SQLITE_ENGINES', DEFAULT_SQLITE_ENGINES)
MYSQL_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_MYSQL_ENGINES', DEFAULT_MYSQL_ENGINES)
POSTGRESQL_ENGINES = getattr(settings, 'DJANGO_EXTENSIONS_RESET_DB_POSTGRESQL_ENGINES', DEFAULT_POSTGRESQL_ENGINES)
|
Add blank line before return statements. | <?php
namespace Github\Api;
/**
* Get rate limits
*
* @link https://developer.github.com/v3/rate_limit/
* @author Jeff Finley <quickliketurtle@gmail.com>
*/
class RateLimit extends AbstractApi
{
/**
* Get rate limits
*
* @return array
*/
public function getRateLimits()
{
return $this->get('rate_limit');
}
/**
* Get core rate limit
*
* @return integer
*/
public function getCoreLimit()
{
$response = $this->getRateLimits();
return $response['resources']['core']['limit'];
}
/**
* Get search rate limit
*
* @return integer
*/
public function getSearchLimit()
{
$response = $this->getRateLimits();
return $response['resources']['search']['limit'];
}
}
| <?php
namespace Github\Api;
/**
* Get rate limits
*
* @link https://developer.github.com/v3/rate_limit/
* @author Jeff Finley <quickliketurtle@gmail.com>
*/
class RateLimit extends AbstractApi
{
/**
* Get rate limits
*
* @return array
*/
public function getRateLimits()
{
return $this->get('rate_limit');
}
/**
* Get core rate limit
*
* @return integer
*/
public function getCoreLimit()
{
$response = $this->getRateLimits();
return $response['resources']['core']['limit'];
}
/**
* Get search rate limit
*
* @return integer
*/
public function getSearchLimit()
{
$response = $this->getRateLimits();
return $response['resources']['search']['limit'];
}
}
|
Include popper.js and tooltip.js sourcemaps
Fixes #226 | 'use strict';
module.exports = {
name: 'ember-tooltips',
options: {
nodeAssets: {
'popper.js': {
vendor: {
srcDir: 'dist/umd',
destDir: 'popper',
include: ['popper.js', 'popper.js.map'],
},
},
'tooltip.js': {
vendor: {
srcDir: 'dist/umd',
destDir: 'popper',
include: ['tooltip.js', 'tooltip.js.map'],
},
},
},
},
included: function(app) {
this._super.included(app);
app.import('vendor/popper/popper.js');
app.import('vendor/popper/tooltip.js');
},
};
| 'use strict';
module.exports = {
name: 'ember-tooltips',
options: {
nodeAssets: {
'popper.js': {
vendor: {
srcDir: 'dist/umd',
destDir: 'popper',
include: ['popper.js'],
},
},
'tooltip.js': {
vendor: {
srcDir: 'dist/umd',
destDir: 'popper',
include: ['tooltip.js'],
},
},
},
},
included: function(app) {
this._super.included(app);
app.import('vendor/popper/popper.js');
app.import('vendor/popper/tooltip.js');
},
};
|
Change variable from snake_case to camelCase.
Signed-off-by: Kristján Oddsson <7f4038d71424a99d2ff6bb9f6d45a8ec0dfda48e@gmail.com> | var React = require('react/addons');
var ContainerListItem = require('./ContainerListItem.react');
var ContainerListNewItem = require('./ContainerListNewItem.react');
var ContainerList = React.createClass({
componentWillMount: function () {
this._start = Date.now();
},
render: function () {
var self = this;
var containers = this.props.containers.map(function (container) {
var containerId = container.Id;
if (!containerId && container.State.Downloading) {
// Fall back to the container image name when there is no id. (when the
// image is downloading).
containerId = container.Image;
}
return (
<ContainerListItem key={containerId} container={container} start={self._start} />
);
});
var newItem;
if (!this.props.downloading) {
newItem = <ContainerListNewItem key={'newcontainer'} containers={this.props.containers} />;
} else {
newItem = '';
}
return (
<ul>
{newItem}
{containers}
</ul>
);
}
});
module.exports = ContainerList;
| var React = require('react/addons');
var ContainerListItem = require('./ContainerListItem.react');
var ContainerListNewItem = require('./ContainerListNewItem.react');
var ContainerList = React.createClass({
componentWillMount: function () {
this._start = Date.now();
},
render: function () {
var self = this;
var containers = this.props.containers.map(function (container) {
var container_id = container.Id;
if (!container_id && container.State.Downloading) {
// Fall back to the container image name when there is no id. (when the
// image is downloading).
container_id = container.Image;
}
return (
<ContainerListItem key={container_id} container={container} start={self._start} />
);
});
var newItem;
if (!this.props.downloading) {
newItem = <ContainerListNewItem key={'newcontainer'} containers={this.props.containers} />;
} else {
newItem = '';
}
return (
<ul>
{newItem}
{containers}
</ul>
);
}
});
module.exports = ContainerList;
|
Handle missing and invalid email addresses. | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from post_office import mail
class Command(BaseCommand):
help = "Notify users to update."
def handle(self, *args, **options):
domain = Site.objects.get_current().domain
full_url = "https://{}{}".format(domain,
reverse('edit_common_profile'))
for user in User.objects.filter(common_profile__is_student=True,
is_active=True).exclude(email=""):
try:
mail.send([user.email],
template="update_common_profile",
context={'user': user, 'full_url': full_url})
self.stdout.write(u'Emailed {}.'.format(user.email))
except ValidationError:
self.stdout.write(u'Error with {}'.format(user.email))
| from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from post_office import mail
class Command(BaseCommand):
help = "Notify users to update."
def handle(self, *args, **options):
domain = Site.objects.get_current().domain
full_url = "https://{}{}".format(domain,
reverse('edit_common_profile'))
for user in User.objects.filter(common_profile__is_student=True,
is_active=True):
mail.send([user.email],
template="update_common_profile",
context={'user': user, 'full_url': full_url})
self.stdout.write(u'Emailed {}.'.format(user.email))
|
Add support check for hrefNormalized IE bug | var div = require('./div'),
a = div.getElementsByTagName('a')[0];
module.exports = {
classList: !!div.classList,
currentStyle: !!div.currentStyle,
matchesSelector: div.matches ||
div.matchesSelector ||
div.msMatchesSelector ||
div.mozMatchesSelector ||
div.webkitMatchesSelector ||
div.oMatchesSelector,
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: (/^0.55$/).test(div.style.opacity),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute('href') === '/a'
}; | var div = require('./div');
module.exports = {
classList: !!div.classList,
currentStyle: !!div.currentStyle,
matchesSelector: div.matches ||
div.matchesSelector ||
div.msMatchesSelector ||
div.mozMatchesSelector ||
div.webkitMatchesSelector ||
div.oMatchesSelector,
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: (/^0.55$/).test(div.style.opacity)
}; |
Rename internal functions for clarity.
What
===
Rename internal functions.
Why
===
Clarity. | package static
import (
"errors"
"fmt"
"log"
"os"
)
var (
ErrUnknownCommand = errors.New("Unknown command. Valid commands are: 'server', 'build'.")
)
const (
RunCommandServer = "server"
RunCommandBuild = "build"
)
func (s *Static) Run() error {
command := RunCommandServer
if len(os.Args) >= 2 {
command = os.Args[1]
}
switch command {
case RunCommandBuild:
s.Build(logEvent)
return nil
case RunCommandServer:
addr := fmt.Sprintf(":%d", s.ServerPort)
return s.ListenAndServe(addr, logEvent)
}
return ErrUnknownCommand
}
func logEvent(event Event) {
var s string
if event.Error == nil {
s = fmt.Sprintf("%10s %-20s", event.Action, event.Path)
} else {
s = fmt.Sprintf("%10s %-20s %v", "error", event.Path, event.Error)
}
log.Println(s)
}
| package static
import (
"errors"
"fmt"
"log"
"os"
)
var (
ErrUnknownCommand = errors.New("Unknown command. Valid commands are: 'server', 'build'.")
)
const (
RunCommandServer = "server"
RunCommandBuild = "build"
)
func (s *Static) Run() error {
command := RunCommandServer
if len(os.Args) >= 2 {
command = os.Args[1]
}
switch command {
case RunCommandBuild:
s.Build(logOutput)
return nil
case RunCommandServer:
addr := fmt.Sprintf(":%d", s.ServerPort)
return s.ListenAndServe(addr, logOutput)
}
return ErrUnknownCommand
}
func logOutput(event Event) {
var s string
if event.Error == nil {
s = fmt.Sprintf("%10s %-20s", event.Action, event.Path)
} else {
s = fmt.Sprintf("%10s %-20s %v", "error", event.Path, event.Error)
}
log.Println(s)
}
|
Use the config_file attribute to find .jscs.json | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ilya Akhmadullin
# Copyright (c) 2013 Ilya Akhmadullin
#
# License: MIT
#
"""This module exports the jscs plugin class."""
from SublimeLinter.lint import Linter
class Jscs(Linter):
"""Provides an interface to jscs."""
syntax = ('javascript', 'html', 'html 5')
cmd = 'jscs -r checkstyle'
config_file = ('-c', '.jscs.json')
regex = (
r'^\s+?<error line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
# jscs always reports with error severity; show as warning
r'severity="(?P<warning>error)" '
r'message="(?P<message>.+?)"'
)
multiline = True
selectors = {'html': 'source.js.embedded.html'}
tempfile_suffix = 'js'
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ilya Akhmadullin
# Copyright (c) 2013 Ilya Akhmadullin
#
# License: MIT
#
"""This module exports the jscs plugin class."""
from SublimeLinter.lint import Linter
class Jscs(Linter):
"""Provides an interface to jscs."""
syntax = ('javascript', 'html', 'html 5')
cmd = 'jscs -r checkstyle'
regex = (
r'^\s+?<error line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
# jscs always reports with error severity; show as warning
r'severity="(?P<warning>error)" '
r'message="(?P<message>.+?)"'
)
multiline = True
selectors = {'html': 'source.js.embedded.html'}
tempfile_suffix = 'js'
|
Use isEmpty instead of isNone | import TextArea from '@ember/component/text-area';
import { isEmpty } from '@ember/utils';
import { get, computed } from '@ember/object';
import AutoResize from "../mixins/autoresize";
/**
@element text-area
*/
TextArea.reopen(AutoResize, {
/**
By default, textareas only resize
their height.
@attribute shouldResizeHeight
@type Boolean
*/
shouldResizeHeight: true,
/**
Whitespace should be treated as significant
for text areas.
@attribute significantWhitespace
@default true
@type Boolean
*/
significantWhitespace: true,
/**
Optimistically resize the height
of the textarea so when users reach
the end of a line, they will be
presented with space to begin typing.
If a placeholder is set,
it will be used instead of the value.
@attribute autoResizeText
@type String
*/
autoResizeText: computed('value', 'placeholder', {
get() {
var placeholder = get(this, 'placeholder');
var value = get(this, 'value');
var fillChar = '@';
if (isEmpty(value)) {
return isEmpty(placeholder) ? fillChar : placeholder + fillChar;
}
return value + fillChar;
}
})
});
| import TextArea from '@ember/component/text-area';
import { isNone } from '@ember/utils';
import { get, computed } from '@ember/object';
import AutoResize from "../mixins/autoresize";
/**
@element text-area
*/
TextArea.reopen(AutoResize, {
/**
By default, textareas only resize
their height.
@attribute shouldResizeHeight
@type Boolean
*/
shouldResizeHeight: true,
/**
Whitespace should be treated as significant
for text areas.
@attribute significantWhitespace
@default true
@type Boolean
*/
significantWhitespace: true,
/**
Optimistically resize the height
of the textarea so when users reach
the end of a line, they will be
presented with space to begin typing.
If a placeholder is set,
it will be used instead of the value.
@attribute autoResizeText
@type String
*/
autoResizeText: computed('value', 'placeholder', {
get() {
var placeholder = get(this, 'placeholder');
var value = get(this, 'value');
if (isNone(value)) {
return isNone(placeholder) ? '@' : placeholder;
}
return value + '@';
}
})
});
|
Return the actual value from Lexical::bind_lexing. | <?php
namespace Pharen;
class Lexical{
static $scopes = array();
public static function init_closure($ns, $id){
if(isset(self::$scopes[$ns][$id])){
self::$scopes[$ns][$id][] = array();
}else{
self::$scopes[$ns][$id] = array(array());
}
return $id;
}
public static function get_closure_id($ns, $id){
if($id === Null){
return Null;
}else{
return count(self::$scopes[$ns][$id])-1;
}
}
public static function bind_lexing($ns, $id, $var, &$val){
$closure_id = self::get_closure_id($ns, $id);
self::$scopes[$ns][$id][$closure_id][$var] =& $val;
return $val;
}
public static function get_lexical_binding($ns, $id, $var, $closure_id){
return self::$scopes[$ns][$id][$closure_id][$var];
}
}
| <?php
namespace Pharen;
class Lexical{
static $scopes = array();
public static function init_closure($ns, $id){
if(isset(self::$scopes[$ns][$id])){
self::$scopes[$ns][$id][] = array();
}else{
self::$scopes[$ns][$id] = array(array());
}
return $id;
}
public static function get_closure_id($ns, $id){
if($id === Null){
return Null;
}else{
return count(self::$scopes[$ns][$id])-1;
}
}
public static function bind_lexing($ns, $id, $var, &$val){
$closure_id = self::get_closure_id($ns, $id);
self::$scopes[$ns][$id][$closure_id][$var] =& $val;
}
public static function get_lexical_binding($ns, $id, $var, $closure_id){
return self::$scopes[$ns][$id][$closure_id][$var];
}
}
|
Fix for error when clicking on browser market share pie charts | (function () {
document.addEventListener('mousedown', function (event) {
if (event.target &&
event.target.className &&
event.target.className.indexOf &&
event.target.className.indexOf('ripple') !== -1) {
let $div = document.createElement('div'),
btnRect = event.target.getBoundingClientRect(),
height = event.target.clientHeight,
xPos = event.pageX - (btnRect.left + window.pageXOffset),
yPos = event.pageY - (btnRect.top + window.pageYOffset);
$div.className = 'ripple-effect';
$div.style.height = `${height}px`;
//noinspection JSSuspiciousNameCombination
$div.style.width = `${height}px`;
$div.style.top = `${yPos - (height / 2)}px`;
$div.style.left = `${xPos - (height / 2)}px`;
event.target.appendChild($div);
window.setTimeout(() => event.target.removeChild($div), 2000);
}
});
})();
| (function () {
document.addEventListener('mousedown', function (event) {
if (event.target && event.target.className.indexOf('ripple') !== -1) {
let $div = document.createElement('div'),
btnRect = event.target.getBoundingClientRect(),
height = event.target.clientHeight,
xPos = event.pageX - (btnRect.left + window.pageXOffset),
yPos = event.pageY - (btnRect.top + window.pageYOffset);
$div.className = 'ripple-effect';
$div.style.height = `${height}px`;
//noinspection JSSuspiciousNameCombination
$div.style.width = `${height}px`;
$div.style.top = `${yPos - (height / 2)}px`;
$div.style.left = `${xPos - (height / 2)}px`;
event.target.appendChild($div);
window.setTimeout(() => event.target.removeChild($div), 2000);
}
});
})();
|
Fix tests for udata/datagouvfr backend | import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer',
'first_name': 'foobar',
'email': 'foobar@example.com'
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
'oauth_callback_confirmed': 'true'
})
user_data_body = json.dumps({})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
| import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer'
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
'oauth_callback_confirmed': 'true'
})
user_data_body = json.dumps({})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
|
MAINT: Add a missing subscription slot to `NestedSequence` | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
_T = TypeVar("_T")
NestedSequence = Sequence[Sequence[_T]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
| """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
Test that server config hasn't broken | global.XMLHttpRequest = require('xhr2');
global.dataLayer = [];
var test = require('blue-tape');
var GeordiClient = require('../index');
test('Instantiate a client with default settings', function(t) {
var geordi = new GeordiClient();
t.equal(geordi.env, 'staging');
t.equal(geordi.projectToken, 'unspecified');
t.end();
});
test('Instantiate a client with older settings', function(t) {
var geordi = new GeordiClient({server: 'production'});
t.equal(geordi.env, 'production');
t.end();
});
test('Log without a valid project token', function(t) {
var geordi = new GeordiClient({projectToken:''});
geordi.logEvent('test event')
.then(function(response){
t.fail('invalid project token should not be logged');
t.end();
})
.catch(function(error){
t.pass(error);
t.end();
});
});
test('Log with valid project token', function(t) {
var geordi = new GeordiClient({projectToken: 'test/token'});
geordi.logEvent('test event')
.then(function(response){
t.pass('Valid project token will allow logging');
t.end();
})
});
test('Update data on Geordi', function(t) {
var geordi = new GeordiClient({projectToken: 'test/token'});
geordi.update({projectToken: 'new/token'})
t.equal(geordi.projectToken, 'new/token');
t.end();
});
| global.XMLHttpRequest = require('xhr2');
global.dataLayer = [];
var test = require('blue-tape');
var GeordiClient = require('../index');
test('Instantiate a client with default settings', function(t) {
var geordi = new GeordiClient();
t.equal(geordi.env, 'staging');
t.equal(geordi.projectToken, 'unspecified');
t.end()
});
test('Log without a valid project token', function(t) {
var geordi = new GeordiClient({projectToken:''});
geordi.logEvent('test event')
.then(function(response){
t.fail('invalid project token should not be logged');
t.end()
})
.catch(function(error){
t.pass(error);
t.end()
});
});
test('Log with valid project token', function(t) {
var geordi = new GeordiClient({projectToken: 'test/token'});
geordi.logEvent('test event')
.then(function(response){
t.pass('Valid project token will allow logging');
t.end()
})
});
test('Update data on Geordi', function(t) {
var geordi = new GeordiClient({projectToken: 'test/token'});
geordi.update({projectToken: 'new/token'})
t.equal(geordi.projectToken, 'new/token');
t.end()
});
|
Reorder and group metadata and options together | from setuptools import find_packages, setup
setup(
name='satnogsclient',
version='0.2.5',
url='https://github.com/satnogs/satnogs-client/',
author='SatNOGS team',
author_email='client-dev@satnogs.org',
description='SatNOGS Client',
zip_safe=False,
install_requires=[
'APScheduler',
'SQLAlchemy',
'requests',
'validators',
'python-dateutil',
'ephem',
'pytz',
'flask',
'pyopenssl',
'pyserial',
'flask-socketio',
'redis'
],
extras_require={
'develop': 'flake8'
},
scripts=['satnogsclient/bin/satnogs-poller'],
include_package_data=True,
packages=find_packages()
)
| from setuptools import find_packages, setup
setup(name='satnogsclient',
packages=find_packages(),
version='0.2.5',
author='SatNOGS team',
author_email='client-dev@satnogs.org',
url='https://github.com/satnogs/satnogs-client/',
description='SatNOGS Client',
include_package_data=True,
zip_safe=False,
install_requires=[
'APScheduler',
'SQLAlchemy',
'requests',
'validators',
'python-dateutil',
'ephem',
'pytz',
'flask',
'pyopenssl',
'pyserial',
'flask-socketio',
'redis'
],
extras_require={
'develop': 'flake8'
},
scripts=['satnogsclient/bin/satnogs-poller'])
|
Change default port to 8080 | #!/usr/bin/env python
import os
import bottle
import multivid
# where static files are kept
STATIC_FILES_ROOT = os.path.abspath("static")
@bottle.route("/")
def index():
return bottle.static_file("index.html", root=STATIC_FILES_ROOT)
@bottle.route('/static/<filename:path>')
def serve_static(filename):
return bottle.static_file(filename, root=STATIC_FILES_ROOT)
@bottle.get("/search/autocomplete")
def autocomplete():
query = bottle.request.query["query"]
results = multivid.autocomplete(query)
return {
"query": query,
"results": [r.to_dict() for r in results]
}
@bottle.get("/search/find")
def find():
query = bottle.request.query["query"]
results = multivid.find(query)
return {
"query": query,
"results": [r.to_dict() for r in results]
}
bottle.debug(True)
bottle.run(host="localhost", port=8080, reloader=True)
| #!/usr/bin/env python
import os
import bottle
import multivid
# where static files are kept
STATIC_FILES_ROOT = os.path.abspath("static")
@bottle.route("/")
def index():
return bottle.static_file("index.html", root=STATIC_FILES_ROOT)
@bottle.route('/static/<filename:path>')
def serve_static(filename):
return bottle.static_file(filename, root=STATIC_FILES_ROOT)
@bottle.get("/search/autocomplete")
def autocomplete():
query = bottle.request.query["query"]
results = multivid.autocomplete(query)
return {
"query": query,
"results": [r.to_dict() for r in results]
}
@bottle.get("/search/find")
def find():
query = bottle.request.query["query"]
results = multivid.find(query)
return {
"query": query,
"results": [r.to_dict() for r in results]
}
bottle.debug(True)
bottle.run(host="localhost", port=8000, reloader=True)
|
Undo my 'work-around' for flask-heroku. | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Primary setup for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from flask import Flask
from flask_heroku import Heroku
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('pytips.default_settings')
heroku = Heroku(app)
db = SQLAlchemy(app)
# I'm about to import a module that I won't use explicitly; when it loads, the
# model definitions created, so you *must* leave the import in place. Also, it
# relies on `db` being already configured, so don't import it before everything
# is all set up.
from pytips import models
# I'm about to import a module that I won't use explicitly; when it loads, the
# routes for the app will be defined, so you *must* leave the import in place.
# Also, it relies on `app` being already configured, so don't import it before
# everything is all set up.
from pytips import views
if __name__ == '__main__':
app.run()
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Primary setup for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import os
from flask import Flask
from flask_heroku import Heroku
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('pytips.default_settings')
heroku = Heroku(app)
# Flask-Heroku is looking at an env var that I don't have, so overwrite
# it with one that I found by dumping os.environ in a log statement.
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
'HEROKU_POSTGRESQL_CRIMSON_URL',
app.config['SQLALCHEMY_DATABASE_URI'])
db = SQLAlchemy(app)
# I'm about to import a module that I won't use explicitly; when it loads, the
# model definitions created, so you *must* leave the import in place. Also, it
# relies on `db` being already configured, so don't import it before everything
# is all set up.
from pytips import models
# I'm about to import a module that I won't use explicitly; when it loads, the
# routes for the app will be defined, so you *must* leave the import in place.
# Also, it relies on `app` being already configured, so don't import it before
# everything is all set up.
from pytips import views
if __name__ == '__main__':
app.run()
|
Remove tests to quick fix 'Tinytest is not defined' error | Package.describe({
name: 'konecty:mongo-counter',
summary: "Atomic counters stored in MongoDB",
version: "0.0.5",
git: "https://github.com/Konecty/meteor-mongo-counter.git"
});
Package.on_use(function (api) {
api.versionsFrom("METEOR@0.9.0");
api.use(['coffeescript', 'mongo-livedata'], 'server');
api.addFiles('counter.coffee', 'server');
if (api.export) {
api.export('incrementCounter', 'server');
api.export('decrementCounter', 'server');
api.export('setCounter', 'server');
api.export('deleteCounters', 'server', {testOnly: true});
}
});
//Package.on_test(function(api) {
// api.use(['coffeescript', 'tinytest', "konecty:mongo-counter"]);
// api.addFiles('counter-tests.coffee', 'server');
//});
| Package.describe({
name: 'konecty:mongo-counter',
summary: "Atomic counters stored in MongoDB",
version: "0.0.4",
git: "https://github.com/Konecty/meteor-mongo-counter.git"
});
Package.on_use(function (api) {
api.versionsFrom("METEOR@0.9.0");
api.use(['coffeescript', 'mongo-livedata'], 'server');
api.addFiles('counter.coffee', 'server');
if (api.export) {
api.export('incrementCounter', 'server');
api.export('decrementCounter', 'server');
api.export('setCounter', 'server');
api.export('deleteCounters', 'server', {testOnly: true});
}
});
Package.on_test(function(api) {
api.use(['coffeescript', 'tinytest', "konecty:mongo-counter"]);
api.addFiles('counter-tests.coffee', 'server');
});
|
Gifs: Move map to normalize function. | function ddg_spice_gifs(res) {
if(!res || !res.data || !res.data.length){ return; }
var searchTerm = DDG.get_query().replace(/gifs?/i,'').trim();
Spice.add({
id: 'gifs',
name: 'Gifs',
data: res.data,
normalize: function(item) {
return {
h: item.images.original.url,
j: item.images.original.url,
u: item.url,
ih: item.images.original.height,
iw: item.images.original.width
};
},
meta: {
sourceName: 'Giphy',
sourceUrl: 'http://giphy.com/search/' + searchTerm,
sourceIcon: true,
count: res.pagination.count,
total: res.pagination.total_count,
itemType: 'Gifs'
},
view: 'Images'
});
}
| function ddg_spice_gifs(res) {
if(!res || !res.data || !res.data.length){ return; }
var searchTerm = DDG.get_query().replace(/gif+/i,'').trim();
var items = res.data.map(function(item){
return {
h: item.images.original.url,
j: item.images.original.url,
u: item.url,
ih: item.images.original.height,
iw: item.images.original.width
}
});
Spice.add({
id: 'gifs',
name: 'Gifs',
data: items,
meta: {
sourceName: 'Giphy',
sourceUrl: 'http://giphy.com/search/' + searchTerm,
sourceIcon: true,
count: res.pagination.count,
total: res.pagination.total_count,
itemType: 'Gifs'
},
view: 'Images'
});
}
|
Add cid:// file:// file: schemes
Add cid:// file:// file: schemes, this permits add images with HtmlHelper:
´´´php
echo $this->Html->image('cid://full/path/image');
echo $this->Html->image('file://full/path/image');
´´´ | <?php
App::uses('CakeEmail', 'Network/Email');
class FawnoEmail extends CakeEmail {
protected function _renderTemplates ($content) {
if (!empty($this->_subject) && empty($this->_viewVars['subject'])) {
$this->_viewVars['subject'] = $this->_subject;
}
$render = parent::_renderTemplates($content);
if (!empty($render['html'])) {
$render['html'] = str_replace(array('file:', 'file://', 'cid://'), 'cid:', $render['html']);
if (preg_match_all('~(["\'])cid:([^\1]+)\1~iU', $render['html'], $img)) {
$img = array_unique($img[2]);
foreach ($img as $file) if (is_file($file)) {
$cid = sha1($file);
$this->_attachments['cid:' . $cid]['data'] = base64_encode(file_get_contents($file));
$this->_attachments['cid:' . $cid]['contentId'] = $cid;
$this->_attachments['cid:' . $cid]['mimetype'] = mime_content_type($file);
$render['html'] = str_replace($file, $cid, $render['html']);
}
}
}
return $render;
}
}
?>
| <?php
App::uses('CakeEmail', 'Network/Email');
class FawnoEmail extends CakeEmail {
protected function _renderTemplates ($content) {
if (!empty($this->_subject) && empty($this->_viewVars['subject'])) {
$this->_viewVars['subject'] = $this->_subject;
}
$render = parent::_renderTemplates($content);
if (!empty($render['html'])) {
if (preg_match_all('~(["\'])cid:([^\1]+)\1~iU', $render['html'], $img)) {
$img = array_unique($img[2]);
foreach ($img as $file) if (is_file($file)) {
$cid = sha1($file);
$this->_attachments['cid:' . $cid]['data'] = base64_encode(file_get_contents($file));
$this->_attachments['cid:' . $cid]['contentId'] = $cid;
$this->_attachments['cid:' . $cid]['mimetype'] = mime_content_type($file);
$render['html'] = str_replace($file, $cid, $render['html']);
}
}
}
return $render;
}
}
?>
|
Add doc string for waymo open dataset | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Test for waymo_open_dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
| # coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TODO(waymo_open_dataset): Add a description here."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
|
Change Wait time from 60 to 5 sec | from selenium.webdriver.firefox.webdriver import WebDriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
class Application:
def __init__(self):
self.wd = WebDriver()
self.wd.implicitly_wait(5)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.contact = ContactHelper(self)
def open_home_page(self):
wd = self.wd
wd.get("http://localhost/addressbook/")
def destroy(self):
self.wd.quit()
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False | from selenium.webdriver.firefox.webdriver import WebDriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
class Application:
def __init__(self):
self.wd = WebDriver()
self.wd.implicitly_wait(60)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.contact = ContactHelper(self)
def open_home_page(self):
wd = self.wd
wd.get("http://localhost/addressbook/")
def destroy(self):
self.wd.quit()
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False |
Fix apple observer to create apple in starting goroutine | package observers
import (
"github.com/sirupsen/logrus"
"github.com/ivan1993spb/snake-server/objects/apple"
"github.com/ivan1993spb/snake-server/world"
)
const chanAppleObserverEventsBuffer = 32
const defaultAppleCount = 1
const oneAppleArea = 50
type AppleObserver struct{}
func (AppleObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) {
go func() {
appleCount := defaultAppleCount
size := w.Size()
if size > oneAppleArea {
appleCount = int(size / oneAppleArea)
}
logger.Debugf("apple count for size %d = %d", size, appleCount)
for i := 0; i < appleCount; i++ {
if _, err := apple.NewApple(w); err != nil {
logger.WithError(err).Error("cannot create apple")
}
}
for event := range w.Events(stop, chanAppleObserverEventsBuffer) {
if event.Type == world.EventTypeObjectDelete {
if _, ok := event.Payload.(*apple.Apple); ok {
if _, err := apple.NewApple(w); err != nil {
logger.WithError(err).Error("cannot create apple")
}
}
}
}
}()
}
| package observers
import (
"github.com/sirupsen/logrus"
"github.com/ivan1993spb/snake-server/objects/apple"
"github.com/ivan1993spb/snake-server/world"
)
const chanAppleObserverEventsBuffer = 32
const defaultAppleCount = 1
const oneAppleArea = 50
type AppleObserver struct{}
func (AppleObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) {
appleCount := defaultAppleCount
size := w.Size()
if size > oneAppleArea {
appleCount = int(size / oneAppleArea)
}
logger.Debugf("apple count for size %d = %d", size, appleCount)
for i := 0; i < appleCount; i++ {
if _, err := apple.NewApple(w); err != nil {
logger.WithError(err).Error("cannot create apple")
}
}
go func() {
for event := range w.Events(stop, chanAppleObserverEventsBuffer) {
if event.Type == world.EventTypeObjectDelete {
if _, ok := event.Payload.(*apple.Apple); ok {
if _, err := apple.NewApple(w); err != nil {
logger.WithError(err).Error("cannot create apple")
}
}
}
}
}()
}
|
Allow any object to be used as the response target for a moveTo request.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@1293 542714f4-19e9-0310-aa3c-eee0fc999fb1 | //
// $Id: SceneService.java,v 1.7 2002/04/26 00:07:05 ray Exp $
package com.threerings.whirled.client;
import com.threerings.presents.client.Client;
import com.threerings.presents.client.InvocationDirector;
import com.threerings.whirled.Log;
import com.threerings.whirled.data.SceneCodes;
/**
* The scene service class provides the client interface to the scene
* related invocation services (e.g. moving from scene to scene).
*/
public class SceneService implements SceneCodes
{
/**
* Requests that that this client's body be moved to the specified
* scene.
*
* @param sceneId the scene id to which we want to move.
* @param sceneVers the version number of the scene object that we
* have in our local repository.
*/
public static void moveTo (Client client, int sceneId,
int sceneVers, Object rsptarget)
{
InvocationDirector invdir = client.getInvocationDirector();
Object[] args = new Object[] {
new Integer(sceneId), new Integer(sceneVers) };
invdir.invoke(MODULE_NAME, MOVE_TO_REQUEST, args, rsptarget);
Log.info("Sent moveTo request [scene=" + sceneId +
", version=" + sceneVers + "].");
}
}
| //
// $Id: SceneService.java,v 1.6 2002/04/15 16:28:03 shaper Exp $
package com.threerings.whirled.client;
import com.threerings.presents.client.Client;
import com.threerings.presents.client.InvocationDirector;
import com.threerings.whirled.Log;
import com.threerings.whirled.data.SceneCodes;
/**
* The scene service class provides the client interface to the scene
* related invocation services (e.g. moving from scene to scene).
*/
public class SceneService implements SceneCodes
{
/**
* Requests that that this client's body be moved to the specified
* scene.
*
* @param sceneId the scene id to which we want to move.
* @param sceneVers the version number of the scene object that we
* have in our local repository.
*/
public static void moveTo (Client client, int sceneId,
int sceneVers, SceneDirector rsptarget)
{
InvocationDirector invdir = client.getInvocationDirector();
Object[] args = new Object[] {
new Integer(sceneId), new Integer(sceneVers) };
invdir.invoke(MODULE_NAME, MOVE_TO_REQUEST, args, rsptarget);
Log.info("Sent moveTo request [scene=" + sceneId +
", version=" + sceneVers + "].");
}
}
|
Use utf8 rune decoding instead | package str
import (
"unicode"
"unicode/utf8"
)
// ToSnake converts a string (camel or spinal) to snake case
func ToSnake(str string) string {
// Skip processing for an empty string
if len(str) == 0 {
return ""
}
// Build the results in this buffer
buf := ""
// Trick: if the first character is uppercase, do not prepend an underscore
prev := '_'
for len(str) > 0 {
r, size := utf8.DecodeRuneInString(str)
str = str[size:]
switch {
case unicode.IsUpper(r):
// Prepend an underscore if the previous char is not an underscore
// and the current char is not part of an abbreviation
if prev != '_' && !unicode.IsUpper(prev) {
buf += "_"
}
buf += string(unicode.ToLower(r))
default:
if r == '-' || r == ' ' {
r = '_'
}
buf += string(r)
}
prev = r
}
return buf
}
| package str
import "unicode"
// ToSnake converts a string (camel or spinal) to snake case
func ToSnake(str string) string {
// Skip processing for an empty string
if len(str) == 0 {
return ""
}
// Build the results in this buffer
buf := ""
// Trick: if the first character is uppercase, do not prepend an underscore
prev := '_'
for _, c := range str {
switch {
case unicode.IsUpper(c):
// Prepend an underscore if the previous char is not an underscore
// and the current char is not part of an abbreviation
if prev != '_' && !unicode.IsUpper(prev) {
buf += "_"
}
buf += string(unicode.ToLower(c))
default:
if c == '-' || c == ' ' {
c = '_'
}
buf += string(c)
}
prev = c
}
return buf
}
|
Fix typo in previous commit | #!/usr/bin/env python
from contextlib import closing
from sqlite3 import connect
from os.path import isfile
from bottle import request, template, route, run
@route('/virustotal/<db>')
def virus(db):
if not isfile(db):
return 'The database does not exist: "%s"' % db
with connect(db, timeout=10) as connection:
with closing(connection.cursor()) as cursor:
cursor.execute("SELECT count(*), CAST(0.999 + detected * 10 AS INT) || '0%' AS score"
"FROM virus WHERE detected >= 0 GROUP BY score ORDER BY score")
return template('virustotal', title=db, cursor=cursor, refresh=request.query.refresh)
run(host='0.0.0.0')
| #!/usr/bin/env python
from contextlib import closing
from sqlite3 import connect
from os.path import isfile
from bottle import request, template, route, run
@route('/virustotal/<db>')
def virus(db):
if not isfile(db):
return 'The database does not exist: "%s"' % db
with connect(db, timeout=10) as connection:
with closing(connection.cursor()) as cursor:
cursor.execute('SELECT count(*), CAST(0.999 + detected * 10 AS INT) || '0%' AS score'
'FROM virus WHERE detected >= 0 GROUP BY score ORDER BY score')
return template('virustotal', title=db, cursor=cursor, refresh=request.query.refresh)
run(host='0.0.0.0')
|
Set integrations for the index page now | from werkzeug import redirect
from werkzeug.exceptions import NotFound
from websod.utils import session, expose, url_for, serve_template
from websod.models import Integration
from datetime import timedelta, datetime
def home(request):
# show results from last 3 days
integrations_from = datetime.now() + timedelta(days=-3)
from_str = integrations_from.strftime("%Y-%m-%d 00:00:00")
latest_integrations = session.query(Integration).\
filter("started > '%s'" % from_str).\
order_by(Integration.started.desc()).all()
return serve_template('home.html', latest_integrations=latest_integrations)
@expose('/integration/<int:id>')
def integration(request, id):
integration = session.query(Integration).get(id)
return serve_template('integration.html', integration=integration)
@expose('/')
@expose('/integration/')
def integration_list(request):
integrations = session.query(Integration).all()
return serve_template('integration_list.html', integrations=integrations)
| from werkzeug import redirect
from werkzeug.exceptions import NotFound
from websod.utils import session, expose, url_for, serve_template
from websod.models import Integration
from datetime import timedelta, datetime
@expose('/')
def home(request):
# show results from last 3 days
integrations_from = datetime.now() + timedelta(days=-3)
from_str = integrations_from.strftime("%Y-%m-%d 00:00:00")
latest_integrations = session.query(Integration).\
filter("started > '%s'" % from_str).\
order_by(Integration.started.desc()).all()
return serve_template('home.html', latest_integrations=latest_integrations)
@expose('/integration/<int:id>')
def integration(request, id):
integration = session.query(Integration).get(id)
return serve_template('integration.html', integration=integration)
@expose('/integration/')
def integration_list(request):
integrations = session.query(Integration).all()
return serve_template('integration_list.html', integrations=integrations)
|
Remove the responsability of spec checking
Signed-off-by: Fabio José <34f3a7e4e4d9fe971c99ebc4af947a5309eca653@gmail.com> | function JSONParser() {
}
/**
* Level 0 of validation: is that string? is that JSON?
*/
function validate_and_parse_as_json(payload) {
var json = payload;
if(payload) {
if( (typeof payload) == "string"){
try {
json = JSON.parse(payload);
}catch(e) {
throw {message: "invalid json payload", errors: e};
}
} else if( (typeof payload) != "object"){
// anything else
throw {message: "invalid payload type, allowed are: string or object"};
}
} else {
throw {message: "null or undefined payload"};
}
return json;
}
/*
* Level 1 of validation: is that follow a spec?
*/
function validate_spec(payload, spec) {
// is that follow the spec?
spec.check(payload);
return payload;
}
JSONParser.prototype.parse = function(payload) {
//is that string? is that JSON?
var valid = validate_and_parse_as_json(payload);
return valid;
}
module.exports = JSONParser;
| var Spec02 = require("../../specs/spec_0_2.js");
const spec02 = new Spec02();
function JSONParser(_spec) {
this.spec = (_spec) ? _spec : new Spec02();
}
/**
* Level 0 of validation: is that string? is that JSON?
*/
function validate_and_parse_as_json(payload) {
var json = payload;
if(payload) {
if( (typeof payload) == "string"){
try {
json = JSON.parse(payload);
}catch(e) {
throw {message: "invalid json payload", errors: e};
}
} else if( (typeof payload) != "object"){
// anything else
throw {message: "invalid payload type, allowed are: string or object"};
}
} else {
throw {message: "null or undefined payload"};
}
return json;
}
/*
* Level 1 of validation: is that follow a spec?
*/
function validate_spec(payload, spec) {
// is that follow the spec?
spec.check(payload);
return payload;
}
JSONParser.prototype.parse = function(payload) {
// Level 0 of validation: is that string? is that JSON?
var valid0 = validate_and_parse_as_json(payload);
// Level 1 of validation: is that follow a spec?
var valid1 = validate_spec(valid0, this.spec);
return valid1;
}
module.exports = JSONParser;
|
Add flag to print version | package main
import (
"flag"
"fmt"
"os"
"sync"
"github.com/leoleovich/grafsy"
)
var version = "dev"
func main() {
var configFile string
printVersion := false
flag.StringVar(&configFile, "c", "/etc/grafsy/grafsy.toml", "Path to config file.")
flag.BoolVar(&printVersion, "v", printVersion, "Print version and exit")
flag.Parse()
if printVersion {
fmt.Printf("Version: %v\n", version)
os.Exit(0)
}
var conf grafsy.Config
err := conf.LoadConfig(configFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lc, err := conf.GenerateLocalConfig()
if err != nil {
fmt.Println(err)
os.Exit(2)
}
mon := &grafsy.Monitoring{
Conf: &conf,
Lc: lc,
}
cli := grafsy.Client{
Conf: &conf,
Lc: lc,
Mon: mon,
}
srv := grafsy.Server{
Conf: &conf,
Lc: lc,
Mon: mon,
}
var wg sync.WaitGroup
go mon.Run()
go srv.Run()
go cli.Run()
wg.Add(3)
wg.Wait()
}
| package main
import (
"flag"
"fmt"
"os"
"sync"
"github.com/leoleovich/grafsy"
)
func main() {
var configFile string
flag.StringVar(&configFile, "c", "/etc/grafsy/grafsy.toml", "Path to config file.")
flag.Parse()
var conf grafsy.Config
err := conf.LoadConfig(configFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lc, err := conf.GenerateLocalConfig()
if err != nil {
fmt.Println(err)
os.Exit(2)
}
mon := &grafsy.Monitoring{
Conf: &conf,
Lc: lc,
}
cli := grafsy.Client{
Conf: &conf,
Lc: lc,
Mon: mon,
}
srv := grafsy.Server{
Conf: &conf,
Lc: lc,
Mon: mon,
}
var wg sync.WaitGroup
go mon.Run()
go srv.Run()
go cli.Run()
wg.Add(3)
wg.Wait()
}
|
Fix for empty() on a constant | <?php
function sql_open() {
global $pdo;
if($pdo) return true;
$dsn = DB_TYPE . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE;
if((bool)DB_DSN) // empty() doesn't work on constants
$dsn .= ';' . DB_DSN;
try {
return $pdo = new PDO($dsn, DB_USER, DB_PASSWORD);
} catch(PDOException $e) {
$message = $e->getMessage();
// Remove any sensitive information
$message = str_replace(DB_USER, '<em>hidden</em>', $message);
$message = str_replace(DB_PASSWORD, '<em>hidden</em>', $message);
// Print error
error('Database error: ' . $message);
}
}
function sql_close() {
global $pdo;
$pdo = NULL;
}
function prepare($query) {
global $pdo;
return $pdo->prepare($query);
}
function query($query) {
global $pdo;
return $pdo->query($query);
}
function db_error($PDOStatement=null) {
global $pdo;
if(isset($PDOStatement)) {
$err = $PDOStatement->errorInfo();
return $err[2];
} else {
$err = $pdo->errorInfo();
return $err[2];
}
}
?> | <?php
function sql_open() {
global $pdo;
if($pdo) return true;
$dsn = DB_TYPE . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE;
if(!empty(DB_DSN))
$dsn .= ';' . DB_DSN;
try {
return $pdo = new PDO($dsn, DB_USER, DB_PASSWORD);
} catch(PDOException $e) {
$message = $e->getMessage();
// Remove any sensitive information
$message = str_replace(DB_USER, '<em>hidden</em>', $message);
$message = str_replace(DB_PASSWORD, '<em>hidden</em>', $message);
// Print error
error('Database error: ' . $message);
}
}
function sql_close() {
global $pdo;
$pdo = NULL;
}
function prepare($query) {
global $pdo;
return $pdo->prepare($query);
}
function query($query) {
global $pdo;
return $pdo->query($query);
}
function db_error($PDOStatement=null) {
global $pdo;
if(isset($PDOStatement)) {
$err = $PDOStatement->errorInfo();
return $err[2];
} else {
$err = $pdo->errorInfo();
return $err[2];
}
}
?> |
Fix typo in output json message | #!/usr/bin/env python3
from flask import Flask
from flask import request
from flask import jsonify
from utils import download_file, create_temp_dir, zip_up_dir, delete_dir
from annotations import sort_annotations_by_time
from videoeditor import bake_annotations
app = Flask(__name__)
@app.route("/", methods=["POST"])
def index():
request_json = request.get_json()
# Allow both plain JSON objects and arrays
if type(request_json) is dict:
request_json = [request_json]
for video_json in request_json:
export_dir_name = create_temp_dir()
video_uri = video_json["videoUri"]
video_filename = video_uri.rsplit("/")[-1]
video_location = download_file(video_uri, "video-cache/" + video_filename)
sorted_annotations = sort_annotations_by_time(video_json["annotations"])
bake_annotations(video_location, export_dir_name + '/' + video_filename, sorted_annotations)
zip_up_dir(export_dir_name, 'video-exports/' + video_json["title"])
delete_dir(export_dir_name)
return jsonify({"message": "Annotated video created successfully"})
if __name__ == "__main__":
app.run(debug=True)
| #!/usr/bin/env python3
from flask import Flask
from flask import request
from flask import jsonify
from utils import download_file, create_temp_dir, zip_up_dir, delete_dir
from annotations import sort_annotations_by_time
from videoeditor import bake_annotations
app = Flask(__name__)
@app.route("/", methods=["POST"])
def index():
request_json = request.get_json()
# Allow both plain JSON objects and arrays
if type(request_json) is dict:
request_json = [request_json]
for video_json in request_json:
export_dir_name = create_temp_dir()
video_uri = video_json["videoUri"]
video_filename = video_uri.rsplit("/")[-1]
video_location = download_file(video_uri, "video-cache/" + video_filename)
sorted_annotations = sort_annotations_by_time(video_json["annotations"])
bake_annotations(video_location, export_dir_name + '/' + video_filename, sorted_annotations)
zip_up_dir(export_dir_name, 'video-exports/' + video_json["title"])
delete_dir(export_dir_name)
return jsonify({"message": "Annotated video created succesfully"})
if __name__ == "__main__":
app.run(debug=True)
|
Fix bug where installer wasn't working on non ipython-pip machines. | # -*- coding: utf-8 -*-
from __future__ import print_function
from setuptools import setup
try:
from ipythonpip import cmdclass
except:
import pip, importlib
pip.main(['install', 'ipython-pip']); cmdclass = importlib.import_module('ipythonpip').cmdclass
setup(
name='d3networkx',
version='0.1',
description='Visualize networkx graphs using D3.js in the IPython notebook.',
author='Jonathan Frederic',
author_email='jon.freder@gmail.com',
license='MIT License',
url='https://github.com/jdfreder/ipython-d3networkx',
keywords='python ipython javascript d3 networkx d3networkx widget',
classifiers=['Development Status :: 4 - Beta',
'Programming Language :: Python',
'License :: OSI Approved :: MIT License'],
packages=['d3networkx'],
include_package_data=True,
install_requires=["ipython-pip"],
cmdclass=cmdclass('d3networkx'),
)
| # -*- coding: utf-8 -*-
from __future__ import print_function
from setuptools import setup
try:
from ipythonpip import cmdclass
except:
cmdclass = lambda *args: None
setup(
name='d3networkx',
version='0.1',
description='Visualize networkx graphs using D3.js in the IPython notebook.',
author='Jonathan Frederic',
author_email='jon.freder@gmail.com',
license='MIT License',
url='https://github.com/jdfreder/ipython-d3networkx',
keywords='python ipython javascript d3 networkx d3networkx widget',
classifiers=['Development Status :: 4 - Beta',
'Programming Language :: Python',
'License :: OSI Approved :: MIT License'],
packages=['d3networkx'],
include_package_data=True,
install_requires=["ipython-pip"],
cmdclass=cmdclass('d3networkx'),
)
|
Allow overriding of date error fields | 'use strict';
const debug = require('debug')('hmpo:fields:Select');
const InputDate = require('./input-date');
const ErrorGroup = require('./error-group');
class InputDateGroup extends InputDate {
constructor(content, ctx, options) {
debug('constructor');
super(content, ctx, options);
this.errorGroup = new ErrorGroup(Object.assign({
groupClassName: 'form-date',
legendClassName: 'form-label-bold'
}, this.field), ctx, options);
this.errorGroupEnd = new ErrorGroup.End({}, ctx, options);
}
render() {
let parts = [
this.errorGroup.render(),
super.render(),
this.errorGroupEnd.render(),
];
return parts.join('\n');
}
}
module.exports = InputDateGroup;
| 'use strict';
const debug = require('debug')('hmpo:fields:Select');
const InputDate = require('./input-date');
const ErrorGroup = require('./error-group');
class InputDateGroup extends InputDate {
constructor(content, ctx, options) {
debug('constructor');
super(content, ctx, options);
this.errorGroup = new ErrorGroup({
key: this.key,
groupClassName: 'form-date',
legendClassName: 'form-label-bold'
}, ctx, options);
this.errorGroupEnd = new ErrorGroup.End({}, ctx, options);
}
render() {
let parts = [
this.errorGroup.render(),
super.render(),
this.errorGroupEnd.render(),
];
return parts.join('\n');
}
}
module.exports = InputDateGroup;
|
Fix bug on the class loader | 'use strict';
var ensure = require('ensure.js'),
ClassNotFoundException = require('./Exceptions/ClassNotFoundException.js'),
ClassMap = require('../Mapper/ClassMap.js');
var Loader;
/**
* ClassLoader
*
* Capable of loading a class using multiple class maps. A class will be
* resolved in the order the class maps have been added.
*
* @return {undefined} -
*/
Loader = function () {
this.maps = [];
};
/**
* Add a map to the loader
*
* @param {enclosure.Chromabits.Mapper.ClassMap} map -
*
* @return {undefined} -
*/
Loader.prototype.addMap = function (map) {
ensure(map, ClassMap);
this.maps.push(map);
};
/**
* Get the constructor for the specified class
*
* @param {String} fullClassName -
*
* @return {Function} -
*/
Loader.prototype.get = function (fullClassName) {
for (var key in this.maps) {
if (this.maps.hasOwnProperty(key)) {
var map = this.maps[key];
if (map.has(fullClassName)) {
return map.get(fullClassName);
}
}
}
throw new ClassNotFoundException(fullClassName);
};
module.exports = Loader;
| 'use strict';
var ensure = require('ensure.js'),
ClassNotFoundException = require('./Exceptions/ClassNotFoundException.js'),
ClassMap = require('../Mapper/ClassMap.js');
var Loader;
/**
* ClassLoader
*
* Capable of loading a class using multiple class maps. A class will be
* resolved in the order the class maps have been added.
*
* @return {undefined} -
*/
Loader = function () {
this.maps = [];
};
/**
* Add a map to the loader
*
* @param {enclosure.Chromabits.Mapper.ClassMap} map -
*
* @return {undefined} -
*/
Loader.prototype.addMap = function (map) {
ensure(map, ClassMap);
this.maps.push(map);
};
/**
* Get the constructor for the specified class
*
* @param {String} fullClassName -
*
* @return {Function} -
*/
Loader.prototype.get = function (fullClassName) {
for (var map in this.maps) {
if (map.has(fullClassName)) {
return map.get(fullClassName);
}
}
throw new ClassNotFoundException(fullClassName);
};
module.exports = Loader;
|
Move variable declaration and add section headers | 'use strict';
// TODO: clean-up
// MODULES //
var abs = require( '@stdlib/math/base/special/abs' );
var divide = require( 'compute-divide' );
var mean = require( 'compute-mean' );
var subtract = require( 'compute-subtract' );
var log10 = require( './../lib' );
// FIXTURES //
var data = require( './fixtures/julia/data.json' );
// MAIN //
var customErrs;
var nativeErrs;
var yexpected;
var ycustom;
var ynative;
var x;
var i;
x = data.x;
yexpected = data.expected;
ycustom = new Array( x.length );
ynative = new Array( x.length );
for ( i = 0; i < x.length; i++ ) {
if ( yexpected[ i ] === 0.0 ) {
yexpected[ i ] += 1e-16;
}
ycustom[ i ] = log10( x[ i ] );
ynative[ i ] = Math.log10( x[ i ] );
}
customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) );
nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) );
console.log( 'The mean relative error of Math.log10 compared to Julia is %d', mean( nativeErrs ) );
console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
| 'use strict';
// TODO: clean-up
var abs = require( '@stdlib/math/base/special/abs' );
var divide = require( 'compute-divide' );
var mean = require( 'compute-mean' );
var subtract = require( 'compute-subtract' );
var log10 = require( './../lib' );
var data = require( './fixtures/julia/data.json' );
var x = data.x;
var yexpected = data.expected;
var ycustom = new Array( x.length );
var ynative = new Array( x.length );
for ( var i = 0; i < x.length; i++ ) {
if ( yexpected[ i ] === 0.0 ) {
yexpected[ i ] += 1e-16;
}
ycustom[ i ] = log10( x[ i ] );
ynative[ i ] = Math.log10( x[ i ] );
}
var customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) );
var nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) );
console.log( 'The mean relative error of Math.log10 compared to Julia is %d', mean( nativeErrs ) );
console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
|
consentSimpleAdmin: Use new selftest-function on database backend.
git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@3309 44740490-163a-0410-bde0-09ae8108e29a | <?php
/**
*
* @param array &$hookinfo hookinfo
*/
function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) {
assert('is_array($hookinfo)');
assert('array_key_exists("errors", $hookinfo)');
assert('array_key_exists("info", $hookinfo)');
try {
$consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php');
// Parse consent config
$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));
if (!is_callable(array($consent_storage, 'selftest'))) {
/* Doesn't support a selftest. */
return;
}
$testres = $consent_storage->selftest();
if ($testres) {
$hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage selftest OK.';
} else {
$hookinfo['errors'][] = '[consentSimpleAdmin] Consent Storage selftest failed.';
}
} catch (Exception $e) {
$hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage();
}
}
?> | <?php
/**
*
* @param array &$hookinfo hookinfo
*/
function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) {
assert('is_array($hookinfo)');
assert('array_key_exists("errors", $hookinfo)');
assert('array_key_exists("info", $hookinfo)');
try {
$consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php');
// Parse consent config
$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));
// Get all consents for user
$stats = $consent_storage->getStatistics();
$hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage connection OK.';
} catch (Exception $e) {
$hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage();
}
}
?> |
:art: Extend HTMLElement instead of HTMLDivElement | "use strict";
class BottomTab extends HTMLElement{
initialize(Content, linter){
this.linter = linter
this._active = true
this._count = 0
this.innerHTML = Content
this.classList.add('linter-tab')
this.countSpan = document.createElement('span')
this.countSpan.classList.add('badge')
this.countSpan.classList.add('badge-flexible')
this.countSpan.textContent = '0'
this.appendChild(document.createTextNode(' '))
this.appendChild(this.countSpan)
this.addEventListener('click', this.onClick)
}
get active(){
return this._active
}
set active(value){
if(value){
this.classList.add('active')
} else {
this.classList.remove('active')
}
this._active = value
}
get count(){
return this._count
}
set count(value){
this._count = value
this.countSpan.textContent = value
}
onClick(){} // To be replaced by the extending classes
}
// module.exports = BottomTab = document.registerElement('linter-bottom-tab', {prototype: BottomTab.prototype})
module.exports = BottomTab | "use strict";
class BottomTab extends HTMLDivElement{
initialize(Content, linter){
this.linter = linter
this._active = true
this._count = 0
this.innerHTML = Content
this.classList.add('linter-tab')
this.countSpan = document.createElement('span')
this.countSpan.classList.add('badge')
this.countSpan.classList.add('badge-flexible')
this.countSpan.textContent = '0'
this.appendChild(document.createTextNode(' '))
this.appendChild(this.countSpan)
this.addEventListener('click', this.onClick)
}
get active(){
return this._active
}
set active(value){
if(value){
this.classList.add('active')
} else {
this.classList.remove('active')
}
this._active = value
}
get count(){
return this._count
}
set count(value){
this._count = value
this.countSpan.textContent = value
}
onClick(){} // To be replaced by the extending classes
}
// module.exports = BottomTab = document.registerElement('linter-bottom-tab', {prototype: BottomTab.prototype})
module.exports = BottomTab |
Fix for loading SiteMap entry on Spring 2.x | /*
* Created on 11-Jan-2006
*/
package uk.org.ponder.rsf.test.sitemap;
import java.util.HashMap;
import uk.org.ponder.rsf.bare.junit.PlainRSFTests;
import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters;
import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser;
public class TestSiteMap extends PlainRSFTests {
public TestSiteMap() {
contributeConfigLocation("classpath:uk/org/ponder/rsf/test/sitemap/sitemap-context.xml");
}
public void testParseECVP() {
BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser");
HashMap attrmap = new HashMap();
attrmap.put("flowtoken", "ec38f0");
EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap);
System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname);
}
}
| /*
* Created on 11-Jan-2006
*/
package uk.org.ponder.rsf.test.sitemap;
import java.util.HashMap;
import uk.org.ponder.rsf.bare.junit.PlainRSFTests;
import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters;
import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser;
public class TestSiteMap extends PlainRSFTests {
public void testParseECVP() {
BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser");
HashMap attrmap = new HashMap();
attrmap.put("flowtoken", "ec38f0");
EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap);
System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname);
}
}
|
Fix toast problem with apostrophe | <?php
/**
* Toast messages file.
* This file is being included in footer_scripts.php
*
* Shows toasts for the various 'levels':
* - notice
* - success
* - warning
* - error
*
* Success toasts are the only ones not sticky due to its nature.
*/
?>
<?php $messages = Status_msg::get(); ?>
<?php if ($messages) : ?>
<script>
<?php foreach($messages as $index => $msg): ?>
$().toastmessage('showToast', {
sticky : <?= $msg['sticky'] ? 'true' : 'false'; ?>,
text : "<?= $msg['msg']; ?>",
type : '<?= $msg['level']; ?>',
inEffectDuration : 100,
position : 'bottom-right',
});
<?php endforeach; ?>
</script>
<?php endif; ?> | <?php
/**
* Toast messages file.
* This file is being included in footer_scripts.php
*
* Shows toasts for the various 'levels':
* - notice
* - success
* - warning
* - error
*
* Success toasts are the only ones not sticky due to its nature.
*/
?>
<?php $messages = Status_msg::get(); ?>
<?php if ($messages) : ?>
<script>
<?php foreach($messages as $index => $msg): ?>
$().toastmessage('showToast', {
sticky : <?= $msg['sticky'] ? 'true' : 'false'; ?>,
text : '<?= $msg['msg']; ?>',
type : '<?= $msg['level']; ?>',
inEffectDuration : 100,
position : 'bottom-right',
});
<?php endforeach; ?>
</script>
<?php endif; ?> |
Fix month filter for recap passage report | from __future__ import absolute_import
from __future__ import unicode_literals
from memoized import memoized
from corehq.apps.reports.standard import MonthYearMixin
from custom.intrahealth.filters import RecapPassageLocationFilter2, FRMonthFilter, FRYearFilter
from custom.intrahealth.sqldata import RecapPassageData2, DateSource2
from custom.intrahealth.reports.tableu_de_board_report_v2 import MultiReport
class RecapPassageReport2(MonthYearMixin, MultiReport):
title = "Recap Passage NEW"
name = "Recap Passage NEW"
slug = 'recap_passage2'
report_title = "Recap Passage"
exportable = True
default_rows = 10
fields = [FRMonthFilter, FRYearFilter, RecapPassageLocationFilter2]
def config_update(self, config):
if self.location and self.location.location_type_name.lower() == 'pps':
config['location_id'] = self.location.location_id
@property
@memoized
def data_providers(self):
dates = DateSource2(config=self.report_config).rows
data_providers = []
for date in dates:
config = self.report_config
config.update(dict(startdate=date, enddate=date))
data_providers.append(RecapPassageData2(config=config))
if not data_providers:
data_providers.append(RecapPassageData2(config=self.report_config))
return data_providers
| from __future__ import absolute_import
from __future__ import unicode_literals
from memoized import memoized
from custom.intrahealth.filters import RecapPassageLocationFilter2, FRMonthFilter, FRYearFilter
from custom.intrahealth.sqldata import RecapPassageData2, DateSource2
from custom.intrahealth.reports.tableu_de_board_report_v2 import MultiReport
class RecapPassageReport2(MultiReport):
title = "Recap Passage NEW"
name = "Recap Passage NEW"
slug = 'recap_passage2'
report_title = "Recap Passage"
exportable = True
default_rows = 10
fields = [FRMonthFilter, FRYearFilter, RecapPassageLocationFilter2]
def config_update(self, config):
if self.location and self.location.location_type_name.lower() == 'pps':
config['location_id'] = self.location.location_id
@property
@memoized
def data_providers(self):
dates = DateSource2(config=self.report_config).rows
data_providers = []
for date in dates:
config = self.report_config
config.update(dict(startdate=date, enddate=date))
data_providers.append(RecapPassageData2(config=config))
if not data_providers:
data_providers.append(RecapPassageData2(config=self.report_config))
return data_providers
|
Fix bug that prevents Locale from launching scripts. | /*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.ase.locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.ase.Constants;
import com.google.ase.IntentBuilders;
public class LocaleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String scriptName = intent.getStringExtra(Constants.EXTRA_SCRIPT_NAME);
Log.v("LocaleReceiver", "Locale initiated launch of " + scriptName);
context.startActivity(IntentBuilders.buildStartInTerminalIntent(scriptName));
}
}
| /*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.ase.locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.ase.Constants;
import com.google.ase.IntentBuilders;
public class LocaleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String scriptName = intent.getStringExtra(Constants.EXTRA_SCRIPT_NAME);
Log.v("LocaleReceiver", "Locale initiated launch of " + scriptName);
context.startService(IntentBuilders.buildStartInTerminalIntent(scriptName));
}
}
|
Remove create_wrapper from the API | """ Simphony engine module
This module is dynamicaly populated at import with the
registered plugins modules. Plugins modules need to be
registered at the 'simphony.engine' entry point.
"""
from ..extension import get_engine_manager
__all__ = ['get_supported_engines',
'get_supported_engine_names']
def get_supported_engine_names():
"""Show a list of supported engine names.
Returns
-------
names: list
a list of engine names
"""
return get_engine_manager().get_supported_engine_names()
def get_supported_engines():
"""Show a list of supported engines.
Returns
-------
metadata: list
a list of engine metadata objects
"""
return get_engine_manager().get_supported_engines()
def load_engine_extentions():
""" Discover and load engine extension modules.
"""
from stevedore import extension
mgr = extension.ExtensionManager(
namespace='simphony.engine',
invoke_on_load=False)
extensions = {}
engine_manager = get_engine_manager()
for ext in mgr.extensions:
extensions[ext.name] = ext.plugin
# Load engine metadata
engine_manager.load_metadata(ext.plugin)
return extensions
# Populate the module namespace
globals().update(load_engine_extentions())
# cleanup
del load_engine_extentions
| """ Simphony engine module
This module is dynamicaly populated at import with the
registered plugins modules. Plugins modules need to be
registered at the 'simphony.engine' entry point.
"""
from ..extension import get_engine_manager
from ..extension import create_wrapper
__all__ = ['get_supported_engines', 'create_wrapper',
'get_supported_engine_names']
def get_supported_engine_names():
"""Show a list of supported engine names.
Returns
-------
names: list
a list of engine names
"""
return get_engine_manager().get_supported_engine_names()
def get_supported_engines():
"""Show a list of supported engines.
Returns
-------
metadata: list
a list of engine metadata objects
"""
return get_engine_manager().get_supported_engines()
def load_engine_extentions():
""" Discover and load engine extension modules.
"""
from stevedore import extension
mgr = extension.ExtensionManager(
namespace='simphony.engine',
invoke_on_load=False)
extensions = {}
engine_manager = get_engine_manager()
for ext in mgr.extensions:
extensions[ext.name] = ext.plugin
# Load engine metadata
engine_manager.load_metadata(ext.plugin)
return extensions
# Populate the module namespace
globals().update(load_engine_extentions())
# cleanup
del load_engine_extentions
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.