text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Remove manual emit on status
|
from gevent import monkey
monkey.patch_all()
import time
from threading import Thread
import settings
import requests
from flask import Flask
from flask.ext.socketio import SocketIO, emit
app = Flask(__name__)
app.config.from_object('settings')
app.debug = True
if not app.debug:
import logging
file_handler = logging.FileHandler('production.log')
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
socketio = SocketIO(app)
thread = None
class StorjAPI:
@staticmethod
def getNodeStatus():
r = requests.get(app.config['NODE_URL'] + '/api/status')
return r.json()
def status_thread():
while True:
time.sleep(5)
socketio.emit('status', StorjAPI.getNodeStatus(), namespace='/metadisk')
@socketio.on('connect', namespace='/metadisk')
def metadisk_connect():
global thread
if thread is None:
thread = Thread(target=status_thread)
thread.start()
print('Client has connected.')
@socketio.on('disconnect', namespace='/metadisk')
def metadisk_disconnect():
print('Client has disconnected.')
if __name__ == '__main__':
socketio.run(app)
|
from gevent import monkey
monkey.patch_all()
import time
from threading import Thread
import settings
import requests
from flask import Flask
from flask.ext.socketio import SocketIO, emit
app = Flask(__name__)
app.config.from_object('settings')
app.debug = True
if not app.debug:
import logging
file_handler = logging.FileHandler('production.log')
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
socketio = SocketIO(app)
thread = None
class StorjAPI:
@staticmethod
def getNodeStatus():
r = requests.get(app.config['NODE_URL'] + '/api/status')
return r.json()
def status_thread():
while True:
time.sleep(5)
socketio.emit('status', StorjAPI.getNodeStatus(), namespace='/metadisk')
@socketio.on('status')
def node_status():
socketio.emit('status', StorjAPI.getNodeStatus())
@socketio.on('connect', namespace='/metadisk')
def metadisk_connect():
global thread
if thread is None:
thread = Thread(target=status_thread)
thread.start()
print('Client has connected.')
@socketio.on('disconnect', namespace='/metadisk')
def metadisk_disconnect():
print('Client has disconnected.')
if __name__ == '__main__':
socketio.run(app)
|
Update test to use standard scenario
|
from django.db import IntegrityError
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from crm.tests.scenario import (
contact_contractor,
)
from login.tests.scenario import (
get_fred,
get_sara,
user_contractor,
)
class TestContactUser(TestCase):
def test_link_user_to_contact(self):
"""Create a contact and link it to a user"""
user_contractor()
contact_contractor()
user_contacts = get_fred().usercontact_set.all()
self.assertIn("Fred's Farm", user_contacts[0].contact.name)
def test_one_contact_per_user(self):
"""Make sure a user can only link to one contact"""
user_contractor()
contact_contractor()
self.assertRaises(
IntegrityError,
make_user_contact,
get_sara(),
make_contact('zoo', 'Bristol Zoo')
)
|
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from login.tests.model_maker import make_user
class TestContactUser(TestCase):
def test_link_user_to_contact(self):
"""Create a contact and link it to a user"""
contact = make_contact(
'pkimber',
'Patrick Kimber',
)
make_user_contact(make_user('fred'), contact)
user = User.objects.get(username='fred')
user_contacts = user.usercontact_set.all()
self.assertIn('Kimber', user_contacts[0].contact.name)
def test_one_contact_per_user(self):
"""Make sure a user can only link to one contact"""
fred = make_user('fred')
jsmith = make_contact('jsmith', 'John Smith')
pkimber = make_contact('pkimber', 'Patrick Kimber')
make_user_contact(fred, pkimber)
self.assertRaises(
IntegrityError,
make_user_contact,
fred,
jsmith,
)
|
fix(joystick): Merge beam's agar angle handling
|
'use strict';
// Mostly borrowed from https://github.com/WatchBeam/agar-node-robot/blob/master/index.js
const ANGLE_OFFSET = Math.PI / 2;
const multiplier = 20;
function clamp(val, min, max) {
if (isNaN(val)) {
return 0;
}
if (val < min) {
return min;
}
if (val > max) {
return max;
}
return val;
}
function formula(value, multiplier, intensity) {
return value * (multiplier * intensity);
}
function intensity(x, y) {
return clamp(Math.sqrt(x * x + y * y), 0, 1);
}
module.exports = function (joyStickState) {
const result = {};
if (joyStickState.coordMean && joyStickState.coordMean.x) {
result.x = joyStickState.coordMean.x;
result.y = joyStickState.coordMean.y;
result.intensity = intensity(result.x, result.y);
result.x = formula(result.x, multiplier, result.intensity);
result.y = formula(result.y, multiplier, result.intensity);
const angle = Math.atan2(result.x, result.y) + ANGLE_OFFSET;
result.angle = isNaN (angle) ? 0 : angle;
return result;
}
return undefined;
};
|
'use strict';
// Mostly borrowed from https://github.com/WatchBeam/agar-node-robot/blob/master/index.js
const ANGLE_OFFSET = Math.PI / 2;
const multiplier = 20;
function clamp(val, min, max) {
if (val < min) {
return min;
}
if (val > max) {
return max;
}
return val;
}
function formula(value, multiplier, intensity) {
return value * (multiplier * intensity);
}
function intensity(x, y) {
return clamp(Math.sqrt(x * x + y * y), 0, 1);
}
module.exports = function (joyStickState) {
const result = {};
if (joyStickState.coordMean && joyStickState.coordMean.x) {
result.x = joyStickState.coordMean.x;
result.y = joyStickState.coordMean.y;
result.intensity = intensity(result.x, result.y);
result.x = formula(result.x, multiplier, result.intensity);
result.y = formula(result.y, multiplier, result.intensity);
result.angle = Math.atan2(result.x, result.y) + ANGLE_OFFSET;
return result;
}
return undefined;
};
|
Update test to check all files created
|
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('ink generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('ink:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'package.json',
'bower.json',
'app',
'app/index.html',
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
'someOption': true
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
|
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('ink generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('ink:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
'someOption': true
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
|
Allow importing StdinStream from antlr4 package
|
from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.StdinStream import StdinStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import Parser
from antlr4.dfa.DFA import DFA
from antlr4.atn.ATN import ATN
from antlr4.atn.ATNDeserializer import ATNDeserializer
from antlr4.atn.LexerATNSimulator import LexerATNSimulator
from antlr4.atn.ParserATNSimulator import ParserATNSimulator
from antlr4.atn.PredictionMode import PredictionMode
from antlr4.PredictionContext import PredictionContextCache
from antlr4.ParserRuleContext import RuleContext, ParserRuleContext
from antlr4.tree.Tree import ParseTreeListener, ParseTreeVisitor, ParseTreeWalker, TerminalNode, ErrorNode, RuleNode
from antlr4.error.Errors import RecognitionException, IllegalStateException, NoViableAltException
from antlr4.error.ErrorStrategy import BailErrorStrategy
from antlr4.error.DiagnosticErrorListener import DiagnosticErrorListener
from antlr4.Utils import str_list
|
from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import Parser
from antlr4.dfa.DFA import DFA
from antlr4.atn.ATN import ATN
from antlr4.atn.ATNDeserializer import ATNDeserializer
from antlr4.atn.LexerATNSimulator import LexerATNSimulator
from antlr4.atn.ParserATNSimulator import ParserATNSimulator
from antlr4.atn.PredictionMode import PredictionMode
from antlr4.PredictionContext import PredictionContextCache
from antlr4.ParserRuleContext import RuleContext, ParserRuleContext
from antlr4.tree.Tree import ParseTreeListener, ParseTreeVisitor, ParseTreeWalker, TerminalNode, ErrorNode, RuleNode
from antlr4.error.Errors import RecognitionException, IllegalStateException, NoViableAltException
from antlr4.error.ErrorStrategy import BailErrorStrategy
from antlr4.error.DiagnosticErrorListener import DiagnosticErrorListener
from antlr4.Utils import str_list
|
Add tests for env serialization
|
from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
env={'foo': 'bar'},
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
assert result['env'] == {'foo': 'bar'}
assert result['script'] == command.script
|
from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
assert result['script'] == command.script
|
Set auto_init=True when creating new github repo through osf
|
# -*- coding: utf-8 -*-
import httplib as http
from flask import request
from github3 import GitHubError
from framework.exceptions import HTTPError
from framework.auth.decorators import must_be_logged_in
from website.project.decorators import must_have_addon
from ..api import GitHub
@must_be_logged_in
@must_have_addon('github', 'user')
def github_create_repo(**kwargs):
repo_name = request.json.get('name')
if not repo_name:
raise HTTPError(http.BAD_REQUEST)
user_settings = kwargs['user_addon']
connection = GitHub.from_settings(user_settings)
try:
repo = connection.create_repo(repo_name, auto_init=True)
except GitHubError:
# TODO: Check status code
raise HTTPError(http.BAD_REQUEST)
return {
'user': repo.owner.login,
'repo': repo.name,
}
|
# -*- coding: utf-8 -*-
import httplib as http
from flask import request
from github3 import GitHubError
from framework.exceptions import HTTPError
from framework.auth.decorators import must_be_logged_in
from website.project.decorators import must_have_addon
from ..api import GitHub
@must_be_logged_in
@must_have_addon('github', 'user')
def github_create_repo(**kwargs):
repo_name = request.json.get('name')
if not repo_name:
raise HTTPError(http.BAD_REQUEST)
user_settings = kwargs['user_addon']
connection = GitHub.from_settings(user_settings)
try:
repo = connection.create_repo(repo_name)
except GitHubError:
# TODO: Check status code
raise HTTPError(http.BAD_REQUEST)
return {
'user': repo.owner.login,
'repo': repo.name,
}
|
Make the front matter closing dashes matcher lazy
I was having a bit of trouble parsing several Markdown files with front matter, getting errors like these:
> Fatal error: JS-YAML: expected a single document in the stream, but found more
This was caused by Markdown headers like these:
Chapter IV: A new acquaintance
------------------------------
Since the plus in the `([\w\W]+)` is greedy, it eat the document all the way down to last instance of `---` in our document, which would the header.
The fix is to add a question mark, making the plus lazy, like this `([\w\W]+?)`. That causes only the front matter to be extracted.
|
var jsYaml = require('js-yaml')
, path = require('path')
, fs = require('fs')
jsYaml.parse = function (text, name) {
name = name || '__content';
var re = /^(-{3}(?:\n|\r)([\w\W]+?)-{3})?([\w\W]*)*/
, results = re.exec(text)
, conf = {}
, yamlOrJson;
if((yamlOrJson = results[2])) {
if(yamlOrJson.charAt(0) === '{') {
conf = JSON.parse(yamlOrJson);
} else {
conf = jsYaml.load(yamlOrJson);
}
}
conf[name] = results[3] ? results[3] : '';
return conf;
};
jsYaml.loadFront = function (context, name) {
var contents;
if(fs.existsSync(context)) {
contents = fs.readFileSync(context, 'utf8');
if (contents instanceof Error) return contents;
return jsYaml.parse(contents, name);
} else if (Buffer.isBuffer(context)) {
return jsYaml.parse(context.toString(), name);
} else {
return jsYaml.parse(context, name);
}
return false;
};
module.exports = jsYaml;
|
var jsYaml = require('js-yaml')
, path = require('path')
, fs = require('fs')
jsYaml.parse = function (text, name) {
name = name || '__content';
var re = /^(-{3}(?:\n|\r)([\w\W]+)-{3})?([\w\W]*)*/
, results = re.exec(text)
, conf = {}
, yamlOrJson;
if((yamlOrJson = results[2])) {
if(yamlOrJson.charAt(0) === '{') {
conf = JSON.parse(yamlOrJson);
} else {
conf = jsYaml.load(yamlOrJson);
}
}
conf[name] = results[3] ? results[3] : '';
return conf;
};
jsYaml.loadFront = function (context, name) {
var contents;
if(fs.existsSync(context)) {
contents = fs.readFileSync(context, 'utf8');
if (contents instanceof Error) return contents;
return jsYaml.parse(contents, name);
} else if (Buffer.isBuffer(context)) {
return jsYaml.parse(context.toString(), name);
} else {
return jsYaml.parse(context, name);
}
return false;
};
module.exports = jsYaml;
|
Adjust for pep8 package rename.
Closes #1
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2
try:
from pep8 import StandardReport, noqa
except ImportError:
# Try the new (as of 2016-June) pycodestyle package.
from pycodestyle import StandardReport, noqa
class RespectNoqaReport(StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
Stop adding database misses to output array.
|
from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
data = APP.Movie.get_data(movie)
if not data:
continue
records.append(data)
output(records)
|
from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
records.append(APP.Movie.get_data(movie))
output(records)
|
Remove unused modules, fix HTML response
|
#!/usr/bin/python
# Based on examples from
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
import cgi
import os
import cgitb
cgitb.enable()
CSV_DIR = '../csv/' # CSV upload directory
form = cgi.FieldStorage()
fileitem = form['filename'] # Get filename
# Check if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open(CSV_DIR + fn, 'wb').write(fileitem.file.read())
print 'Status: 204\r\n\r\n' # Success, don't reload page
else:
# Error, send a message
print """\
Status: 500\r
Content-Type: text/html;charset=UTF-8\r
<html>\r
<body>\r
<p>Error: No se subió el archivo.</p>\r
</body>\r
</html>\r
"""
|
#!/usr/bin/python
# Based on examples from
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
import sys
import cgi
import os
import cgitb
cgitb.enable()
CSV_DIR = '../csv/' # CSV upload directory
form = cgi.FieldStorage()
fileitem = form['filename'] # Get filename
# Check if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open(CSV_DIR + fn, 'wb').write(fileitem.file.read())
print 'Status: 204\r\n\r\n' # Success, don't reload page
else:
# Error, send a message
print """\
Status: 500\r\n
Content-Type: text/html;charset=UTF-8\n
<html>
<body>
<p>Error: No se subió el archivo.</p>
</body>
</html>
"""
|
Reorder assertions so more useful information generated on failure.
|
package co.arcs.groove.basking.test;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutionException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import co.arcs.groove.basking.Config;
import co.arcs.groove.basking.SyncService;
import co.arcs.groove.basking.task.SyncTask.Outcome;
public class SyncServiceTest {
private static final String USERNAME = "jka32muwfhqt3jf4qbubc8dp@mailinator.com";
private static final String PASSWORD = "jka32muwfhqt3jf4qbubc8dp";
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
@Test
public void syncTest() throws InterruptedException, ExecutionException {
Config config = new Config(USERNAME, PASSWORD, tempDir.getRoot());
Outcome outcome = new SyncService().start(config).get();
assertEquals(0, outcome.failedToDownload);
assertEquals(0, outcome.deleted);
assertEquals(2, outcome.downloaded);
}
}
|
package co.arcs.groove.basking.test;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutionException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import co.arcs.groove.basking.Config;
import co.arcs.groove.basking.SyncService;
import co.arcs.groove.basking.task.SyncTask.Outcome;
public class SyncServiceTest {
private static final String USERNAME = "jka32muwfhqt3jf4qbubc8dp@mailinator.com";
private static final String PASSWORD = "jka32muwfhqt3jf4qbubc8dp";
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
@Test
public void syncTest() throws InterruptedException, ExecutionException {
Config config = new Config(USERNAME, PASSWORD, tempDir.getRoot());
Outcome outcome = new SyncService().start(config).get();
assertEquals(0, outcome.deleted);
assertEquals(2, outcome.downloaded);
assertEquals(0, outcome.failedToDownload);
}
}
|
Fix the lunch URL for Byns Bistro
No change to the parser, the page format is completely changed so I
will handle it separately.
|
package net.rebworks.lunchy.domain.places;
import net.rebworks.lunchy.domain.Place;
import net.rebworks.lunchy.resources.LunchResource;
import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
public class BynsBistro implements Place {
private static final TreeSet<String> ALIASES = new TreeSet<>(Arrays.asList("byns", "bynsbistro"));
public static final String NAME = ALIASES.first();
final UriInfo uriInfo;
@Inject
public BynsBistro(@Context final UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
@Override
public String getName() {
return "Byns Bistro";
}
@Override
public SortedSet<String> getAliases() {
return ALIASES;
}
@Override
public URI getWebsite() {
return URI.create("https://www.bynsbistro.se/menyer");
}
@Override
public URI getUri() {
return LunchResource.getPlaceURI(uriInfo, NAME);
}
}
|
package net.rebworks.lunchy.domain.places;
import net.rebworks.lunchy.domain.Place;
import net.rebworks.lunchy.resources.LunchResource;
import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
public class BynsBistro implements Place {
private static final TreeSet<String> ALIASES = new TreeSet<>(Arrays.asList("byns", "bynsbistro"));
public static final String NAME = ALIASES.first();
final UriInfo uriInfo;
@Inject
public BynsBistro(@Context final UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
@Override
public String getName() {
return "Byns Bistro";
}
@Override
public SortedSet<String> getAliases() {
return ALIASES;
}
@Override
public URI getWebsite() {
return URI.create("http://www.bynsbistro.nu/veckans-lunch.aspx");
}
@Override
public URI getUri() {
return LunchResource.getPlaceURI(uriInfo, NAME);
}
}
|
Add @TypeQueryBean annotation into generation
|
package org.example.prototype.example;
import org.example.domain.Customer;
import org.example.domain.Order;
import org.example.domain.query.QCustomer;
import org.example.domain.query.QOrder;
import org.junit.Test;
import java.util.List;
/**
*/
public class ExampleQuery {
@Test
public void test() {
QCustomer qc = new QCustomer(5);
Customer rob = new QCustomer(2)
.select("id, name")
.id.greaterThan(42)
.status.equalTo(Customer.Status.GOOD)
.name.ilike("Asd")
.name.isNull()
.billingAddress.country.code.equalTo("NZ")
.contacts.email.endsWith("@foo.com")
.findUnique();
}
@Test
public void testOrder() {
List<Order> orders = new QOrder()
.customer.name.ilike("rob")
.orderBy()
.customer.name.asc()
.orderDate.asc()
.findList();
// .shippingAddress.city.ieq("auckla")
// .shippingAddress.country.code.eq("NZ")
// .status.equalTo(Order.Status.APPROVED)
// .orderDate.after(Date.valueOf("2015-01-20"))
// .findList();
}
}
|
package org.example.prototype.example;
import org.example.domain.Customer;
import org.example.domain.Order;
import org.example.domain.query.QCustomer;
import org.example.domain.query.QOrder;
import org.junit.Test;
import java.util.List;
/**
*/
public class ExampleQuery {
@Test
public void test() {
QCustomer qc = new QCustomer(5);
Customer rob = new QCustomer(2)
.select("id, name")
.status.equalTo(Customer.Status.GOOD)
.name.ilike("Asd")
.name.isNull()
.billingAddress.country.code.equalTo("NZ")
.contacts.email.endsWith("@foo.com")
.findUnique();
}
@Test
public void testOrder() {
List<Order> orders = new QOrder()
.customer.name.ilike("rob")
.orderBy()
.customer.name.asc()
.orderDate.asc()
.findList();
// .shippingAddress.city.ieq("auckla")
// .shippingAddress.country.code.eq("NZ")
// .status.equalTo(Order.Status.APPROVED)
// .orderDate.after(Date.valueOf("2015-01-20"))
// .findList();
}
}
|
Add support for Redux devtools
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
import { Provider } from 'react-redux';
import {
createStore,
combineReducers,
applyMiddleware
} from 'redux';
import thunk from 'redux-thunk';
import reducers from 'reducers';
import AppComponent from 'components/App';
import NotFoundComponent from 'components/NotFound';
let store = createStore(
combineReducers(reducers),
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
ReactDOM.render(
<Provider store={store}>
<Router>
<Switch>
<Route exact path="/" component={AppComponent} />
<Route component={NotFoundComponent} />
</Switch>
</Router>
</Provider>,
document.getElementById('root')
);
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
import { Provider } from 'react-redux';
import {
createStore,
combineReducers,
applyMiddleware
} from 'redux';
import thunk from 'redux-thunk';
import reducers from 'reducers';
import AppComponent from 'components/App';
import NotFoundComponent from 'components/NotFound';
let store = createStore(
combineReducers(reducers),
applyMiddleware(thunk)
);
ReactDOM.render(
<Provider store={store}>
<Router>
<Switch>
<Route exact path="/" component={AppComponent} />
<Route component={NotFoundComponent} />
</Switch>
</Router>
</Provider>,
document.getElementById('root')
);
|
Add some basic auth to reporting server
|
var http = require('http'),
express = require('express'),
db = require('../db');
var user = 'codebrag',
password = '_showmestats_';
function configureExpressApp() {
var app = express();
app.use(genericErrorHandler);
app.use(express.basicAuth(user, password));
app.use(express.static(__dirname + '/../../public'));
return app;
function genericErrorHandler(err, req, res, next) {
res.status(500);
res.json({ error: "Something went wrong with reports generation" });
}
}
function initializeRoutes(app, db) {
require('./reports_routes')(app, db);
}
function startServer(app) {
var port = 8080;
var httpServer = http.createServer(app);
httpServer.listen(port);
console.log("Codebrag reporting server started on port", port);
return httpServer;
}
db.initialize().then(function(db) {
var app = configureExpressApp();
initializeRoutes(app, db);
startServer(app);
}).done();
|
var http = require('http'),
express = require('express'),
db = require('../db');
function configureExpressApp() {
var app = express();
app.use(genericErrorHandler);
console.log(__dirname + '../../public');
app.use(express.static(__dirname + '/../../public'));
return app;
function genericErrorHandler(err, req, res, next) {
res.status(500);
res.json({ error: "Something went wrong with reports generation" });
}
}
function initializeRoutes(app, db) {
require('./reports_routes')(app, db);
}
function startServer(app) {
var port = 8080;
var httpServer = http.createServer(app);
httpServer.listen(port);
console.log("Codebrag reporting server started on port", port);
return httpServer;
}
db.initialize().then(function(db) {
var app = configureExpressApp();
initializeRoutes(app, db);
startServer(app);
}).done();
|
Add error param to diskspace callback.
diskspace 0.1.7 expects an error parameter as the first parameter of the callback (this is different from diskspace 0.1.5, which this plugi
n had been using previously).
https://github.com/keverw/diskspace.js/commit/d690faad01fdf76f001d85e92fb8a5e67eebaadc
|
var _param = require('./param.json');
var _du = require('diskspace');
var pollInterval = _param.pollInterval || 3000;
var c;
var smallestDev;
var smallest;
function checkFnc(dev)
{
return function(error, total, free, status)
{
if (!error) {
var perc = 1.0 - (free / total);
if (!smallest || smallest < perc)
{
smallest = perc;
smallestDev = dev;
}
if (!--c)
{
console.log('DISKUSE_SUMMARY %d', smallest);
}
} else {
--c;
}
}
}
function poll()
{
c = process.argv.length - 3;
smallestDev = null;
smallest = null;
for (var i = 3; i < process.argv.length; i++)
{
_du.check(process.argv[i], checkFnc(process.argv[i]));
}
}
setInterval(poll, pollInterval);
|
var _param = require('./param.json');
var _du = require('diskspace');
var pollInterval = _param.pollInterval || 3000;
var c;
var smallestDev;
var smallest;
function checkFnc(dev)
{
return function(total, free, status)
{
var perc = 1.0 - (free / total);
if (!smallest || smallest < perc)
{
smallest = perc;
smallestDev = dev;
}
if (!--c)
{
console.log('DISKUSE_SUMMARY %d', smallest);
}
}
}
function poll()
{
c = process.argv.length - 3;
smallestDev = null;
smallest = null;
for (var i = 3; i < process.argv.length; i++)
{
_du.check(process.argv[i], checkFnc(process.argv[i]));
}
}
setInterval(poll, pollInterval);
|
Throw exception if sequence generator not found
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Addressing\Model;
/**
* Province interface.
*
* @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
*/
interface ProvinceInterface
{
/**
* @return mixed
*/
public function getId();
/**
* @return string
*/
public function getName();
/**
* @param string $name
* @return $this
*/
public function setName($name);
/**
* @return string
*/
public function getIsoName();
/**
* @param string $isoName
* @return $this
*/
public function setIsoName($isoName);
/**
* @return CountryInterface
*/
public function getCountry();
/**
* @param CountryInterface $country
* @return $this
*/
public function setCountry(CountryInterface $country = null);
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Addressing\Model;
/**
* Province interface.
*
* @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
*/
interface ProvinceInterface
{
/**
* @return mixed
*/
public function getId();
/**
* @return string
*/
public function getName();
/**
* @param string $name
* @return $this
*/
public function setName($name);
/**
* @return string
*/
public function getIsoName();
/**
* @param string $isoName
* @return $this
*/
public function setIsoName($isoName);
/**
* @return CountryInterface
*/
public function getCountry();
/**
* @param CountryInterface $country
* @return $this
*/
public function setCountry(CountryInterface $country = null);
}
|
Change exception to die() in order to always show a message when these fatal errors are found
As proposed by @mahagr
|
<?php
namespace Grav;
// Ensure vendor libraries exist
$autoload = __DIR__ . '/vendor/autoload.php';
if (!is_file($autoload)) {
throw new \RuntimeException("Please run: <i>bin/grav install</i>");
}
use Grav\Common\Grav;
// Register the auto-loader.
$loader = require_once $autoload;
if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
die(sprintf('You are running PHP %s, but Grav needs at least <strong>PHP %s</strong> to run.', $ver, $req));
}
// Set timezone to default, falls back to system if php.ini not set
date_default_timezone_set(@date_default_timezone_get());
// Set internal encoding if mbstring loaded
if (extension_loaded('mbstring')) {
die("'mbstring' extension is not loaded. This is required for Grav to run correctly");
}
mb_internal_encoding('UTF-8');
// Get the Grav instance
$grav = Grav::instance(
array(
'loader' => $loader
)
);
// Process the page
try {
$grav->process();
} catch (\Exception $e) {
$grav->fireEvent('onFatalException');
throw $e;
}
|
<?php
namespace Grav;
// Ensure vendor libraries exist
$autoload = __DIR__ . '/vendor/autoload.php';
if (!is_file($autoload)) {
throw new \RuntimeException("Please run: <i>bin/grav install</i>");
}
use Grav\Common\Grav;
// Register the auto-loader.
$loader = require_once $autoload;
if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
throw new \RuntimeException(sprintf('You are running PHP %s, but Grav needs at least <strong>PHP %s</strong> to run.', $ver, $req));
}
// Set timezone to default, falls back to system if php.ini not set
date_default_timezone_set(@date_default_timezone_get());
// Set internal encoding if mbstring loaded
if (!extension_loaded('mbstring')) {
throw new \RuntimeException("'mbstring' extension is not loaded. This is required for Grav to run correctly");
}
mb_internal_encoding('UTF-8');
// Get the Grav instance
$grav = Grav::instance(
array(
'loader' => $loader
)
);
// Process the page
try {
$grav->process();
} catch (\Exception $e) {
$grav->fireEvent('onFatalException');
throw $e;
}
|
tests: Add Chrome path for Windows
|
var browserify = require('browserify')
var cp = require('child_process')
var envify = require('envify/custom')
var fs = require('fs')
var once = require('once')
var path = require('path')
var CHROME
if (process.env.CHROME) {
CHROME = process.env.CHROME
} else if (process.platform === 'win32') {
CHROME = '"%ProgramFiles(x86)%\\Google\\Chrome\\Application\\chrome.exe"'
} else {
CHROME = '/Applications/Google\\ Chrome\\ Canary.app/Contents/MacOS/Google\\ Chrome\\ Canary'
}
var BUNDLE_PATH = path.join(__dirname, 'chrome-app/bundle.js')
exports.browserify = function (filename, env, cb) {
if (!env) env = {}
if (!cb) cb = function () {}
cb = once(cb)
var b = browserify()
b.add(path.join(__dirname, 'client', filename))
b.transform(envify(env))
b.bundle()
.pipe(fs.createWriteStream(BUNDLE_PATH))
.on('close', cb)
.on('error', cb)
}
exports.launchBrowser = function () {
// chrome 40.0.2188.2 won't open extensions without absolute path.
var app = path.join(__dirname, '..', 'test/chrome-app')
var command = CHROME + ' --load-and-launch-app=' + app
var env = { cwd: path.join(__dirname, '..') }
return cp.exec(command, env, function () {})
}
|
var browserify = require('browserify')
var cp = require('child_process')
var envify = require('envify/custom')
var fs = require('fs')
var once = require('once')
var path = require('path')
var CHROME = process.env.CHROME || '/Applications/Google\\ Chrome\\ Canary.app/Contents/MacOS/Google\\ Chrome\\ Canary'
var BUNDLE_PATH = path.join(__dirname, 'chrome-app/bundle.js')
exports.browserify = function (filename, env, cb) {
if (!env) env = {}
if (!cb) cb = function () {}
cb = once(cb)
var b = browserify()
b.add(path.join(__dirname, 'client', filename))
b.transform(envify(env))
b.bundle()
.pipe(fs.createWriteStream(BUNDLE_PATH))
.on('close', cb)
.on('error', cb)
}
exports.launchBrowser = function () {
// chrome 40.0.2188.2 won't open extensions without absolute path.
var app = path.join(__dirname, '..', 'test/chrome-app')
var command = CHROME + ' --load-and-launch-app=' + app
var env = { cwd: path.join(__dirname, '..') }
return cp.exec(command, env, function () {})
}
|
Sort vacation type by id when displaying on home page
|
# -*- coding: utf-8 -*-
from .base import RedirectView
from pyvac.models import VacationType
class Index(RedirectView):
redirect_route = u'login'
class Home(RedirectView):
redirect_route = u'login'
def render(self):
if not self.user:
return self.redirect()
ret_dict = {'types': [vac.name for vac in
VacationType.find(self.session,
order_by=[VacationType.id])]}
if self.request.matched_route:
matched_route = self.request.matched_route.name
ret_dict.update({'matched_route': matched_route,
'csrf_token': self.request.session.get_csrf_token()})
return ret_dict
ret_dict.update({'csrf_token': self.request.session.get_csrf_token()})
return ret_dict
|
# -*- coding: utf-8 -*-
from .base import RedirectView
from pyvac.models import VacationType
class Index(RedirectView):
redirect_route = u'login'
class Home(RedirectView):
redirect_route = u'login'
def render(self):
if not self.user:
return self.redirect()
ret_dict = {'types': [vac.name for vac in
VacationType.find(self.session,
order_by=[VacationType.name])]}
if self.request.matched_route:
matched_route = self.request.matched_route.name
ret_dict.update({'matched_route': matched_route,
'csrf_token': self.request.session.get_csrf_token()})
return ret_dict
ret_dict.update({'csrf_token': self.request.session.get_csrf_token()})
return ret_dict
|
Change from array_pop to array_shift for returning the 'default' transformer
|
<?php
declare(strict_types=1);
namespace Onion\REST;
use \Onion\Framework\Http\Header\Accept;
use \Onion\REST\Transformers\Interfaces\TransformerInterface;
class TransformerContainer
{
/**
* @var TransformerInterface
*/
private $strategies = [];
/**
* @param TransformerInterface[] $strategies
*/
public function __construct(array $transformers)
{
$this->strategies = $stransformers;
}
public function getDefaultTransformer(): TransformerInterface
{
return array_shift$this->strategies);
}
public function negotiateTransformer(Accept $accept): TransformerInterface
{
$list = [];
foreach ($this->strategies as $type => $strategy) {
if ($header->supports($type)) {
$list[$header->getPriority($type)] = $strategy;
}
}
if ($list === []) {
return $this->getDefaultTransformer();
}
return array_pop($list);
}
}
|
<?php
declare(strict_types=1);
namespace Onion\REST;
use \Onion\Framework\Http\Header\Accept;
use \Onion\REST\Transformers\Interfaces\TransformerInterface;
class TransformerContainer
{
/**
* @var TransformerInterface
*/
private $strategies = [];
/**
* @param TransformerInterface[] $strategies
*/
public function __construct(array $transformers)
{
$this->strategies = $stransformers;
}
public function getDefaultTransformer(): TransformerInterface
{
return array_pop($this->strategies);
}
public function negotiateTransformer(Accept $accept): TransformerInterface
{
$list = [];
foreach ($this->strategies as $type => $strategy) {
if ($header->supports($type)) {
$list[$header->getPriority($type)] = $strategy;
}
}
if ($list === []) {
return $this->getDefaultTransformer();
}
return array_pop($list);
}
}
|
Fix GitHub link in footer
|
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link href="microcms.css" rel="stylesheet" />
<title>MicroCMS - Home</title>
</head>
<body>
<header>
<h1>MicroCMS</h1>
</header>
<?php foreach ($articles as $article): ?>
<article>
<h2><?php echo $article['art_title'] ?></h2>
<p><?php echo $article['art_content'] ?></p>
</article>
<?php endforeach; ?>
<footer class="footer">
<a href="https://github.com/bpesquet/OC-MicroCMS">MicroCMS</a> is a minimalistic CMS built as a showcase for modern PHP development.
</footer>
</body>
</html>
|
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link href="microcms.css" rel="stylesheet" />
<title>MicroCMS - Home</title>
</head>
<body>
<header>
<h1>MicroCMS</h1>
</header>
<?php foreach ($articles as $article): ?>
<article>
<h2><?php echo $article['art_title'] ?></h2>
<p><?php echo $article['art_content'] ?></p>
</article>
<?php endforeach; ?>
<footer class="footer">
<a href="https://github.com/bpesquet/MicroCMS">MicroCMS</a> is a minimalistic CMS built as a showcase for modern PHP development.
</footer>
</body>
</html>
|
Add game message to play attachment
|
const BaseAbility = require('./baseability.js');
const Costs = require('./costs.js');
class PlayAttachmentAction extends BaseAbility {
constructor() {
super({
cost: [
Costs.payReduceableFateCost('play'),
Costs.playLimited()
],
target: {
cardCondition: (card, context) => context.source.owner.canAttach(context.source, card)
}
});
this.title = 'PlayAttachmentAction';
}
meetsRequirements(context) {
return (
context.game.currentPhase !== 'dynasty' &&
context.source.getType() === 'attachment' &&
context.source.location === 'hand' &&
context.source.canPlay()
);
}
executeHandler(context) {
context.player.attach(context.source, context.target);
context.game.addMessage('0} plays {1}, attaching it to {2}', context.player, context.source, context.target);
}
isCardPlayed() {
return true;
}
isCardAbility() {
return false;
}
}
module.exports = PlayAttachmentAction;
|
const BaseAbility = require('./baseability.js');
const Costs = require('./costs.js');
class PlayAttachmentAction extends BaseAbility {
constructor() {
super({
cost: [
Costs.payReduceableFateCost('play'),
Costs.playLimited()
],
target: {
cardCondition: (card, context) => context.source.owner.canAttach(context.source, card)
}
});
this.title = 'PlayAttachmentAction';
}
meetsRequirements(context) {
return (
context.game.currentPhase !== 'dynasty' &&
context.source.getType() === 'attachment' &&
context.source.location === 'hand' &&
context.source.canPlay()
);
}
executeHandler(context) {
context.player.attach(context.source, context.target);
}
isCardPlayed() {
return true;
}
isCardAbility() {
return false;
}
}
module.exports = PlayAttachmentAction;
|
Change the message on completion to connect server.
|
package com.samsung.sec.dexter.executor.peerreview.cli;
import com.samsung.sec.dexter.core.util.DexterServerConfig;
import com.samsung.sec.dexter.core.util.IDexterClient;
public class HomeJsonCLIServerCheckState implements IHomeJsonCLIState {
@Override
public void doAction(PeerReviewHomeJsonCLI homeJsonCLI) {
IDexterClient dexterClient = homeJsonCLI.createDexterClient();
System.out.print("Connecting server...");
if (dexterClient.isServerAlive("test")) {
System.out.println("\rCompleted to connect server.");
homeJsonCLI.setState(new HomeJsonCLIHomeState());
} else {
System.out.println("\rCan't connect server (" +
dexterClient.getServerHost() + ":" + dexterClient.getServerPort() + ")");
homeJsonCLI.setState(new HomeJsonCLIHostnameState());
}
}
}
|
package com.samsung.sec.dexter.executor.peerreview.cli;
import com.samsung.sec.dexter.core.util.DexterServerConfig;
import com.samsung.sec.dexter.core.util.IDexterClient;
public class HomeJsonCLIServerCheckState implements IHomeJsonCLIState {
@Override
public void doAction(PeerReviewHomeJsonCLI homeJsonCLI) {
IDexterClient dexterClient = homeJsonCLI.createDexterClient();
System.out.print("Connecting server...");
if (dexterClient.isServerAlive("test")) {
System.out.println("\rCompleted.");
homeJsonCLI.setState(new HomeJsonCLIHomeState());
} else {
System.out.println("\rCan't connect server (" +
dexterClient.getServerHost() + ":" + dexterClient.getServerPort() + ")");
homeJsonCLI.setState(new HomeJsonCLIHostnameState());
}
}
}
|
Remove self references from setup/teardown
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
"""
import os
import shutil
import pytest
@pytest.fixture(scope='function')
def back_up_rc(request):
"""
Back up an existing cookiecutter rc and restore it after the test.
If ~/.cookiecutterrc is pre-existing, move it to a temp location
"""
user_config_path = os.path.expanduser('~/.cookiecutterrc')
user_config_path_backup = os.path.expanduser(
'~/.cookiecutterrc.backup'
)
if os.path.exists(user_config_path):
shutil.copy(user_config_path, user_config_path_backup)
os.remove(user_config_path)
def restore_rc():
"""
If it existed, restore ~/.cookiecutterrc
"""
if os.path.exists(user_config_path_backup):
shutil.copy(user_config_path_backup, user_config_path)
os.remove(user_config_path_backup)
request.addfinalizer(restore_rc)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
"""
import pytest
@pytest.fixture(scope='function')
def back_up_rc(request):
"""
Back up an existing cookiecutter rc and restore it after the test.
If ~/.cookiecutterrc is pre-existing, move it to a temp location
"""
self.user_config_path = os.path.expanduser('~/.cookiecutterrc')
self.user_config_path_backup = os.path.expanduser(
'~/.cookiecutterrc.backup'
)
if os.path.exists(self.user_config_path):
shutil.copy(self.user_config_path, self.user_config_path_backup)
os.remove(self.user_config_path)
def restore_rc():
"""
If it existed, restore ~/.cookiecutterrc
"""
if os.path.exists(self.user_config_path_backup):
shutil.copy(self.user_config_path_backup, self.user_config_path)
os.remove(self.user_config_path_backup)
request.addfinalizer(restore_rc)
|
Fix for scalable option bug, pointed out by Jason Smith.
|
<?php
# $Id$
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#
if (! Gmetad($ganglia_ip, $ganglia_port) )
{
print "<H4>There was an error collecting ganglia data ".
"($ganglia_ip:$ganglia_port): $error</H4>\n";
exit;
}
# If we have no child data sources, assume something is wrong.
if (!count($grid) and !count($cluster))
{
print "<H4>Ganglia cannot find a data source. Is gmond running?</H4>";
exit;
}
# If we only have one cluster source, suppress MetaCluster output.
if (count($grid) == 2 and $context=="meta")
{
# Lets look for one cluster (the other is our grid).
foreach($grid as $source)
if ($source[CLUSTER])
{
$standalone = 1;
$context = "cluster";
# Need to refresh data with new context.
Gmetad($ganglia_ip, $ganglia_port);
$clustername = $source[NAME];
}
}
?>
|
<?php
# $Id$
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#
if (! Gmetad($ganglia_ip, $ganglia_port) )
{
print "<H4>There was an error collecting ganglia data ".
"($ganglia_ip:$ganglia_port): $error</H4>\n";
exit;
}
# If we have no child data sources, assume something is wrong.
if (!count($grid))
{
print "<H4>Ganglia cannot find a data source. Is gmond running?</H4>";
exit;
}
# If we only have one cluster source, suppress MetaCluster output.
if (count($grid) == 2 and $context=="meta")
{
# Lets look for one cluster (the other is our grid).
foreach($grid as $source)
if ($source[CLUSTER])
{
$standalone = 1;
$context = "cluster";
# Need to refresh data with new context.
Gmetad($ganglia_ip, $ganglia_port);
$clustername = $source[NAME];
}
}
?>
|
Return __RequestVerificationToken cookie if it exists
|
// Dependencies
var url = require('url');
// Includes
var http = require('./http.js').func;
var getHash = require('./getHash.js').func;
var getVerificationInputs = require('./getVerificationInputs.js').func;
var cache = require('../cache');
// Args
exports.required = ['url'];
exports.optional = ['ignoreCache', 'getBody', 'jar'];
// Define
function getVerification (jar, url, getBody) {
var httpOpt = {
url: url,
options: {
resolveWithFullResponse: true,
jar: jar
}
};
return http(httpOpt)
.then(function (res) {
var inputs = getVerificationInputs({html: res.body});
var match;
if (res.headers && res.headers['set-cookie']) {
match = res.headers['set-cookie'].toString().match(/__RequestVerificationToken=(.*?);/);
}
return {
body: (getBody ? res.body : null),
inputs: inputs,
header: match && match[1]
};
});
}
exports.func = function (args) {
var jar = args.jar;
if (args.ignoreCache) {
return getVerification(jar, args.url, args.getBody);
} else {
return cache.wrap('Verify', url.parse(args.url).pathname + getHash({jar: jar}), function () {
return getVerification(jar, args.url, args.getBody);
});
}
};
|
// Dependencies
var url = require('url');
// Includes
var http = require('./http.js').func;
var getHash = require('./getHash.js').func;
var getVerificationInputs = require('./getVerificationInputs.js').func;
var cache = require('../cache');
// Args
exports.required = ['url'];
exports.optional = ['ignoreCache', 'getBody', 'jar'];
// Define
function getVerification (jar, url, getBody) {
var httpOpt = {
url: url,
options: {
jar: jar
}
};
return http(httpOpt)
.then(function (body) {
var inputs = getVerificationInputs({html: body});
return {
body: (getBody ? body : null),
inputs: inputs
};
});
}
exports.func = function (args) {
var jar = args.jar;
if (args.ignoreCache) {
return getVerification(jar, args.url, args.getBody);
} else {
return cache.wrap('Verify', url.parse(args.url).pathname + getHash({jar: jar}), function () {
return getVerification(jar, args.url, args.getBody);
});
}
};
|
Change to make BEM solution from mne-C
|
from __future__ import print_function
import mne
import subprocess
from my_settings import *
subject = sys.argv[1]
cmd = "/usr/local/common/meeg-cfin/configurations/bin/submit_to_isis"
# make source space
src = mne.setup_source_space(subject, spacing='oct6',
subjects_dir=subjects_dir,
add_dist=False, overwrite=True)
# save source space
mne.write_source_spaces(mne_folder + "%s-oct-6-src.fif" % subject, src)
setup_forward = "mne_setup_forward_model --subject %s --surf --ico -6" % (
subject)
subprocess.call([cmd, "1", setup_forward])
# conductivity = (0.3, 0.006, 0.3) # for three layers
# model = mne.make_bem_model(subject=subject, ico=None,
# conductivity=conductivity,
# subjects_dir=subjects_dir)
# bem = mne.make_bem_solution(model)
# mne.write_bem_solution(mne_folder + "%s-8194-bem-sol.fif" % subject)
|
from __future__ import print_function
import mne
from my_settings import *
subject = sys.argv[1]
# make source space
src = mne.setup_source_space(subject, spacing='oct6',
subjects_dir=subjects_dir,
add_dist=False, overwrite=True)
# save source space
mne.write_source_spaces(mne_folder + "%s-oct6-src.fif" % subject, src)
conductivity = (0.3, 0.006, 0.3) # for three layers
model = mne.make_bem_model(subject=subject, ico=None,
conductivity=conductivity,
subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)
mne.write_bem_solution(mne_folder + "%s-8194-bem-sol.fif" % subject)
|
Set artisan binary in console kernel
|
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\App\Console\Commands\CacheRMData::class,
];
public function __construct(Application $app, Dispatcher $events)
{
define('ARTISAN_BINARY', 'bin/artisan');
parent::__construct($app, $events);
}
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('app:cachermdata')
->everyFiveMinutes();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('app/routes/console.php');
}
}
|
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\App\Console\Commands\CacheRMData::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('app:cachermdata')
->everyFiveMinutes();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('app/routes/console.php');
}
}
|
Remove comma at end of line when there are no other items in the array.
|
var path = require('path');
var webpack = require('webpack');
module.exports = function(fabricatorConfig) {
"use strict";
var config = {
entry: {
'fabricator/scripts/f': fabricatorConfig.src.scripts.fabricator,
'toolkit/scripts/toolkit': fabricatorConfig.src.scripts.toolkit
},
output: {
path: path.resolve(__dirname, fabricatorConfig.dest, 'assets'),
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|prism\.js)/,
loaders: ['babel-loader']
}
]
},
plugins: [],
cache: {}
};
if (!fabricatorConfig.dev) {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
return config;
};
|
var path = require('path');
var webpack = require('webpack');
module.exports = function(fabricatorConfig) {
"use strict";
var config = {
entry: {
'fabricator/scripts/f': fabricatorConfig.src.scripts.fabricator,
'toolkit/scripts/toolkit': fabricatorConfig.src.scripts.toolkit,
},
output: {
path: path.resolve(__dirname, fabricatorConfig.dest, 'assets'),
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|prism\.js)/,
loaders: ['babel-loader']
}
]
},
plugins: [],
cache: {}
};
if (!fabricatorConfig.dev) {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
return config;
};
|
Change the adapter set id
|
/*
Copyright 2014 Weswit Srl
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.
*/
//////////////// Connect to current host (or localhost) and configure a StatusWidget
define(["LightstreamerClient","StatusWidget"],function(LightstreamerClient,StatusWidget) {
var protocolToUse = document.location.protocol != "file:" ? document.location.protocol : "http:";
var portToUse = document.location.protocol == "https:" ? "443" : "8080";
// in accordance with the port configuration in the factory lightstreamer_conf.xml
// (although the https port is not open by the factory lightstreamer_conf.xml)
var lsClient = new LightstreamerClient(protocolToUse+"//localhost:"+portToUse,"FULLPORTFOLIODEMO");
lsClient.connectionSharing.enableSharing("PortfolioDemoCommonConnection", "ATTACH", "CREATE");
lsClient.addListener(new StatusWidget("left", "0px", true));
lsClient.connect();
return lsClient;
});
|
/*
Copyright 2014 Weswit Srl
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.
*/
//////////////// Connect to current host (or localhost) and configure a StatusWidget
define(["LightstreamerClient","StatusWidget"],function(LightstreamerClient,StatusWidget) {
var protocolToUse = document.location.protocol != "file:" ? document.location.protocol : "http:";
var portToUse = document.location.protocol == "https:" ? "443" : "8080";
// in accordance with the port configuration in the factory lightstreamer_conf.xml
// (although the https port is not open by the factory lightstreamer_conf.xml)
var lsClient = new LightstreamerClient(protocolToUse+"//localhost:"+portToUse,"DEMO");
lsClient.connectionSharing.enableSharing("PortfolioDemoCommonConnection", "ATTACH", "CREATE");
lsClient.addListener(new StatusWidget("left", "0px", true));
lsClient.connect();
return lsClient;
});
|
Add EventLog stuff to package-level exports
|
__version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, StaticIdProvider, \
KeyBuilder, StringDelimitedKeyBuilder, Database, FileSystemDatabase, \
InMemoryDatabase
from datawriter import DataWriter
from database_iterator import DatabaseIterator
from encoder import IdentityEncoder
from decoder import Decoder
from lmdbstore import LmdbDatabase
from objectstore import ObjectStoreDatabase
from persistence import PersistenceSettings
from iteratornode import IteratorNode
from eventlog import EventLog, RedisChannel
try:
from nmpy import NumpyEncoder, PackedNumpyEncoder, StreamingNumpyDecoder, \
BaseNumpyDecoder, NumpyMetaData, NumpyFeature
except ImportError:
pass
|
__version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, StaticIdProvider, \
KeyBuilder, StringDelimitedKeyBuilder, Database, FileSystemDatabase, \
InMemoryDatabase
from datawriter import DataWriter
from database_iterator import DatabaseIterator
from encoder import IdentityEncoder
from decoder import Decoder
from lmdbstore import LmdbDatabase
from objectstore import ObjectStoreDatabase
from persistence import PersistenceSettings
from iteratornode import IteratorNode
try:
from nmpy import NumpyEncoder, PackedNumpyEncoder, StreamingNumpyDecoder, \
BaseNumpyDecoder, NumpyMetaData, NumpyFeature
except ImportError:
pass
|
Fix transmission task for torrent files
|
# -*- coding: utf-8 -*-
from tempfile import NamedTemporaryFile
from rpihelper.celery import current_app, celery
from rpihelper.dropboxclient.logic import Client as DropBoxClient
from rpihelper.transmission.logic import (
transmissionrpc_client, transmissionrpc_add_torrent,
)
__all__ = (
'check_torrent_files',
)
@celery.task
def check_torrent_files():
tc = transmissionrpc_client()
if not tc:
current_app.logger.info('No connetion to remote transmission, stop task.')
return
dbc = DropBoxClient()
for f in dbc.folder(current_app.config['TRANSMISSION_DROPBOX_TORRENTS_FOLDER']):
with NamedTemporaryFile() as tf:
tf.write(dbc.file(f))
success = transmissionrpc_add_torrent(tc, 'file://%s' % tf.name)
if success:
dbc.rm_file(f)
current_app.logger.info('Successfully added torrent "%s".' % f)
else:
current_app.logger.info('Torrent "%s" not added, skip it.' % f)
|
# -*- coding: utf-8 -*-
from rpihelper.celery import current_app, celery
from rpihelper.dropboxclient.logic import Client as DropBoxClient
from rpihelper.transmission.logic import (
transmissionrpc_client, transmissionrpc_add_torrent,
)
__all__ = (
'check_torrent_files',
)
@celery.task
def check_torrent_files():
tc = transmissionrpc_client()
if not tc:
current_app.logger.info('No connetion to remote transmission, stop task.')
return
dbc = DropBoxClient()
for f in dbc.folder(current_app.config['TRANSMISSION_DROPBOX_TORRENTS_FOLDER']):
file_url = dbc.file_url(f)
success = transmissionrpc_add_torrent(tc, file_url)
if success:
dbc.rm_file(f)
current_app.logger.info('Successfully added torrent "%s".' % file_url)
else:
current_app.logger.info('Torrent "%s" not added, skip it.' % file_url)
|
Add border bottom to divs.
|
import inputData from './data.js';
import infiniteDivs from '../../lib/infinitedivs.js';
let rootElement = document.body;
function divGenerator(item) {
let div = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span');
img.setAttribute('src', item.img);
img.setAttribute('style', 'vertical-align: middle; height: 50px; width: 50px; margin: 20px');
img.setAttribute('alt', 'avatar');
span.textContent = item.name;
span.setAttribute('style', 'text-decoration: underline');
div.setAttribute('style', 'border-bottom: 1px dotted');
div.appendChild(img);
div.appendChild(span);
return div;
}
let dataArray = inputData;
let config = {
bufferMultiplier: 2,
dataArray,
divGenerator,
divHeight: 90,
rootElement
};
let infinitedivs = new infiniteDivs(config);
function scrollListener() {
infinitedivs.viewDoctor();
};
document.addEventListener('scroll', scrollListener);
|
import inputData from './data.js';
import infiniteDivs from '../../lib/infinitedivs.js';
let rootElement = document.body;
function divGenerator(item) {
let div = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span');
img.setAttribute('src', item.img);
img.setAttribute('style', 'vertical-align: middle; height: 50px; width: 50px; margin: 20px');
img.setAttribute('alt', 'avatar');
span.textContent = item.name;
span.setAttribute('style', 'text-decoration: underline');
div.appendChild(img);
div.appendChild(span);
return div;
}
let dataArray = inputData;
let config = {
bufferMultiplier: 2,
dataArray,
divGenerator,
divHeight: 90,
rootElement
};
let infinitedivs = new infiniteDivs(config);
function scrollListener() {
infinitedivs.viewDoctor();
};
document.addEventListener('scroll', scrollListener);
|
Add lint rule to ESLint rule namespace
|
'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace rules
*/
var rules = {};
/**
* @name empty-line-before-comment
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/empty-line-before-comment}
*/
setReadOnly( rules, 'empty-line-before-comment', require( '@stdlib/_tools/eslint/rules/empty-line-before-comment') );
/**
* @name no-internal-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-internal-require}
*/
setReadOnly( rules, 'no-internal-require', require( '@stdlib/_tools/eslint/rules/no-internal-require') );
/**
* @name require-typed-arrays
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/require-typed-arrays}
*/
setReadOnly( rules, 'require-typed-arrays', require( '@stdlib/_tools/eslint/rules/require-typed-arrays') );
// EXPORTS //
module.exports = rules;
|
'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace rules
*/
var rules = {};
/**
* @name empty-line-before-comment
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/empty-line-before-comment}
*/
setReadOnly( rules, 'empty-line-before-comment', require( '@stdlib/_tools/eslint/rules/empty-line-before-comment') );
/**
* @name no-internal-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-internal-require}
*/
setReadOnly( rules, 'no-internal-require', require( '@stdlib/_tools/eslint/rules/no-internal-require') );
// EXPORTS //
module.exports = rules;
|
Remove unused imports
Fix indentation
|
package guitests;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import org.junit.Test;
import seedu.ezdo.logic.commands.SaveCommand;
public class SaveCommandTest extends EzDoGuiTest {
private final String validDirectory = "data/test.xml";
private final String inexistentDirectory = "data/COWABUNGA/";
@Test
public void save_validDirectory_success() {
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS, validDirectory));
}
@Test
public void save_invalidFormat_failure() {
commandBox.runCommand("save");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE));
}
@Test
public void save_inexistentDirectory_failure() {
commandBox.runCommand("save " + inexistentDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_DOES_NOT_EXIST));
}
}
|
package guitests;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.io.IOException;
import org.junit.Test;
import seedu.ezdo.logic.commands.SaveCommand;
public class SaveCommandTest extends EzDoGuiTest {
private final String validDirectory = "data/test.xml";
private final String inexistentDirectory = "data/COWABUNGA/";
@Test
public void save_validDirectory_success() {
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS, validDirectory));
}
@Test
public void save_invalidFormat_failure() {
commandBox.runCommand("save");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE));
}
@Test
public void save_inexistentDirectory_failure() {
commandBox.runCommand("save " + inexistentDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_DOES_NOT_EXIST));
}
}
|
Add dataContext to postsLimit route
|
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return Meteor.subscribe('notifications');
}
});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return Meteor.subscribe('comments', this.params._id);
},
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
Router.route('/:postsLimit?', {
name: 'postsList',
waitOn: function() {
var limit = parseInt(this.params.postsLimit) || 5;
return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit });
},
data: function() {
var limit = parseInt(this.params.postsLimit) || 5;
return {
posts: Posts.find({}, { sort: { submitted: -1 }, limit: limit });
}
}
});
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
|
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return Meteor.subscribe('notifications');
}
});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return Meteor.subscribe('comments', this.params._id);
},
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
Router.route('/:postsLimit?', {
name: 'postsList',
waitOn: function() {
var limit = parseInt(this.params.postsLimit) || 5;
return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit });
}
});
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
|
Add key property to paths list items
|
var rb = require('react-bootstrap');
var React = require('react');
var _ = require('lodash');
var Table = rb.Table,
tr = rb.tr,
td =rb.td,
form = rb.form,
Input = rb.Input;
var WidgetRow = React.createClass({
render: function() {
return (
<tr>
<td><Input type="checkbox" label=" " checked={this.props.widget.options.active} onChange={this.toggleActive}/></td>
<td>{this.props.widget.getType()}</td>
<td style={{"height":"16vh", "width":"16vw"}}>{this.props.widget.getReactElement()}</td>
<td><ul>{this.props.widget.getHandledPaths().map(function(path, i){
return <li key={i}>{path}</li>
})}</ul></td>
</tr>
);
},
toggleActive: function() {
this.props.widget.setActive(!this.props.widget.options.active);
}
});
module.exports = WidgetRow;
|
var rb = require('react-bootstrap');
var React = require('react');
var _ = require('lodash');
var Table = rb.Table,
tr = rb.tr,
td =rb.td,
form = rb.form,
Input = rb.Input;
var WidgetRow = React.createClass({
render: function() {
return (
<tr>
<td><Input type="checkbox" label=" " checked={this.props.widget.options.active} onChange={this.toggleActive}/></td>
<td>{this.props.widget.getType()}</td>
<td style={{"height":"16vh", "width":"16vw"}}>{this.props.widget.getReactElement()}</td>
<td><ul>{this.props.widget.getHandledPaths().map(function(path){
return <li>{path}</li>
})}</ul></td>
</tr>
);
},
toggleActive: function() {
this.props.widget.setActive(!this.props.widget.options.active);
}
});
module.exports = WidgetRow;
|
Fix tests to delete the _site directory after running.
|
var fs = require('fs')
, path = require('path')
, expect = require('chai').expect
, shell = require('shelljs')
, glob = require('glob')
, _ = require('lodash')
function read(filename) {
return fs.readFileSync(filename, 'utf8')
}
function fixture(name) {
return read('test/fixtures/' + name + '.html')
}
function clean() {
shell.rm('-rf', 'test/src/_site');
}
function filesOnly(file) {
return fs.statSync(file).isFile()
}
describe('torpedo', function() {
beforeEach(clean)
after(clean)
describe('build', function() {
it('should build the site', function(done) {
var spawn = require('child_process').spawn
, child = spawn('torpedo', ['build'], {cwd: 'test/src'})
child.on('close', function() {
var generatedFiles = glob.sync('test/src/_site/**/*').filter(filesOnly)
, expectedFiles = glob.sync('test/expected/**/*').filter(filesOnly)
_.times(expectedFiles.length, function(i) {
expect(read(expectedFiles[i])).to.equal(read(generatedFiles[i]))
})
done()
})
})
})
})
|
var fs = require('fs')
, path = require('path')
, expect = require('chai').expect
, shell = require('shelljs')
, glob = require('glob')
, _ = require('lodash')
function read(filename) {
return fs.readFileSync(filename, 'utf8')
}
function fixture(name) {
return read('test/fixtures/' + name + '.html')
}
function readGenerated(filename, destination) {
var loc = path.resolve(destination || '_site', filename)
return read(loc, 'utf8').trim()
}
function readExpected(filename) {
var loc = path.resolve('../expected', filename)
return read(loc, 'utf8').trim()
}
function clean() {
shell.rm('-rf', '_site');
}
function filesOnly(file) {
return fs.statSync(file).isFile()
}
describe('torpedo', function() {
beforeEach(clean)
after(clean)
describe('build', function() {
it('should build the site', function(done) {
var spawn = require('child_process').spawn
, child = spawn('torpedo', ['build'], {cwd: 'test/src'})
child.on('close', function() {
var generatedFiles = glob.sync('test/src/_site/**/*').filter(filesOnly)
, expectedFiles = glob.sync('test/expected/**/*').filter(filesOnly)
_.times(expectedFiles.length, function(i) {
expect(read(expectedFiles[i])).to.equal(read(generatedFiles[i]))
})
done()
})
})
})
})
|
Create autostart folder for tests
|
import os
from unittest import TestCase
import requests
from furikura import utils
def test_request():
requests.get('https://example.com')
class TestUtils(TestCase):
def test_get_file(self):
self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile")
def test_check_connection(self):
self.addTypeEqualityFunc(type, utils.check_connection(test_request))
def test_autostart(self):
os.makedirs(os.path.expanduser('~/.config/autostart/'), exist_ok=True)
utils.autostart('add')
self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
utils.autostart('remove')
self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
|
import os
from unittest import TestCase
import requests
from furikura import utils
def test_request():
requests.get('https://example.com')
class TestUtils(TestCase):
def test_get_file(self):
self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile")
def test_check_connection(self):
self.addTypeEqualityFunc(type, utils.check_connection(test_request))
def test_autostart(self):
utils.autostart('add')
self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
utils.autostart('remove')
self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
|
Support include-all's capability of optional vs. required includes.
|
var _ = require('underscore');
module.exports = {
required: function(options) {
return buildDictionary(options);
},
optional: function(options) {
options.optional = true;
return buildDictionary(options);
}
};
// buildDictionary ()
// Go through each object, include the code, and determine its identity.
// Tolerates non-existent files/directories by ignoring them.
//
// @dirname :: the path to the source directory
// @filter :: the filter regex
// $replaceExpr :: the replace regex
// @optional :: if optional, don't throw an error if nothing is found
function buildDictionary(options) {
var files = require('include-all')({
dirname: options.dirname,
filter: options.filter,
optional: options.optional
});
var objects = {};
_.each(files, function(object, filename) {
// If no 'identity' attribute was provided,
// take a guess based on the (case-insensitive) filename
if(!object.identity) {
object.identity = options.replaceExpr ? filename.replace(options.replaceExpr, "") : filename;
object.identity = object.identity.toLowerCase();
}
objects[object.identity] = object;
});
if(!objects) return {};
return objects;
}
|
var _ = require('underscore');
var requireAll = require('require-all');
module.exports = {
required: function(options) {
return buildDictionary(options);
},
optional: function(options) {
options.optional = true;
return buildDictionary(options);
}
};
// buildDictionary ()
// Go through each object, include the code, and determine its identity.
// Tolerates non-existent files/directories by ignoring them.
//
// @dirname :: the path to the source directory
// @filter :: the filter regex
// $replaceExpr :: the replace regex
// @optional :: if optional, don't throw an error if nothing is found
function buildDictionary(options) {
var files = requireAll({
dirname: options.dirname,
filter: options.filter
});
// Handle optional vs. required logic
if (!files) {
if (options.optional) return {};
else throw 'Cannot not find required directory '+dirname;
}
var objects = {};
_.each(files, function(object, filename) {
// If no 'identity' attribute was provided,
// take a guess based on the (case-insensitive) filename
if(!object.identity) {
object.identity = options.replaceExpr ? filename.replace(options.replaceExpr, "") : filename;
object.identity = object.identity.toLowerCase();
}
objects[object.identity] = object;
});
if(!objects) return {};
return objects;
}
|
Revert "Make signature of test auth source match that of class it extends"
This reverts commit a4dcf65abfa0cba1feed8ffba80be943b14fa67c.
|
<?php
namespace SimpleSAML\Test\Auth;
use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;
/**
* Tests for SimpleSAML_Auth_Source
*/
class SourceTest extends ClearStateTestCase
{
public function testParseAuthSource()
{
$class = new \ReflectionClass('SimpleSAML_Auth_Source');
$method = $class->getMethod('parseAuthSource');
$method->setAccessible(true);
// test direct instantiation of the auth source object
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
// test instantiation via an auth source factory
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
}
}
class TestAuthSource extends \SimpleSAML_Auth_Source
{
public function authenticate(&$state)
{
}
}
class TestAuthSourceFactory implements SourceFactory
{
public function create(array $info, array $config)
{
return new TestAuthSource($info, $config);
}
}
|
<?php
namespace SimpleSAML\Test\Auth;
use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;
/**
* Tests for SimpleSAML_Auth_Source
*/
class SourceTest extends ClearStateTestCase
{
public function testParseAuthSource()
{
$class = new \ReflectionClass('SimpleSAML_Auth_Source');
$method = $class->getMethod('parseAuthSource');
$method->setAccessible(true);
// test direct instantiation of the auth source object
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
// test instantiation via an auth source factory
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
}
}
class TestAuthSource extends \SimpleSAML_Auth_Source
{
public function authenticate(array &$state)
{
}
}
class TestAuthSourceFactory implements SourceFactory
{
public function create(array $info, array $config)
{
return new TestAuthSource($info, $config);
}
}
|
Set Session variable for image and image._id
|
Template.createBetForm.helpers({
photo: function(){
return Session.get("photo");
}
})
Template.createBetForm.events({
"submit .create-bet" : function(event){
event.preventDefault();
var title = event.target.betTitle.value,
wager = event.target.betWager.value,
user = Meteor.user(),
username = user.username,
defender = event.target.defender.value,
type = "new";
if (Meteor.users.find({username: defender}).count() === 0){
throw new Meteor.Error(
alert( "Sorry the Username you are trying to challenge is not valid!" )
);
}
if (defender === username) {
throw new Meteor.Error(
alert( "You can't bet yourself!" )
);
}
Meteor.call('createBet', username, defender, title, wager, betImage);
Meteor.call('createBetNotification', username, defender, type);
Router.go('/bets');
},
"click .take-photo" : function(event){
event.preventDefault();
var cameraOptions = {
width: 700,
height: 500
};
MeteorCamera.getPicture(cameraOptions, function(error, data){
var image = Images.insert(data);
Session.set('image', data);
Session.set('image._id', image._id);
});
}
});
|
Template.createBetForm.helpers({
photo: function(){
return Session.get("photo");
}
})
Template.createBetForm.events({
"submit .create-bet" : function(event){
event.preventDefault();
var title = event.target.betTitle.value,
wager = event.target.betWager.value,
user = Meteor.user(),
username = user.username,
defender = event.target.defender.value,
type = "new";
if (Meteor.users.find({username: defender}).count() === 0){
throw new Meteor.Error(
alert( "Sorry the Username you are trying to challenge is not valid!" )
);
}
if (defender === username) {
throw new Meteor.Error(
alert( "You can't bet yourself!" )
);
}
Meteor.call("createBet", username, defender, title, wager);
Meteor.call("createBetNotification", username, defender, type);
Router.go('/bets');
},
"click .take-photo" : function(event){
event.preventDefault();
var cameraOptions = {
width: 700,
height: 500
};
MeteorCamera.getPicture(cameraOptions, function(error, data){
Images.insert(data);
Session.set("photo", data);
});
}
});
|
Throw exception in to be injected method
+review REVIEW-6467
|
/*
* Copyright 2014 the original author or 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.
*/
package org.gradle.language.java.tasks;
import org.gradle.api.Incubating;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.jvm.platform.JavaPlatform;
import org.gradle.jvm.toolchain.JavaToolChain;
import javax.inject.Inject;
/**
* A platform-aware Java compile task.
*/
@Incubating
public class PlatformJavaCompile extends JavaCompile {
private JavaPlatform platform;
@Override
public JavaPlatform getPlatform() {
return platform;
}
public void setPlatform(JavaPlatform platform) {
this.platform = platform;
}
@Inject
@Override
public JavaToolChain getToolChain() {
throw new UnsupportedOperationException();
}
}
|
/*
* Copyright 2014 the original author or 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.
*/
package org.gradle.language.java.tasks;
import org.gradle.api.Incubating;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.jvm.platform.JavaPlatform;
import org.gradle.jvm.toolchain.JavaToolChain;
import javax.inject.Inject;
/**
* A platform-aware Java compile task.
*/
@Incubating
public class PlatformJavaCompile extends JavaCompile {
private JavaPlatform platform;
@Override
public JavaPlatform getPlatform() {
return platform;
}
public void setPlatform(JavaPlatform platform) {
this.platform = platform;
}
@Inject
@Override
public JavaToolChain getToolChain() {
return super.getToolChain();
}
}
|
Fix worker class name for mock
|
<?php
namespace Gourmet\Dashboard\TestSuite;
class WidgetWorkerTestCase extends \PHPUnit_Framework_TestCase {
/**
* Widget's name (i.e. Buzzwords)
*
* @var string
*/
protected $_name;
/**
* Get mocked instance of current widget
*
* @param array $methods
* @return
*/
protected function _getWidgetWorkerMock(array $methods = []) {
return $this->getMock('\\' . $this->_name . 'WidgetWorker', array_merge(['_getEvents'], $methods));
}
/**
* Return mocked instance with basic expectations pre-defined
*
* @param array $data
* @param string $id
* @return
*/
protected function _getWidgetWorkerExpectingPush($data, $id = null) {
$worker = $this->_getWidgetWorkerMock(['interval', 'push']);
$worker->expects($this->once())
->method('interval')
->with($this->anything())
->will($this->returnValue(true));
$worker->expects($this->once())
->method('push')
->with($data, $id);
return $worker;
}
}
|
<?php
namespace Gourmet\Dashboard\TestSuite;
class WidgetWorkerTestCase extends \PHPUnit_Framework_TestCase {
/**
* Widget's name (i.e. Buzzwords)
*
* @var string
*/
protected $_name;
/**
* Get mocked instance of current widget
*
* @param array $methods
* @return
*/
protected function _getWidgetWorkerMock(array $methods = []) {
return $this->getMock('\\' . $this->_name, array_merge(['_getEvents'], $methods));
}
/**
* Return mocked instance with basic expectations pre-defined
*
* @param array $data
* @param string $id
* @return
*/
protected function _getWidgetWorkerExpectingPush($data, $id = null) {
$worker = $this->_getWidgetWorkerMock(['interval', 'push']);
$worker->expects($this->once())
->method('interval')
->with($this->anything())
->will($this->returnValue(true));
$worker->expects($this->once())
->method('push')
->with($data, $id);
return $worker;
}
}
|
Make it a single instance app
|
var app = require("app"); // Module to control application life.
var BrowserWindow = require("browser-window"); // Module to create native browser window.
// Keep a global reference of the window object, if you don"t, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// Prevent multiple instances of Down Quark
if (app.makeSingleInstance(function (commandLine, workingDirectory) {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
return true;
})) {
app.quit();
return;
}
// Quit when all windows are closed.
app.on("window-all-closed", function() {
app.quit();
});
// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on("ready", function() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
show: false,
"auto-hide-menu-bar": true,
icon: __dirname + "/static/images/icon.png"
});
// and load the index.html of the app.
mainWindow.loadUrl("file://" + __dirname + "/static/index.html");
// Emitted when the window is closed.
mainWindow.on("closed", function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
|
var app = require("app"); // Module to control application life.
var BrowserWindow = require("browser-window"); // Module to create native browser window.
// Keep a global reference of the window object, if you don"t, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on("window-all-closed", function() {
app.quit();
});
// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on("ready", function() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
show: false,
"auto-hide-menu-bar": true,
icon: __dirname + "/static/images/icon.png"
});
// and load the index.html of the app.
mainWindow.loadUrl("file://" + __dirname + "/static/index.html");
// Emitted when the window is closed.
mainWindow.on("closed", function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
|
Load main JSOM Scripts under one label
|
angular
.module('ngSharepoint', [])
.run(['$sp', '$spLoader', function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
$spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']);
}else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken) {
$spLoader.loadScript('SP.RequestExecutor.js');
}
}
}]);
|
angular
.module('ngSharepoint', [])
.run(['$sp', '$spLoader', function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
$spLoader.loadScript('//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js');
$spLoader.loadScript('SP.Runtime.js');
$spLoader.loadScript('SP.js');
}else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken) {
$spLoader.loadScript('SP.RequestExecutor.js');
}
}
}]);
|
Convert default parameters to be ES-pre-6 friendly
|
var route = function(name, params = {}, absolute) {
if (absolute === undefined) absolute = true;
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri.replace(/^\//, ''),
params = typeof params !== 'object' ? [params] : params,
paramsArrayKey = 0;
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, '');
paramsArrayKey++;
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
return params[key].id || params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
|
var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri.replace(/^\//, ''),
params = typeof params !== 'object' ? [params] : params,
paramsArrayKey = 0;
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, '');
paramsArrayKey++;
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
return params[key].id || params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
|
Add the ingest param to the context only if present
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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 org.elasticsearch.plugin.ingest.rest;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.rest.*;
import static org.elasticsearch.plugin.ingest.IngestPlugin.*;
import static org.elasticsearch.plugin.ingest.IngestPlugin.INGEST_PARAM_CONTEXT_KEY;
public class IngestRestFilter extends RestFilter {
@Inject
public IngestRestFilter(RestController controller) {
controller.registerFilter(this);
}
@Override
public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception {
if (request.hasParam(INGEST_PARAM)) {
request.putInContext(INGEST_PARAM_CONTEXT_KEY, request.param(INGEST_PARAM));
}
filterChain.continueProcessing(request, channel);
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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 org.elasticsearch.plugin.ingest.rest;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.rest.*;
import static org.elasticsearch.plugin.ingest.IngestPlugin.*;
import static org.elasticsearch.plugin.ingest.IngestPlugin.INGEST_PARAM_CONTEXT_KEY;
public class IngestRestFilter extends RestFilter {
@Inject
public IngestRestFilter(RestController controller) {
controller.registerFilter(this);
}
@Override
public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception {
request.putInContext(INGEST_PARAM_CONTEXT_KEY, request.param(INGEST_PARAM));
filterChain.continueProcessing(request, channel);
}
}
|
Remove option for empty title
Looks terrible without a title. We shouldn't do it.
|
// website/static/js/growlBox.js
// Initial semicolon for safe minification
;(function (global, factory) {
// Support RequireJS/AMD or no module loader
if (typeof define === 'function' && define.amd) {
// Dependency IDs here
define(['jquery', 'vendor/bower_components/bootstrap.growl/bootstrap-growl'], factory);
} else { // No module loader, just attach to global namespace
global.GrowlBox = factory(jQuery);
}
}(this, function($) { // named dependencies here
'use strict';
// Private methods go up here
// This is the public API
// The constructor
function GrowlBox (title, message) {
var self = this;
self.title = title;
self.message = message;
self.init(self);
}
// Methods
GrowlBox.prototype.init = function(self) {
$.growl({
title: '<strong>' + self.title + '<strong><br />',
message: self.message
},{
type: 'danger',
delay: 0
});
};
return GrowlBox;
}));
|
// website/static/js/growlBox.js
// Initial semicolon for safe minification
;(function (global, factory) {
// Support RequireJS/AMD or no module loader
if (typeof define === 'function' && define.amd) {
// Dependency IDs here
define(['jquery', 'vendor/bower_components/bootstrap.growl/bootstrap-growl'], factory);
} else { // No module loader, just attach to global namespace
global.GrowlBox = factory(jQuery);
}
}(this, function($) { // named dependencies here
'use strict';
// Private methods go up here
// This is the public API
// The constructor
function GrowlBox (title, message) {
var self = this;
if (typeof title === 'undefined'){
title = '';
}
self.title = title;
self.message = message;
self.init(self);
}
// Methods
GrowlBox.prototype.init = function(self) {
$.growl({
title: '<strong>' + self.title + '<strong><br />',
message: self.message
},{
type: 'danger',
delay: 0
});
};
return GrowlBox;
}));
|
Make email and password have default values
* which must be overriden
|
package com.fns.xlator.client.impl;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app.frengly")
public class FrenglyClientSettings {
private String host = "frengly.com";
@NotEmpty
private String email = "change@me.com";
@NotEmpty
private String password = "changeme";
private int retries = 10;
@Value("${app.defaults.locale}")
private String defaultSource;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDefaultSource() {
return defaultSource;
}
public int getRetries() {
return retries;
}
}
|
package com.fns.xlator.client.impl;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app.frengly")
public class FrenglyClientSettings {
private String host = "frengly.com";
@NotEmpty
private String email;
@NotEmpty
private String password;
private int retries = 10;
@Value("${app.defaults.locale}")
private String defaultSource;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDefaultSource() {
return defaultSource;
}
public int getRetries() {
return retries;
}
}
|
Make API urls public constants
|
package com.simplenote.android;
public class Constants {
public static final String PREFS_NAME = "SimpleNotePrefs";
public static final String TAG = "SimpleNote:";
public static final boolean USE_CACHE = true;
// API Base URL
public static final String API_BASE_URL = "https://simple-note.appspot.com/api";
public static final String API_LOGIN_URL = API_BASE_URL + "/login"; // POST
public static final String API_NOTES_URL = API_BASE_URL + "/index"; // GET
public static final String API_NOTE_URL = API_BASE_URL + "/note"; // GET
public static final String API_UPDATE_URL = API_BASE_URL + "/note"; // POST
public static final String API_DELETE_URL = API_BASE_URL + "/delete"; // GET
public static final String API_SEARCH_URL = API_BASE_URL + "/search"; // GET
}
|
package com.simplenote.android;
public class Constants {
public static final String PREFS_NAME = "SimpleNotePrefs";
public static final String TAG = "SimpleNote:";
public static final boolean USE_CACHE = true;
// API Base URL
static final String API_BASE_URL = "https://simple-note.appspot.com/api";
static final String API_LOGIN_URL = API_BASE_URL + "/login"; // POST
static final String API_NOTES_URL = API_BASE_URL + "/index"; // GET
static final String API_NOTE_URL = API_BASE_URL + "/note"; // GET
static final String API_UPDATE_URL = API_BASE_URL + "/note"; // POST
static final String API_DELETE_URL = API_BASE_URL + "/delete"; // GET
static final String API_SEARCH_URL = API_BASE_URL + "/search"; // GET
}
|
Refactor to inline value search
|
'use strict';
// MODULES //
var modes = require( '@stdlib/types/ndarray/base/modes' );
// VARIABLES //
var MODES = modes();
var len = MODES.length;
// MAIN //
/**
* Tests whether an input value is a supported ndarray index mode.
*
* @param {*} v - value to test
* @returns {boolean} boolean indicating whether an input value is a supported ndarray index mode
*
* @example
* var bool = isIndexMode( 'wrap' );
* // returns true
*
* bool = isIndexMode( 'clamp' );
* // returns true
*
* bool = isIndexMode( 'throw' );
* // returns true
*
* bool = isIndexMode( 'foo' );
* // returns false
*/
function isIndexMode( v ) {
var i;
for ( i = 0; i < len; i++ ) {
if ( v === MODES[ i ] ) {
return true;
}
}
return false;
} // end FUNCTION isIndexMode()
// EXPORTS //
module.exports = isIndexMode;
|
'use strict';
// MODULES //
var indexOf = require( '@stdlib/utils/index-of' );
var modes = require( '@stdlib/types/ndarray/base/modes' );
// VARIABLES //
var MODES = modes();
// MAIN //
/**
* Tests whether an input value is a supported ndarray index mode.
*
* @param {*} v - value to test
* @returns {boolean} boolean indicating whether an input value is a supported ndarray index mode
*
* @example
* var bool = isIndexMode( 'wrap' );
* // returns true
*
* bool = isIndexMode( 'clamp' );
* // returns true
*
* bool = isIndexMode( 'throw' );
* // returns true
*
* bool = isIndexMode( 'foo' );
* // returns false
*/
function isIndexMode( v ) {
return ( indexOf( MODES, v ) !== -1 );
} // end FUNCTION isIndexMode()
// EXPORTS //
module.exports = isIndexMode;
|
Change and forget links go above Remeber me, not after
|
<form action="<?php echo url_for('account/login') ?>" method="POST">
<?php echo $form['_csrf_token']; ?>
<div id="password_field">
<?php echo $form['password']->renderError() ?>
<?php echo $form['password']->renderLabel() ?>
<?php echo $form['password'] ?>
</div>
<div class="links">
<?php echo link_to('Change',"account/password"); ?>
·
<?php echo link_to('I forgot',"http://limecast.com/tracker/reset-password"); ?>
</div>
<div id="remember_field">
<?php echo $form['remember_me']->renderError() ?>
<?php echo $form['remember_me'] ?>
<?php echo $form['remember_me']->renderLabel(null, array('id' => 'remember_label')) ?>
</div>
<input type="submit" class="submit" value="Sign in" />
</form>
|
<form action="<?php echo url_for('account/login') ?>" method="POST">
<?php echo $form['_csrf_token']; ?>
<div id="password_field">
<?php echo $form['password']->renderError() ?>
<?php echo $form['password']->renderLabel() ?>
<?php echo $form['password'] ?>
</div>
<div id="remember_field">
<?php echo $form['remember_me']->renderError() ?>
<?php echo $form['remember_me'] ?>
<?php echo $form['remember_me']->renderLabel(null, array('id' => 'remember_label')) ?>
</div>
<div class="links">
<?php echo link_to('Change',"account/password"); ?>
·
<?php echo link_to('I forgot',"http://limecast.com/tracker/reset-password"); ?>
</div>
<input type="submit" class="submit" value="Sign in" />
</form>
|
Update the tests for query_pricing
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
eans = [7321900286480, 9780262510875, 5060314991222]
fake_manager.query_pricing(eans=eans)
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(eans=['007'])
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
fake_manager.query_pricing(ean='0886971942323')
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(ean='007')
|
Update file cache path to /storage/framework/cache/
|
<?php
/**
* Author: Abel Halo <zxz054321@163.com>
*/
return [
'debug' => true,
'cache' => [
'driver' => 'file',
'file' => [
'dir' => ROOT.'/storage/framework/cache/',
],
'memcached' => [
[
'host' => '127.0.0.1',
'port' => '11211',
'weight' => '100',
],
],
],
'database' => [
'mysql' => [
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'dbname' => 'doclib',
],
],
];
|
<?php
/**
* Author: Abel Halo <zxz054321@163.com>
*/
return [
'debug' => true,
'cache' => [
'driver' => 'file',
'file' => [
'dir' => ROOT.'/cache/',
],
'memcached' => [
[
'host' => '127.0.0.1',
'port' => '11211',
'weight' => '100',
],
],
],
'database' => [
'mysql' => [
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'dbname' => 'doclib',
],
],
];
|
Use micromatch.matcher on strings only
Its behavior with functions is different (more generic) which broke
expected behavior for some scenarios.
This patch fixes the failing tests that were just introduced.
|
'use strict';
var micromatch = require('micromatch');
var arrify = require('arrify');
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
criteria = arrify(criteria);
value = arrify(value);
if (arguments.length === 1) {
return anymatch.bind(null, criteria.map(function(criterion) {
return typeof criterion === 'string' ?
micromatch.matcher(criterion) : criterion;
}));
}
startIndex = startIndex || 0;
var string = value[0];
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || micromatch.isMatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion.apply(null, value);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
|
'use strict';
var micromatch = require('micromatch');
var arrify = require('arrify');
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
criteria = arrify(criteria);
value = arrify(value);
if (arguments.length === 1) {
return criteria.length === 1 ?
micromatch.matcher(criteria[0]) :
anymatch.bind(null, criteria.map(function(criterion) {
return micromatch.matcher(criterion);
}));
}
startIndex = startIndex || 0;
var string = value[0];
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || micromatch.isMatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion.apply(null, value);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
|
Reset heat every 6 seconds
|
var setHeat = function () {
"use strict";
var allArr = Posts.find({
oldPoints: {
$gt: 1
}
}).fetch();
console.log('Calculating post heat');
_(allArr).forEach(function (post) {
var secondsAgo = Math.abs((new Date()) - (new Date(post.createdAt))) / 1000;
var hoursAgo = secondsAgo / 60 / 60;
var points = (post.oldPoints - 1);
var decay = Math.pow(hoursAgo + 2, 1.5);
Posts.update({
_id: post._id
},{
$set: {
heat: points / decay
}
});
});
};
Meteor.startup(setHeat);
// run every 6 seconds
Meteor.setInterval(setHeat, 6 * 1000);
|
var setHeat = function () {
"use strict";
var allArr = Posts.find({
oldPoints: {
$gt: 1
}
}).fetch();
console.log('Calculating post heat');
_(allArr).forEach(function (post) {
var secondsAgo = Math.abs((new Date()) - (new Date(post.createdAt))) / 1000;
var hoursAgo = secondsAgo / 60 / 60;
var points = (post.oldPoints - 1);
var decay = Math.pow(hoursAgo + 2, 1.5);
Posts.update({
_id: post._id
},{
$set: {
heat: points / decay
}
});
});
};
Meteor.startup(setHeat);
// run every 10 seconds
Meteor.setInterval(setHeat, 10 * 1000);
|
Use constant for error number
|
package main
import (
"syscall"
"github.com/mistifyio/gozfs/nv"
)
func snapshot(zpool string, snapNames []string, props map[string]string) (map[string]int32, error) {
// snaps needs to be a map with the snap name as the key and an arbitrary value
snaps := make(map[string]string)
for _, snapName := range snapNames {
snaps[snapName] = ""
}
m := map[string]interface{}{
"cmd": "zfs_snapshot",
"version": uint64(0),
"innvl": map[string]interface{}{
"snaps": snaps,
"props": props,
},
}
encoded, err := nv.Encode(m)
if err != nil {
return nil, err
}
var errlist map[string]int32
out := make([]byte, 1024)
err = ioctl(zfs, zpool, encoded, out)
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EEXIST {
// Try to get errlist info, but ignore any errors in the attempt
_ = nv.Decode(out, &errlist)
}
return errlist, err
}
|
package main
import (
"syscall"
"github.com/mistifyio/gozfs/nv"
)
func snapshot(zpool string, snapNames []string, props map[string]string) (map[string]int32, error) {
// snaps needs to be a map with the snap name as the key and an arbitrary value
snaps := make(map[string]string)
for _, snapName := range snapNames {
snaps[snapName] = ""
}
m := map[string]interface{}{
"cmd": "zfs_snapshot",
"version": uint64(0),
"innvl": map[string]interface{}{
"snaps": snaps,
"props": props,
},
}
encoded, err := nv.Encode(m)
if err != nil {
return nil, err
}
var errlist map[string]int32
out := make([]byte, 1024)
err = ioctl(zfs, zpool, encoded, out)
if errno, ok := err.(syscall.Errno); ok && errno == 17 {
// Try to get errlist info, but ignore any errors in the attempt
_ = nv.Decode(out, &errlist)
}
return errlist, err
}
|
Make corrections in task 3.3
|
package ru.job4j.maximum;
/**
* Max class.
* @author Yury Chuksin (chuksin.yury@gmail.com)
* @since 18.01.2017
*/
public class Max {
/**
* maxFromTwo method compare two variables and takes maximum.
* @param first first of two compared variables
* @param second second of two compared variables
*/
public maxFromTwo(int first, int second) {
int resultMax = 0;
if (first > second) {
resultMax = first;
} else {
resultMax = second;
}
return resultMax;
}
/**
* maxFromTree method compare tree variables and takes maximum.
* @param first first of tree compared variables
* @param second second of tree compared variables
* @param third of tree compared variables
*/
public maxFromThree(int first, int second, int third) {
int maxFthree = maxFromTwo(first, second);
maxFthree = maxFromTwo(maxFthree, third);
return maxFthree;
}
}
|
package ru.job4j.maximum;
/**
* Max class.
* @author Yury Chuksin (chuksin.yury@gmail.com)
* @since 18.01.2017
*/
public class Max {
/**
* maxFromTwo method compare two variables and takes maximum.
* @param first first of two compared variables
* @param second second of two compared variables
*/
public maxFromTwo(int first, int second) {
int resultMax = 0;
if (first > second) {
resultMax = first;
} else {
resultMax = second;
}
return resultMax;
}
/**
* maxFromTree method compare tree variables and takes maximum.
* @param first first of tree compared variables
* @param second second of tree compared variables
* @param third of tree compared variables
*/
public maxFromThree(int first, int second, int third) {
int maxFthree = (first > second) ? first : second;
maxFthree = (maxFthree > third) ? maxFthree : third;
return maxFthree;
}
}
|
Fix and disable AuthorList test case
The parsing logic in AuthorList.Author is broken and also terribly written (Even Intellij complains that it is too complex for its dataflow analyzer). Until somebody has the will to fix this, there is no point in executing this test.
|
package net.sf.jabref.logic;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AuthorListTest {
@Ignore
@Test
public void authorListTest() {
String authorString = "Olaf von Nilsen, Jr.";
AuthorList authorList = AuthorList.getAuthorList(authorString);
for (int i = 0; i < authorList.size(); i++) {
AuthorList.Author author = authorList.getAuthor(i);
assertEquals("Olaf", author.getFirst());
assertEquals("Nilsen", author.getLast());
assertEquals("Jr.", author.getJr());
assertEquals("von", author.getVon());
}
}
}
|
package net.sf.jabref.logic;
import net.sf.jabref.export.layout.format.CreateDocBookAuthors;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AuthorListTest {
@Test
public void authorListTest() {
String authorString = "Olaf von Nilsen, Jr.";
AuthorList authorList = AuthorList.getAuthorList(authorString);
for (int i = 0; i < authorList.size(); i++) {
AuthorList.Author author = authorList.getAuthor(i);
assertEquals("Jr.", author.getFirst());
assertEquals("Olaf von Nilsen", author.getLast());
assertEquals(null, author.getJr());
assertEquals(null, author.getVon());
}
assertEquals("<author><firstname>Jr.</firstname><surname>Olaf von Nilsen</surname></author>", new CreateDocBookAuthors().format(authorString));
}
}
|
Add status messages to `gitdir update`
|
import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
print('[ ** ] updating {}'.format(repo_dir))
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname))
|
import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname))
|
Change the access-types from private to protected
|
<?php
/**
*
*/
class Script
{
protected $helpMessage = '';
protected $matches;
protected $message;
protected $waConnection;
function __construct($message, $matches, $waConnection)
{
$this->matches = $matches;
$this->message = $message;
$this->waConnection = $waConnection;
}
public function help()
{
return $helpMessage;
}
public function run()
{
}
public function send($from, $content, $type = 'text')
{
switch ($type) {
case 'text':
return $this->waConnection->sendMessage($from, $content);
break;
case 'image':
return $this->waConnection->sendMessageImage($from, $content);
break;
case 'audio':
return $this->waConnection->sendMessageAudio($from, $content);
break;
case 'video':
return $this->waConnection->sendMessageVideo($from, $content);
break;
case 'location':
return $this->waConnection->sendMessageLocation($from, $content);
break;
}
}
}
?>
|
<?php
/**
*
*/
class Script
{
private $helpMessage = '';
private $matches;
private $message;
private $waConnection;
function __construct($message, $matches, $waConnection)
{
$this->matches = $matches;
$this->message = $message;
$this->waConnection = $waConnection;
}
public function help()
{
return $helpMessage;
}
public function run()
{
}
public function send($from, $content, $type = 'text')
{
switch ($type) {
case 'text':
return $this->waConnection->sendMessage($from, $content);
break;
case 'image':
return $this->waConnection->sendMessageImage($from, $content);
break;
case 'audio':
return $this->waConnection->sendMessageAudio($from, $content);
break;
case 'video':
return $this->waConnection->sendMessageVideo($from, $content);
break;
case 'location':
return $this->waConnection->sendMessageLocation($from, $content);
break;
}
}
}
?>
|
Allow Knox usage server side
The `var` keyword restricts the use of it to this file only. Removing it lets `package.js` see it and export it
|
Knox = Npm.require("knox");
var Future = Npm.require('fibers/future');
var knox;
var S3;
Meteor.methods({
S3config:function(obj){
knox = Knox.createClient(obj);
S3 = {directory:obj.directory || "/"};
},
S3upload:function(file,context,callback){
var future = new Future();
var extension = (file.name).match(/\.[0-9a-z]{1,5}$/i);
file.name = Meteor.uuid()+extension;
var path = S3.directory+file.name;
var buffer = new Buffer(file.data);
knox.putBuffer(buffer,path,{"Content-Type":file.type,"Content-Length":buffer.length},function(e,r){
if(!e){
future.return(path);
} else {
console.log(e);
}
});
if(future.wait() && callback){
var url = knox.http(future.wait());
Meteor.call(callback,url,context);
}
}
});
|
var Knox = Npm.require("knox");
var Future = Npm.require('fibers/future');
var knox;
var S3;
Meteor.methods({
S3config:function(obj){
knox = Knox.createClient(obj);
S3 = {directory:obj.directory || "/"};
},
S3upload:function(file,context,callback){
var future = new Future();
var extension = (file.name).match(/\.[0-9a-z]{1,5}$/i);
file.name = Meteor.uuid()+extension;
var path = S3.directory+file.name;
var buffer = new Buffer(file.data);
knox.putBuffer(buffer,path,{"Content-Type":file.type,"Content-Length":buffer.length},function(e,r){
if(!e){
future.return(path);
} else {
console.log(e);
}
});
if(future.wait() && callback){
var url = knox.http(future.wait());
Meteor.call(callback,url,context);
}
}
});
|
Add an endpoint for getting recordings
|
'use strict';
const express = require('express');
const knex = require('knex');
const morgan = require('morgan');
// Configuration
const DB_CONFIG = require('./knexfile');
const PORT = process.env.PORT || 8888;
// Database
const db = knex(DB_CONFIG);
// API v1
const apiV1 = express.Router();
apiV1.use((request, response, next) => {
if (request.accepts('json')) {
next();
} else {
response.status(406).json(null);
}
});
apiV1.get('/recordings', (request, response) => {
db('recordings')
.where('deleted_at', null)
.orderBy('created_at', 'desc')
.then((recordings) => {
response.json(recordings);
});
});
apiV1.use((error, _request, response, _next) => {
console.error(error);
response.status(500).json(null);
});
// API
const api = express.Router();
api.use('/v1', apiV1);
// Application
const app = express();
app.use(morgan('combined'));
app.use('/api', api);
// Server
const server = app.listen(PORT, () => {
console.log('Listening on port ' + server.address().port + '...');
});
|
'use strict';
const express = require('express');
const knex = require('knex');
const morgan = require('morgan');
// Configuration
const DB_CONFIG = require('./knexfile');
const PORT = process.env.PORT || 8888;
// Database
const db = knex(DB_CONFIG);
// API v1
const apiV1 = express.Router();
apiV1.use((request, response, next) => {
if (request.accepts('json')) {
next();
} else {
response.status(406).json(null);
}
});
apiV1.get('/', (request, response) => {
response.status(501).json(null);
});
apiV1.use((error, _request, response, _next) => {
console.error(error);
response.status(500).json(null);
});
// API
const api = express.Router();
api.use('/v1', apiV1);
// Application
const app = express();
app.use(morgan('combined'));
app.use('/api', api);
// Server
const server = app.listen(PORT, () => {
console.log('Listening on port ' + server.address().port + '...');
});
|
Fix test: redundant done argument
|
/* eslint-env mocha */
var chai = require('chai')
chai.use(require('chai-as-promised'))
chai.should()
var schema = {
type: 'object',
additionalProperties: false,
patternProperties: {
'[0-9]*': {
type: 'object',
additionalProperties: false,
properties: {
browserName: {type: 'string'},
version: {type: 'string'},
platform: {type: 'string'},
base: {type: 'string', enum: ['SauceLabs']}
},
required: ['browserName', 'version', 'platform', 'base']
}
}
}
var ZSchema = require('z-schema')
var validator = new ZSchema()
var browsers = require('../')
describe('exports', function () {
this.timeout(10000)
it('is a promise that fulfills according to the schema', function () {
return browsers.then(function (browsers) {
var valid = validator.validate(browsers, schema)
if (!valid) {
var errors = validator.getLastErrors()
console.log(errors)
}
return valid
}).should.eventually.be.true
})
})
|
/* eslint-env mocha */
var chai = require('chai')
chai.use(require('chai-as-promised'))
chai.should()
var schema = {
type: 'object',
additionalProperties: false,
patternProperties: {
'[0-9]*': {
type: 'object',
additionalProperties: false,
properties: {
browserName: {type: 'string'},
version: {type: 'string'},
platform: {type: 'string'},
base: {type: 'string', enum: ['SauceLabs']}
},
required: ['browserName', 'version', 'platform', 'base']
}
}
}
var ZSchema = require('z-schema')
var validator = new ZSchema()
var browsers = require('../')
describe('exports', function () {
this.timeout(10000)
it('is a promise that fulfills according to the schema', function (done) {
return browsers.then(function (browsers) {
var valid = validator.validate(browsers, schema)
if (!valid) {
var errors = validator.getLastErrors()
console.log(errors)
}
return valid
}).should.eventually.be.true
})
})
|
Update remote origin for deploy github pages
|
module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin2' // default is 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
|
module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
|
Use the same reference for all method calls
|
package co.codesharp.jwampsharp.defaultBinding;
import co.codesharp.jwampsharp.api.client.WampChannel;
import co.codesharp.jwampsharp.api.client.WampChannelFactoryImpl;
import co.codesharp.jwampsharp.core.binding.WampTextBinding;
import co.codesharp.jwampsharp.defaultBinding.jsr.WebsocketWampTextConnection;
import java.net.URI;
/**
* Created by Elad on 7/11/2014.
*/
public class DefaultWampChannelFactory extends WampChannelFactoryImpl {
private JsonNodeBinding jsonNodeBinding = new JsonNodeBinding();
public <TMessage> WampChannel createChannel
(URI address,
String realm,
WampTextBinding<TMessage> binding) {
WebsocketWampTextConnection<TMessage> connection =
new WebsocketWampTextConnection<TMessage>(address, binding);
return this.createChannel(realm, connection, binding);
}
public WampChannel createJsonChannel(URI address,
String realm) {
return this.createChannel(address, realm, jsonNodeBinding);
}
}
|
package co.codesharp.jwampsharp.defaultBinding;
import co.codesharp.jwampsharp.api.client.WampChannel;
import co.codesharp.jwampsharp.api.client.WampChannelFactoryImpl;
import co.codesharp.jwampsharp.core.binding.WampTextBinding;
import co.codesharp.jwampsharp.defaultBinding.jsr.WebsocketWampTextConnection;
import java.net.URI;
/**
* Created by Elad on 7/11/2014.
*/
public class DefaultWampChannelFactory extends WampChannelFactoryImpl {
public <TMessage> WampChannel createChannel
(URI address,
String realm,
WampTextBinding<TMessage> binding) {
WebsocketWampTextConnection<TMessage> connection =
new WebsocketWampTextConnection<TMessage>(address, binding);
return this.createChannel(realm, connection, binding);
}
public WampChannel createJsonChannel(URI address,
String realm) {
JsonNodeBinding binding = new JsonNodeBinding();
return this.createChannel(address, realm, binding);
}
}
|
Prepare for release for 8.3dev-601.
|
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.22 2007/07/31 06:05:43 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public final static int buildNumber = 601;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
|
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.21 2006/12/01 12:06:21 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public static int buildNumber = 600;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
|
Increment the version to realease README with notice about archiving.
|
#!/usr/bin/env python
import sys
from setuptools import setup
VERSION = (0, 4)
VERSION_STR = ".".join(map(str, VERSION))
url = 'https://github.com/mila/spadl'
try:
if sys.version_info >= (3,):
long_description = open('README.rst', 'rb').read().decode('utf-8')
else:
long_description = open('README.rst', 'r').read().decode('utf-8')
except IOError:
long_description = "See %s" % url
setup(
name='spadl',
version=VERSION_STR,
description='This package provides a standard logging handler which writes log records to DbgLog.',
long_description=long_description,
author='Miloslav Pojman',
author_email='miloslav.pojman@gmail.com',
url=url,
py_modules=['spadl'],
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: System :: Logging'
],
zip_safe=False,
)
|
#!/usr/bin/env python
import sys
from setuptools import setup
VERSION = (0, 3)
VERSION_STR = ".".join(map(str, VERSION))
url = 'https://github.com/mila/spadl'
try:
if sys.version_info >= (3,):
long_description = open('README.rst', 'rb').read().decode('utf-8')
else:
long_description = open('README.rst', 'r').read().decode('utf-8')
except IOError:
long_description = "See %s" % url
setup(
name='spadl',
version=VERSION_STR,
description='This package provides a standard logging handler which writes log records to DbgLog.',
long_description=long_description,
author='Miloslav Pojman',
author_email='miloslav.pojman@gmail.com',
url=url,
py_modules=['spadl'],
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: System :: Logging'
],
zip_safe=False,
)
|
Add a TODO comment for the component selection hack
|
var _ = require('lodash');
var Helpers = {
getAlterEgoComponent: function getAlterEgoComponent (device) {
// TODO: remove this ugly hack when mainComponentId is there
if (device.properties.displayType === 'LAMP') {
return _.find(device.components, (component) =>
component.properties.type === 'SOCKET'
);
}
return _.find(device.components, (component) =>
component.properties.type === device.properties.displayType
);
},
augmentDevice: function augmentDevice (device) {
var alterEgoComponent = Helpers.getAlterEgoComponent(device);
var deviceActions = _.indexBy(alterEgoComponent.actions, 'name');
var primaryCapability = Helpers.getPrimaryCapability(alterEgoComponent);
return {
properties: device.properties,
alterEgoComponent: alterEgoComponent,
actions: deviceActions,
primaryCapability: primaryCapability
};
},
getPrimaryCapability: function getPrimaryCapability (component) {
return component.properties.capabilities[0];
},
// TODO: ideally this should be retrieved from the model
propertyByCapability: {
SWITCHABLE: 'SWITCHABLE-on',
SETTABLE: 'setValue'
},
getActionForCapability: function getActionForCapability (component, capability, operation) {
var actionName = operation + '-' + Helpers.propertyByCapability[capability];
return _.find(component.actions, 'name', actionName);
}
};
module.exports = Helpers;
|
var _ = require('lodash');
var Helpers = {
getAlterEgoComponent: function getAlterEgoComponent (device) {
if (device.properties.displayType === 'LAMP') {
return _.find(device.components, (component) =>
component.properties.type === 'SOCKET'
);
}
return _.find(device.components, (component) =>
component.properties.type === device.properties.displayType
);
},
augmentDevice: function augmentDevice (device) {
var alterEgoComponent = Helpers.getAlterEgoComponent(device);
var deviceActions = _.indexBy(alterEgoComponent.actions, 'name');
var primaryCapability = Helpers.getPrimaryCapability(alterEgoComponent);
return {
properties: device.properties,
alterEgoComponent: alterEgoComponent,
actions: deviceActions,
primaryCapability: primaryCapability
};
},
getPrimaryCapability: function getPrimaryCapability (component) {
return component.properties.capabilities[0];
},
// TODO: ideally this should be retrieved from the model
propertyByCapability: {
SWITCHABLE: 'SWITCHABLE-on',
SETTABLE: 'setValue'
},
getActionForCapability: function getActionForCapability (component, capability, operation) {
var actionName = operation + '-' + Helpers.propertyByCapability[capability];
return _.find(component.actions, 'name', actionName);
}
};
module.exports = Helpers;
|
Remove hand cursor from ErrorsLabel
there is changing background is used hover indication now
GitOrigin-RevId: 65ebd0b94c8d306b27d306020b10115637f1827e
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.ui.AnimatedIcon.Blinking;
import javax.swing.*;
import static com.intellij.util.ui.EmptyIcon.ICON_16;
class IdeErrorsIcon extends JLabel {
private final boolean myEnableBlink;
IdeErrorsIcon(boolean enableBlink) {
myEnableBlink = enableBlink;
setBorder(StatusBarWidget.WidgetBorder.INSTANCE);
}
void setState(MessagePool.State state) {
Icon myUnreadIcon = !myEnableBlink ? AllIcons.Ide.FatalError : new Blinking(AllIcons.Ide.FatalError);
if (state != null && state != MessagePool.State.NoErrors) {
setIcon(state == MessagePool.State.ReadErrors ? AllIcons.Ide.FatalError_read : myUnreadIcon);
setToolTipText(DiagnosticBundle.message("error.notification.tooltip"));
}
else {
setIcon(ICON_16);
setToolTipText(null);
}
}
}
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.ui.AnimatedIcon.Blinking;
import javax.swing.*;
import java.awt.Cursor;
import static com.intellij.util.ui.EmptyIcon.ICON_16;
class IdeErrorsIcon extends JLabel {
private final boolean myEnableBlink;
IdeErrorsIcon(boolean enableBlink) {
myEnableBlink = enableBlink;
setBorder(StatusBarWidget.WidgetBorder.INSTANCE);
}
void setState(MessagePool.State state) {
Icon myUnreadIcon = !myEnableBlink ? AllIcons.Ide.FatalError : new Blinking(AllIcons.Ide.FatalError);
if (state != null && state != MessagePool.State.NoErrors) {
setIcon(state == MessagePool.State.ReadErrors ? AllIcons.Ide.FatalError_read : myUnreadIcon);
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setToolTipText(DiagnosticBundle.message("error.notification.tooltip"));
}
else {
setIcon(ICON_16);
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
setToolTipText(null);
}
}
}
|
Fix port back to 6666
Chrome doesn't like 6666 port somehow, I had to change it for dev.
|
var express = require('express');
var https = require('https');
var logger = require('./logger');
var security = require('./security');
var db = require('./db');
var app = configureExpressApp();
initializeMongo(initializeRoutes);
startServer(security, app);
function configureExpressApp() {
var app = express();
app.use(express.json());
app.use(express.urlencoded());
app.use(genericErrorHandler);
return app;
function genericErrorHandler(err, req, res, next) {
res.status(500);
res.json({ error: "Please check if your request is correct" });
}
}
function initializeMongo(onSuccessCallback) {
db.initialize(function(err, _db) {
if(err) throw err; // interrupt when can't connect
onSuccessCallback(_db);
});
}
function initializeRoutes(db) {
require('./routes')(app, logger, db);
}
function startServer(security, app) {
var port = 6666;
var httpsServer = https.createServer(security.credentials, app);
httpsServer.listen(port);
console.log("Codebrag stats server started on port", port);
return httpsServer;
}
|
var express = require('express');
var https = require('https');
var logger = require('./logger');
var security = require('./security');
var db = require('./db');
var app = configureExpressApp();
initializeMongo(initializeRoutes);
startServer(security, app);
function configureExpressApp() {
var app = express();
app.use(express.json());
app.use(express.urlencoded());
app.use(genericErrorHandler);
return app;
function genericErrorHandler(err, req, res, next) {
res.status(500);
res.json({ error: "Please check if your request is correct" });
}
}
function initializeMongo(onSuccessCallback) {
db.initialize(function(err, _db) {
if(err) throw err; // interrupt when can't connect
onSuccessCallback(_db);
});
}
function initializeRoutes(db) {
require('./routes')(app, logger, db);
}
function startServer(security, app) {
var port = 3000;
var httpsServer = https.createServer(security.credentials, app);
httpsServer.listen(port);
console.log("Codebrag stats server started on port", port);
return httpsServer;
}
|
Add JS to not load hidden divs
|
$(function () {
$("img").not(":visible").each(function () {
$(this).data("src", this.src);
this.src = "";
});
var reveal = function (selector) {
var img = $(selector);
img[0].src = img.data("src");
}
});
$("#post_link6").click(function() {
event.preventDefault();
$( ".post.6" ).slideToggle( "slow" );
});
$("#post_link5").click(function() {
event.preventDefault();
$( ".post.5" ).slideToggle( "slow" );
});
$("#post_link4").click(function() {
event.preventDefault();
$( ".post.4" ).slideToggle( "slow" );
});
$("#post_link3").click(function() {
event.preventDefault();
$( ".post.3" ).slideToggle( "slow" );
});
$("#post_link2").click(function() {
event.preventDefault();
$( ".post.2" ).slideToggle( "slow" );
});
$("#post_link1").click(function() {
event.preventDefault();
$( ".post.1" ).slideToggle( "slow" );
});
$("#comment_box_link").click(function() {
event.preventDefault();
$( ".comment_box" ).slideToggle( "slow" );
});
|
$("#post_link6").click(function() {
event.preventDefault();
$( ".post.6" ).slideToggle( "slow" );
});
$("#post_link5").click(function() {
event.preventDefault();
$( ".post.5" ).slideToggle( "slow" );
});
$("#post_link4").click(function() {
event.preventDefault();
$( ".post.4" ).slideToggle( "slow" );
});
$("#post_link3").click(function() {
event.preventDefault();
$( ".post.3" ).slideToggle( "slow" );
});
$("#post_link2").click(function() {
event.preventDefault();
$( ".post.2" ).slideToggle( "slow" );
});
$("#post_link1").click(function() {
event.preventDefault();
$( ".post.1" ).slideToggle( "slow" );
});
$("#comment_box_link").click(function() {
event.preventDefault();
$( ".comment_box" ).slideToggle( "slow" );
});
|
Update annotation on reset events
|
import _ from 'underscore';
import Model from 'girder/models/Model';
import ElementCollection from '../collections/ElementCollection';
import convert from '../annotations/convert';
export default Model.extend({
resourceName: 'annotation',
defaults: {
'annotation': {}
},
initialize() {
this._elements = new ElementCollection(
this.get('annotation').elements || []
);
this._elements.annotation = this;
this.listenTo(this._elements, 'change add remove reset', () => {
// copy the object to ensure a change event is triggered
var annotation = _.extend({}, this.get('annotation'));
annotation.elements = this._elements.toJSON();
this.set('annotation', annotation);
});
},
/**
* Return the annotation as a geojson FeatureCollection.
*
* WARNING: Not all annotations are representable in geojson.
* Annotation types that cannot be converted will be ignored.
*/
geojson() {
const json = this.get('annotation') || {};
const elements = json.elements || [];
return convert(elements);
},
/**
* Return a backbone collection containing the annotation elements.
*/
elements() {
return this._elements;
}
});
|
import _ from 'underscore';
import Model from 'girder/models/Model';
import ElementCollection from '../collections/ElementCollection';
import convert from '../annotations/convert';
export default Model.extend({
resourceName: 'annotation',
defaults: {
'annotation': {}
},
initialize() {
this._elements = new ElementCollection(
this.get('annotation').elements || []
);
this._elements.annotation = this;
this.listenTo(this._elements, 'change add remove', () => {
// copy the object to ensure a change event is triggered
var annotation = _.extend({}, this.get('annotation'));
annotation.elements = this._elements.toJSON();
this.set('annotation', annotation);
});
},
/**
* Return the annotation as a geojson FeatureCollection.
*
* WARNING: Not all annotations are representable in geojson.
* Annotation types that cannot be converted will be ignored.
*/
geojson() {
const json = this.get('annotation') || {};
const elements = json.elements || [];
return convert(elements);
},
/**
* Return a backbone collection containing the annotation elements.
*/
elements() {
return this._elements;
}
});
|
Fix the syntax error in getTypeOptions method
In the method getTypeOptions the array is broken, it's missing one comma.
|
<?php namespace Mohsin\Txt\Models;
use Model;
/**
* Directive Model
*/
class Directive extends Model
{
use \October\Rain\Database\Traits\Validation;
/**
* @var string The database table used by the model.
*/
public $table = 'mohsin_txt_directives';
/**
* @var array Fillable fields
*/
protected $fillable = [
'type',
'data'
];
/**
* @var array Relations
*/
public $belongsTo = [
'robot' => ['Mohsin\txt\Models\Robot',
'table' => 'mohsin_txt_robots']
];
/**
* @var array Validation rules
*/
public $rules = [
'type' => 'required',
'data' => 'required'
];
public $customMessages = [
'type.required' => 'Please select a directive type.',
'data.required' => 'Data cannot be empty.'
];
public function getTypeOptions($fieldName = null, $keyValue = null)
{
return ['Allow' => 'Allow',
'Disallow' => 'Disallow',
'Host' => 'Host',
'Sitemap' => 'Sitemap'];
}
}
|
<?php namespace Mohsin\Txt\Models;
use Model;
/**
* Directive Model
*/
class Directive extends Model
{
use \October\Rain\Database\Traits\Validation;
/**
* @var string The database table used by the model.
*/
public $table = 'mohsin_txt_directives';
/**
* @var array Fillable fields
*/
protected $fillable = [
'type',
'data'
];
/**
* @var array Relations
*/
public $belongsTo = [
'robot' => ['Mohsin\txt\Models\Robot',
'table' => 'mohsin_txt_robots']
];
/**
* @var array Validation rules
*/
public $rules = [
'type' => 'required',
'data' => 'required'
];
public $customMessages = [
'type.required' => 'Please select a directive type.',
'data.required' => 'Data cannot be empty.'
];
public function getTypeOptions($fieldName = null, $keyValue = null)
{
return ['Allow' => 'Allow',
'Disallow' => 'Disallow'
'Host' => 'Host',
'Sitemap' => 'Sitemap'];
}
}
|
Add signature for reading one row
|
package com.github.mrloyal.flatexcelmapper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.io.File;
import java.util.List;
public class FlatExcelMapper {
public <T extends Object>List<T> read(String fileName, int sheetIndex, Class<T> clazz){
List<T> list = null;
return list;
}
public <T extends Object>List<T> read(File file, int sheetIndex, Class<T> clazz){
List<T> list = null;
return list;
}
public <T extends Object>List<T> read(XSSFSheet sheet, Class<T> clazz){
List<T> list = null;
return list;
}
public <T extends Object> T readRow(XSSFSheet sheet, int humanReadableRow, Class<T> clazz) throws IllegalAccessException, InstantiationException {
T object = clazz.newInstance();
return object;
}
public <T extends Object> T readRow(XSSFRow excelRow, Class<T> clazz){
return null;
}
}
|
package com.github.mrloyal.flatexcelmapper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.io.File;
import java.util.List;
public class FlatExcelMapper {
public <T extends Object>List<T> read(String fileName, int sheetIndex, Class<T> clazz){
List<T> list = null;
return list;
}
public <T extends Object>List<T> read(File file, int sheetIndex, Class<T> clazz){
List<T> list = null;
return list;
}
public <T extends Object>List<T> read(XSSFSheet sheet, Class<T> clazz){
List<T> list = null;
return list;
}
public <T extends Object> T readRow(XSSFSheet sheet, int humanReadableRow, Class<T> clazz) throws IllegalAccessException, InstantiationException {
T object = clazz.newInstance();
return object;
}
}
|
Update the api in store package, github.com/armon/consul-api is deprecated
|
package store
import (
"errors"
consul "github.com/hashicorp/consul/api"
)
type ConsulStore struct {
Client *consul.Client
}
func (c *ConsulStore) Get(key string) (Item, error) {
kv, _, err := c.Client.KV().Get(key, nil)
if err != nil {
return nil, err
}
if kv == nil {
return nil, errors.New("key not found")
}
return &ConsulItem{
key: kv.Key,
value: kv.Value,
}, nil
}
func (c *ConsulStore) Del(key string) error {
_, err := c.Client.KV().Delete(key, nil)
return err
}
func (c *ConsulStore) Put(item Item) error {
_, err := c.Client.KV().Put(&consul.KVPair{
Key: item.Key(),
Value: item.Value(),
}, nil)
return err
}
func (c *ConsulStore) NewItem(key string, value []byte) Item {
return &ConsulItem{
key: key,
value: value,
}
}
func NewConsulStore() Store {
client, _ := consul.NewClient(consul.DefaultConfig())
return &ConsulStore{
Client: client,
}
}
|
package store
import (
"errors"
consul "github.com/armon/consul-api"
)
type ConsulStore struct {
Client *consul.Client
}
func (c *ConsulStore) Get(key string) (Item, error) {
kv, _, err := c.Client.KV().Get(key, nil)
if err != nil {
return nil, err
}
if kv == nil {
return nil, errors.New("key not found")
}
return &ConsulItem{
key: kv.Key,
value: kv.Value,
}, nil
}
func (c *ConsulStore) Del(key string) error {
_, err := c.Client.KV().Delete(key, nil)
return err
}
func (c *ConsulStore) Put(item Item) error {
_, err := c.Client.KV().Put(&consul.KVPair{
Key: item.Key(),
Value: item.Value(),
}, nil)
return err
}
func (c *ConsulStore) NewItem(key string, value []byte) Item {
return &ConsulItem{
key: key,
value: value,
}
}
func NewConsulStore() Store {
client, _ := consul.NewClient(&consul.Config{})
return &ConsulStore{
Client: client,
}
}
|
Set don't use station coords for geocoding
|
from data_importers.management.commands import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "HLD"
addresses_name = (
"2022-05-05/2022-03-24T15:19:09.669660/H Democracy Club - Polling Districts.csv"
)
stations_name = (
"2022-05-05/2022-03-24T15:19:09.669660/H Democracy Club - Polling Stations.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.uprn in ["130131593"]:
return None
if record.postcode == "IV17 0QY":
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
if record.stationcode in ["W01 001", "W05 053"]:
record = record._replace(xordinate="", yordinate="")
return super().station_record_to_dict(record)
|
from data_importers.management.commands import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "HLD"
addresses_name = (
"2022-05-05/2022-03-24T15:19:09.669660/H Democracy Club - Polling Districts.csv"
)
stations_name = (
"2022-05-05/2022-03-24T15:19:09.669660/H Democracy Club - Polling Stations.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.uprn in ["130131593"]:
return None
if record.postcode == "IV17 0QY":
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
if record.stationcode in ["W01 001", "W05 053"]:
return None
return super().station_record_to_dict(record)
|
Refresh libraries when showing panel again
|
'use babel';
import {registerCommands, unregisterCommands} from './commands';
import {libraryAddCommand} from './library_add';
import {libraryMigrateCommand} from './library_migrate';
import {libraryInitCommand} from './library_init';
import {libraryContributeCommand} from './library_contribute';
import {libraryPublishCommand} from './library_publish';
import {projectInitCommand} from './project_init';
import {core, toolBar} from './index';
import {LibrariesPanelView} from './views/libraries_panel';
function activate() {
const librariesShow = () => {
core().openPane('libraries', 'left');
};
registerCommands(atom, toolBar(), {
libraryAddCommand,
libraryMigrateCommand,
libraryInitCommand,
libraryContributeCommand,
libraryPublishCommand,
librariesShow,
projectInitCommand
});
atom.workspace.addOpener((uriToOpen) => {
if (!this.librariesPanel) {
this.librariesPanel = new LibrariesPanelView();
}
if (uriToOpen === this.librariesPanel.getUri()) {
this.librariesPanel.fetchLibraries('');
return this.librariesPanel;
}
});
}
function deactivate() {
unregisterCommands(atom);
}
function serialize() {
}
export {
activate,
deactivate,
serialize
};
|
'use babel';
import {registerCommands, unregisterCommands} from './commands';
import {libraryAddCommand} from './library_add';
import {libraryMigrateCommand} from './library_migrate';
import {libraryInitCommand} from './library_init';
import {libraryContributeCommand} from './library_contribute';
import {libraryPublishCommand} from './library_publish';
import {projectInitCommand} from './project_init';
import {core, toolBar} from './index';
import {LibrariesPanelView} from './views/libraries_panel';
function activate() {
const librariesShow = () => {
core().openPane('libraries', 'left');
};
registerCommands(atom, toolBar(), {
libraryAddCommand,
libraryMigrateCommand,
libraryInitCommand,
libraryContributeCommand,
libraryPublishCommand,
librariesShow,
projectInitCommand
});
atom.workspace.addOpener((uriToOpen) => {
if (!this.librariesPanel) {
this.librariesPanel = new LibrariesPanelView();
}
if (uriToOpen === this.librariesPanel.getUri()) {
return this.librariesPanel;
}
});
}
function deactivate() {
unregisterCommands(atom);
}
function serialize() {
}
export {
activate,
deactivate,
serialize
};
|
Add PyYAML as a dependency
|
from setuptools import setup, find_packages
setup(
name="PyRundeck",
version="0.3.4",
description="A thin, pure Python wrapper for the Rundeck API",
author="Panagiotis Koutsourakis",
author_email="kutsurak@ekt.gr",
license='BSD',
url='https://github.com/EKT/pyrundeck',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Internet :: REST API client',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords='rest api client rundeck',
packages=find_packages(exclude=['tests', '*_virtualenv', 'doc']),
install_requires=[
'lxml>=3.4.4',
'requests>=2.7.0',
'pyopenssl>=0.15.1',
'ndg-httpsclient>=0.4.0',
'pyasn1>=0.1.8',
'pyyaml>=3.11'
]
)
|
from setuptools import setup, find_packages
setup(
name="PyRundeck",
version="0.3.4",
description="A thin, pure Python wrapper for the Rundeck API",
author="Panagiotis Koutsourakis",
author_email="kutsurak@ekt.gr",
license='BSD',
url='https://github.com/EKT/pyrundeck',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Internet :: REST API client',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords='rest api client rundeck',
packages=find_packages(exclude=['tests', '*_virtualenv', 'doc']),
install_requires=[
'lxml>=3.4.4',
'requests>=2.7.0',
'pyopenssl>=0.15.1',
'ndg-httpsclient>=0.4.0',
'pyasn1>=0.1.8'
]
)
|
Add the new schema, now the $set modifier is used
|
from eduid_am.exceptions import UserDoesNotExist
WHITELIST_SET_ATTRS = (
'givenName',
'sn',
'displayName',
'photo',
'preferredLanguage',
'mail',
# TODO: Arrays must use put or pop, not set, but need more deep refacts
'norEduPersonNIN',
'eduPersonEntitlement',
'mobile',
'mailAliases',
'portalAddress',
'passwords',
)
def attribute_fetcher(db, user_id):
attributes = {}
user = db.profiles.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
# white list of valid attributes for security reasons
attributes_set = {}
for attr in WHITELIST_SET_ATTRS:
value = user.get(attr, None)
if value is not None:
attributes_set[attr] = value
attributes['$set'] = attributes_set
return attributes
|
from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.profiles.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
# white list of valid attributes for security reasons
for attr in ('email', 'date', 'verified'):
value = user.get(attr, None)
if value is not None:
attributes[attr] = value
# This values must overwrite existent values
for attr in ('screen_name', 'last_name', 'first_name', 'passwords'):
value = user.get(attr, None)
if value is not None:
attributes[attr] = value
return attributes
|
Fix fullscreen mode when using disableEncapsulation option
|
'use strict';
angular.module('sgApp')
.directive('shadowDom', function(Styleguide, $templateCache) {
var USER_STYLES_TEMPLATE = 'userStyles.html';
return {
restrict: 'E',
transclude: true,
link: function(scope, element, attrs, controller, transclude) {
scope.$watch(function() {
return Styleguide.config;
}, function() {
if (typeof element[0].createShadowRoot === 'function' && (Styleguide.config && Styleguide.config.data && !Styleguide.config.data.disableEncapsulation)) {
angular.element(element[0]).empty();
var root = angular.element(element[0].createShadowRoot());
root.append($templateCache.get(USER_STYLES_TEMPLATE));
transclude(function(clone) {
root.append(clone);
});
} else {
transclude(function(clone) {
var root = angular.element(element[0]);
root.empty();
root.append(clone);
});
}
}, true);
}
};
});
|
'use strict';
angular.module('sgApp')
.directive('shadowDom', function(Styleguide, $templateCache) {
var USER_STYLES_TEMPLATE = 'userStyles.html';
return {
restrict: 'E',
transclude: true,
link: function(scope, element, attrs, controller, transclude) {
if (typeof element[0].createShadowRoot === 'function' && !Styleguide.config.data.disableEncapsulation) {
var root = angular.element(element[0].createShadowRoot());
root.append($templateCache.get(USER_STYLES_TEMPLATE));
transclude(function(clone) {
root.append(clone);
});
} else {
transclude(function(clone) {
element.append(clone);
});
}
}
};
});
|
Fix for tests failing because of persisted database file for the next build
|
import os
from sqlalchemy_wrapper import SQLAlchemy
from constants import DATABASE_NAME
os.system('rm -f ' + DATABASE_NAME)
db = SQLAlchemy(uri='sqlite:///' + DATABASE_NAME)
class BlogPostModel(db.Model):
__tablename__ = 'blog_post'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
src_url = db.Column(db.String(128), unique=True)
dest_url = db.Column(db.String(128), unique=True)
blog_title = db.Column(db.String(64))
blog_description = db.Column(db.String(256))
date = db.Column(db.String(10)) # to store yyyy-mm-dd
def __repr__(self):
return str(dict(
id=self.id,
src_url=self.src_url,
dest_url=self.dest_url,
blog_title=self.blog_title,
blog_description=self.blog_description,
date=self.date,
))
db.create_all()
|
from sqlalchemy_wrapper import SQLAlchemy
db = SQLAlchemy(uri='sqlite:///intermediate_data.db')
class BlogPostModel(db.Model):
__tablename__ = 'blog_post'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
src_url = db.Column(db.String(128), unique=True)
dest_url = db.Column(db.String(128), unique=True)
blog_title = db.Column(db.String(64))
blog_description = db.Column(db.String(256))
date = db.Column(db.String(10)) # to store yyyy-mm-dd
def __repr__(self):
return str(dict(
id=self.id,
src_url=self.src_url,
dest_url=self.dest_url,
blog_title=self.blog_title,
blog_description=self.blog_description,
date=self.date,
))
db.create_all()
|
Remove that ... awkward... code
|
#!/usr/bin/python2
import lala
import ConfigParser
import sys
def main():
"""Main method"""
config = ConfigParser.SafeConfigParser()
config.read("config")
lalaconfig = config._sections["lala"]
if "-d" in sys.argv:
debug = True
else:
debug = False
nickserv_password = lalaconfig["nickserv_password"] if "nickserv_password"\
in lalaconfig else None
plugins = lalaconfig["plugins"].split(",")
bot = lala.Bot(
server=lalaconfig["server"],
admin=lalaconfig["admin"],
port=int(lalaconfig["port"]),
nick=lalaconfig["nick"],
channel=lalaconfig["channel"],
debug=debug,
plugins=plugins,
nickserv = nickserv_password
)
#try:
bot.mainloop()
#except RuntimeError, e:
#print e
if __name__ == '__main__':
main()
|
#!/usr/bin/python2
import lala
import ConfigParser
import sys
def main():
"""Main method"""
config = ConfigParser.SafeConfigParser()
config.read("config")
lalaconfig = config._sections["lala"]
if "-d" in sys.argv:
debug = True
else:
debug = False
if "nickserv_password" in lalaconfig:
nickserv_password = lalaconfig["nickserv_password"]
else:
nick
nickserv_password = lalaconfig["nickserv_password"] if "nickserv_password"\
in lalaconfig else None
plugins = lalaconfig["plugins"].split(",")
bot = lala.Bot(
server=lalaconfig["server"],
admin=lalaconfig["admin"],
port=int(lalaconfig["port"]),
nick=lalaconfig["nick"],
channel=lalaconfig["channel"],
debug=debug,
plugins=plugins,
nickserv = nickserv_password
)
#try:
bot.mainloop()
#except RuntimeError, e:
#print e
if __name__ == '__main__':
main()
|
Rename test. Fix copy/pasta forgetfulness.
|
import webtest
import moksha.tests.utils as testutils
from moksha.api.widgets.live import get_moksha_socket
from moksha.middleware import make_moksha_middleware
from tw2.core import make_middleware as make_tw2_middleware
class TestClientSocketDumb:
def _setUp(self):
def kernel(config):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
socket = get_moksha_socket(config)
return map(str, [socket.display()])
app = make_moksha_middleware(app, config)
app = make_tw2_middleware(app, config)
app = webtest.TestApp(app)
self.app = app
for _setup, name in testutils.make_setup_functions(kernel):
yield _setup, name
def _tearDown(self):
pass
@testutils.crosstest
def test_has_socket_str(self):
targets = ['moksha_websocket', 'TCPSocket']
response = self.app.get('/')
assert(any([target in response for target in targets]))
|
import webtest
import moksha.tests.utils as testutils
from moksha.api.widgets.live import get_moksha_socket
from moksha.middleware import make_moksha_middleware
from tw2.core import make_middleware as make_tw2_middleware
class TestClientSocketDumb:
def _setUp(self):
def kernel(config):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
socket = get_moksha_socket(config)
return map(str, [socket.display()])
app = make_moksha_middleware(app, config)
app = make_tw2_middleware(app, config)
app = webtest.TestApp(app)
self.app = app
for _setup, name in testutils.make_setup_functions(kernel):
yield _setup, name
def _tearDown(self):
pass
@testutils.crosstest
def test_middleware_wrap(self):
targets = ['moksha_websocket', 'TCPSocket']
response = self.app.get('/')
assert(any([target in response for target in targets]))
|
Allow passing in the node binary path on init
|
import initialize from './initialize';
import register from './register';
import unregister from './unregister';
import { core } from './commands/lfsCommands';
import { loadGitattributeFiltersFromRepo, repoHasLfs } from './helpers';
import checkout from './commands/checkout';
import push from './commands/push';
import track from './commands/track';
import untrack from './commands/untrack';
import version from './commands/version';
import fetch from './commands/fetch';
import prune from './commands/prune';
import list from './commands/ls';
import testPointer from './commands/pointer';
import pull from './commands/pull';
import clone from './commands/clone';
import { setNodeBinaryPath } from './utils/authService';
import { dependencyCheck } from './utils/checkDependencies';
function LFS(nodegit) {
this.NodeGit = nodegit;
}
LFS.prototype = {
core,
checkout,
clone,
dependencyCheck,
fetch,
filters: loadGitattributeFiltersFromRepo,
repoHasLfs,
initialize,
list,
register,
testPointer,
track,
prune,
pull,
push,
version,
unregister,
untrack,
};
module.exports = (nodegit, nodeBinaryPath) => {
const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle
Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit);
module.exports = _NodeGit;
if (nodeBinaryPath) {
setNodeBinaryPath(nodeBinaryPath);
}
return _NodeGit;
};
|
import initialize from './initialize';
import register from './register';
import unregister from './unregister';
import { core } from './commands/lfsCommands';
import { loadGitattributeFiltersFromRepo, repoHasLfs } from './helpers';
import checkout from './commands/checkout';
import push from './commands/push';
import track from './commands/track';
import untrack from './commands/untrack';
import version from './commands/version';
import fetch from './commands/fetch';
import prune from './commands/prune';
import list from './commands/ls';
import testPointer from './commands/pointer';
import pull from './commands/pull';
import clone from './commands/clone';
import { dependencyCheck } from './utils/checkDependencies';
function LFS(nodegit) {
this.NodeGit = nodegit;
}
LFS.prototype = {
core,
checkout,
clone,
dependencyCheck,
fetch,
filters: loadGitattributeFiltersFromRepo,
repoHasLfs,
initialize,
list,
register,
testPointer,
track,
prune,
pull,
push,
version,
unregister,
untrack,
};
module.exports = (nodegit) => {
const _NodeGit = nodegit; // eslint-disable-line no-underscore-dangle
Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit);
module.exports = _NodeGit;
return _NodeGit;
};
|
Add % operator for modulo division
|
var prefixToInfix = require("./tools/prefix-to-infix");
module.exports = {
js: require("./functions/js"),
def: require("./functions/def"),
let: require("./functions/let"),
"`": require("./functions/`"),
try: require("./functions/try"),
catch: require("./functions/catch"),
".-": require("./functions/.-"),
".": require("./functions/..js"),
do: require("./functions/do"),
if: require("./functions/if"),
fn: require("./functions/fn"),
"=": require("./functions/=")
};
function defPrefixToInfix(operand, maxArgs) {
module.exports[operand] = prefixToInfix(operand, maxArgs);
}
["<", "+", "-", "*", "/", "%"].forEach(function(symbol) {
defPrefixToInfix(symbol);
});
|
var prefixToInfix = require("./tools/prefix-to-infix");
module.exports = {
js: require("./functions/js"),
def: require("./functions/def"),
let: require("./functions/let"),
"`": require("./functions/`"),
try: require("./functions/try"),
catch: require("./functions/catch"),
".-": require("./functions/.-"),
".": require("./functions/..js"),
do: require("./functions/do"),
if: require("./functions/if"),
fn: require("./functions/fn"),
"=": require("./functions/=")
};
function defPrefixToInfix(operand, maxArgs) {
module.exports[operand] = prefixToInfix(operand, maxArgs);
}
["<", "+", "-", "*", "/"].forEach(function(symbol) {
defPrefixToInfix(symbol);
});
|
Add a log to Exp2
|
#!/usr/bin/python3.4
"""
Exp2_DriveForward -- RedBot Experiment 2
Drive forward and stop.
Hardware setup:
The Power switch must be on, the motors must be connected, and the board must be receiving power
from the battery. The motor switch must also be switched to RUN.
"""
from pymata_aio.pymata3 import PyMata3
from RedBot import RedBotMotors
# This line "includes" the RedBot library into your sketch.
# Provides special objects, methods, and functions for the RedBot.
board = PyMata3()
motors = RedBotMotors(board)
# Instantiate the motor control object. This only needs to be done once.
def setup():
print("Left and right motors at full speed forward")
motors.drive(255) # Turn on Left and right motors at full speed forward.
board.sleep(2.0) # Waits for 2 seconds
print("Stop both motors")
motors.stop() # Stops both motors
def loop():
# Nothing here. We'll get to this in the next experiment.
pass
if __name__ == "__main__":
setup()
while True:
loop()
|
#!/usr/bin/python3.4
"""
Exp2_DriveForward -- RedBot Experiment 2
Drive forward and stop.
Hardware setup:
The Power switch must be on, the motors must be connected, and the board must be receiving power
from the battery. The motor switch must also be switched to RUN.
"""
from pymata_aio.pymata3 import PyMata3
from RedBot import RedBotMotors
# This line "includes" the RedBot library into your sketch.
# Provides special objects, methods, and functions for the RedBot.
board = PyMata3()
motors = RedBotMotors(board)
# Instantiate the motor control object. This only needs to be done once.
def setup():
motors.drive(255) # Turn on Left and right motors at full speed forward.
board.sleep(2.0) # Waits for 2 seconds
motors.stop() # Stops both motors
def loop():
# Nothing here. We'll get to this in the next experiment.
pass
if __name__ == "__main__":
setup()
while True:
loop()
|
Add comment for private constructor
|
<?php
namespace Oro\Bundle\ApiBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
final class NullTransformer implements DataTransformerInterface
{
/** @var NullTransformer|null */
private static $instance;
/**
* A private constructor to prevent create an instance of this class explicitly
*/
private function __construct()
{
}
/**
* @return NullTransformer
*/
public static function getInstance()
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
return $value;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
return $value;
}
}
|
<?php
namespace Oro\Bundle\ApiBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
final class NullTransformer implements DataTransformerInterface
{
/** @var NullTransformer|null */
private static $instance;
private function __construct()
{
}
/**
* @return NullTransformer
*/
public static function getInstance()
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
return $value;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
return $value;
}
}
|
Clear the timeout when the request does not timeout
|
var co = require('co');
module.exports = function(timeout) {
return function *(next) {
var ctx = this;
var tmr = null;
yield Promise.race([
new Promise(function(resolve, reject) {
tmr = setTimeout(function() {
var e = new Error('Request timeout');
e.status = 408;
reject(e);
}, timeout);
}),
new Promise(function(resolve, reject) {
co(function*() {
yield *next;
}).call(ctx, function(err) {
clearTimeout(tmr);
if(err) reject(err);
resolve();
});
})
]);
};
};
|
var co = require('co');
module.exports = function(timeout) {
return function *(next) {
var ctx = this;
yield Promise.race([
new Promise(function(resolve, reject) {
setTimeout(function() {
var e = new Error('Request timeout')
e.status = 408;
reject(e);
}, timeout);
}),
new Promise(function(resolve, reject) {
co(function*() {
yield *next;
}).call(ctx, function(err) {
if(err) reject(err);
resolve();
});
})
]);
};
};
|
Fix indentation & class namespace.
|
<?php namespace Northstar\Http\Controllers;
use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;
class AvatarController extends Controller
{
public function __construct(AWS $aws)
{
$this->aws = $aws;
}
/**
* Store a new avatar for a user.
* POST /users/{id}/avatar
*
* @param Request $request
* @param $id - User ID
* @return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
if ($request->file('photo')) {
$file = $request->file('photo');
} else {
$file = $request->photo;
}
$this->validate($request, [
'photo' => 'required'
]);
$filename = $this->aws->storeImage('avatars', $id, $file);
// Save filename to User model
$user = User::where("_id", $id)->first();
$user->photo = $filename;
$user->save();
// Respond to user with success and photo URL
return $this->respond($user);
}
}
|
<?php namespace Northstar\Http\Controllers;
use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;
class AvatarController extends Controller
{
public function __construct(AWS $aws)
{
$this->aws = $aws;
}
/**
* Store a new avatar for a user.
* POST /users/{id}/avatar
*
* @param Request $request
* @param $id - User ID
* @return Response
*/
public function store(Request $request, $id)
{
if ($request->file('photo')) {
$file = $request->file('photo');
} else {
$file = $request->photo;
}
$this->validate($request, [
'photo' => 'required'
]);
$filename = $this->aws->storeImage('avatars', $id, $file);
// Save filename to User model
$user = User::where("_id", $id)->first();
$user->photo = $filename;
$user->save();
// Respond to user with success and photo URL
return $this->respond($user);
}
}
|
Change presentation for primitive values in collection view
|
package com.intellij.debugger.streams.ui;
import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) {
super(project, value);
}
@Override
public String calcValueName() {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.calcValueName();
}
return value.type().name();
}
@Override
public boolean isShowIdLabel() {
return true;
}
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.getDescriptorEvaluation(debuggerContext);
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
}
}
|
package com.intellij.debugger.streams.ui;
import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
/**
* @author Vitaliy.Bibaev
*/
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
PrimitiveValueDescriptor(Project project, Value value) {
super(project, value);
}
@Override
public String calcValueName() {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.calcValueName();
}
return value.toString();
}
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.getDescriptorEvaluation(debuggerContext);
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
}
}
|
Make spawn_n() stub properly ignore errors in the child thread work
When we call spawn_n() normally, we fork off a thread that can run or
die on its own, without affecting the parent. In unit tests, we stub
this out to be a synchronous call, but we allow any exceptions that
occur in that work to bubble up to the caller. This is not normal
behavior and thus we should discard any such exceptions in order to
mimic actual behavior of a child thread.
Change-Id: I35ab21e9525aa76cced797436daa0b99a4fa99f2
Related-bug: #1349147
|
# Copyright (c) 2013 Rackspace Hosting
#
# 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.
"""This modules stubs out functions in nova.utils."""
from nova import utils
def stub_out_utils_spawn_n(stubs):
"""Stubs out spawn_n with a blocking version.
This aids testing async processes by blocking until they're done.
"""
def no_spawn(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
# NOTE(danms): This is supposed to simulate spawning
# of a thread, which would run separate from the parent,
# and die silently on error. If we don't catch and discard
# any exceptions here, we're not honoring the usual
# behavior.
pass
stubs.Set(utils, 'spawn_n', no_spawn)
|
# Copyright (c) 2013 Rackspace Hosting
#
# 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.
"""This modules stubs out functions in nova.utils."""
from nova import utils
def stub_out_utils_spawn_n(stubs):
"""Stubs out spawn_n with a blocking version.
This aids testing async processes by blocking until they're done.
"""
def no_spawn(func, *args, **kwargs):
return func(*args, **kwargs)
stubs.Set(utils, 'spawn_n', no_spawn)
|
Add Bart to PgSqlTools copyright.
|
<?php
/**
* Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl>
* Copyright (c) 2014 Andreas Fischer <bantu@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\DB;
/**
* Various PostgreSQL specific helper functions.
*/
class PgSqlTools {
/**
* @brief Resynchronizes all sequences of a database after using INSERTs
* without leaving out the auto-incremented column.
* @param \OC\DB\Connection $conn
* @return null
*/
public function resynchronizeDatabaseSequences(Connection $conn) {
$databaseName = $conn->getDatabase();
foreach ($conn->getSchemaManager()->listSequences() as $sequence) {
$sequenceName = $sequence->getName();
$sqlInfo = 'SELECT table_schema, table_name, column_name
FROM information_schema.columns
WHERE column_default = ? AND table_catalog = ?';
$sequenceInfo = $conn->fetchAssoc($sqlInfo, array(
"nextval('$sequenceName'::regclass)",
$databaseName
));
$tableName = $sequenceInfo['table_name'];
$columnName = $sequenceInfo['column_name'];
$sqlMaxId = "SELECT MAX($columnName) FROM $tableName";
$sqlSetval = "SELECT setval('$sequenceName', ($sqlMaxId))";
$conn->executeQuery($sqlSetval);
}
}
}
|
<?php
/**
* Copyright (c) 2014 Andreas Fischer <bantu@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\DB;
/**
* Various PostgreSQL specific helper functions.
*/
class PgSqlTools {
/**
* @brief Resynchronizes all sequences of a database after using INSERTs
* without leaving out the auto-incremented column.
* @param \OC\DB\Connection $conn
* @return null
*/
public function resynchronizeDatabaseSequences(Connection $conn) {
$databaseName = $conn->getDatabase();
foreach ($conn->getSchemaManager()->listSequences() as $sequence) {
$sequenceName = $sequence->getName();
$sqlInfo = 'SELECT table_schema, table_name, column_name
FROM information_schema.columns
WHERE column_default = ? AND table_catalog = ?';
$sequenceInfo = $conn->fetchAssoc($sqlInfo, array(
"nextval('$sequenceName'::regclass)",
$databaseName
));
$tableName = $sequenceInfo['table_name'];
$columnName = $sequenceInfo['column_name'];
$sqlMaxId = "SELECT MAX($columnName) FROM $tableName";
$sqlSetval = "SELECT setval('$sequenceName', ($sqlMaxId))";
$conn->executeQuery($sqlSetval);
}
}
}
|
Update package to show readme
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
def recursive_path(pack, path):
matches = []
for root, dirnames, filenames in os.walk(os.path.join(pack, path)):
for filename in filenames:
matches.append(os.path.join(root, filename)[len(pack) + 1:])
return matches
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = "Add unittest cell magics to IPython for easily running tests"
setup(
name="ipython_unittest",
version="0.2.6",
description="Add unittest cell magics to IPython for easily running tests",
long_description=long_description,
packages=find_packages(exclude=["tests_*", "tests"]),
package_data={
"ipython_unittest": recursive_path("ipython_unittest", "resources")},
author=("Joao Pimentel",),
author_email="joaofelipenp@gmail.com",
license="MIT",
keywords="ipython jupyter unittest tdd dojo",
url="https://github.com/JoaoFelipe/ipython-unittest"
)
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
def recursive_path(pack, path):
matches = []
for root, dirnames, filenames in os.walk(os.path.join(pack, path)):
for filename in filenames:
matches.append(os.path.join(root, filename)[len(pack) + 1:])
return matches
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = "Add unittest cell magics to IPython for easily running tests"
setup(
name="ipython_unittest",
version="0.2.4",
description="Add unittest cell magics to IPython for easily running tests",
long_description=long_description,
packages=find_packages(exclude=["tests_*", "tests"]),
package_data={
"ipython_unittest": recursive_path("ipython_unittest", "resources")},
author=("Joao Pimentel",),
author_email="joaofelipenp@gmail.com",
license="MIT",
keywords="ipython jupyter unittest tdd dojo",
url="https://github.com/JoaoFelipe/ipython-unittest"
)
|
Revert "The same thing, but their way haha"
This reverts commit ab12f6cc4593e81bc426a54e8aebc1671ac34e2a.
|
import os
from azure.storage import BlobService
def store(image, entity, entity_id):
blob_service = BlobService(account_name='shnergledata',
account_key=os.environ['BLOB_KEY'])
myblob = image.read()
name = '/' + entity + '/' + entity_id
blob_service.put_blob('images', name, myblob, x_ms_blob_type='BlockBlob')
return True
def retrieve(entity, entity_id):
blob_service = BlobService(account_name='shnergledata',
account_key=os.environ['BLOB_KEY'])
name = '/' + entity + '/' + entity_id
blob = blob_service.get_blob('images', name)
return blob
|
import os
from azure.storage import *
def store(image, entity, entity_id):
blob_service = BlobService(account_name='shnergledata',
account_key=os.environ['BLOB_KEY'])
myblob = image.read()
name = '/' + entity + '/' + entity_id
blob_service.put_blob('images', name, myblob, x_ms_blob_type='BlockBlob')
return True
def retrieve(entity, entity_id):
blob_service = BlobService(account_name='shnergledata',
account_key=os.environ['BLOB_KEY'])
name = '/' + entity + '/' + entity_id
blob = blob_service.get_blob('images', name)
return blob
|
Update more references to the old config style
|
import asyncio
import collections
import dashi.config
import dashi.db
import dashi.time
import datetime
import functools
import jinja2
import logging
import os
import pprint
LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def go():
config = dashi.config.parse()
template_loader = jinja2.FileSystemLoader(searchpath=config['paths']['template'])
template_environment = jinja2.Environment(loader=template_loader)
connection = dashi.db.connection()
authors = dashi.db.get_all_authors(connection)
return
LOGGER.debug(repo_stats)
try:
os.mkdir(config['paths']['output'])
except OSError:
pass
template = template_environment.get_template('index.html')
output = template.render(repo_stats=repo_stats)
path = os.path.join(config['paths']['output'], 'index.html')
with open(path, 'w') as f:
f.write(output)
|
import asyncio
import collections
import dashi.config
import dashi.db
import dashi.time
import datetime
import functools
import jinja2
import logging
import os
import pprint
LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def go():
config = dashi.config.parse()
template_loader = jinja2.FileSystemLoader(searchpath=config.template_path)
template_environment = jinja2.Environment(loader=template_loader)
connection = dashi.db.connection()
authors = dashi.db.get_all_authors(connection)
print(authors)
return
LOGGER.debug(repo_stats)
try:
os.mkdir(config.output_path)
except OSError:
pass
template = template_environment.get_template('index.html')
output = template.render(repo_stats=repo_stats)
path = os.path.join(config.output_path, 'index.html')
with open(path, 'w') as f:
f.write(output)
|
Fix file headers for missing BSD license.
|
/*
* Copyright (C) 2009 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 15. August 2009 by Joerg Schaible
*/
package com.thoughtworks.xstream.io.xml;
/**
* A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
*
* @author Jörg Schaible
* @since upcoming
*/
public class XStream11NameCoder extends XmlFriendlyNameCoder {
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeAttribute(String attributeName) {
return attributeName;
}
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeNode(String elementName) {
return elementName;
}
}
|
/*
* Copyright (C) 2009 XStream Committers.
* All rights reserved.
*
* Created on 15. August 2009 by Joerg Schaible
*/
package com.thoughtworks.xstream.io.xml;
/**
* A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
*
* @author Jörg Schaible
* @since upcoming
*/
public class XStream11NameCoder extends XmlFriendlyNameCoder {
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeAttribute(String attributeName) {
return attributeName;
}
/**
* {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
* compatibility.
*/
public String decodeNode(String elementName) {
return elementName;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.