text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix url shortening for small domains | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
if 'id' in response:
return response['id']
return url
| import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
return response['id']
|
Disable creating image for now | var _ = require('underscore'),
fs = require('fs'),
path = require('path'),
buildImage = require('./docker_build_image').buildImage,
dockerImages = require('../docker_config/image_list.json');
//check whether the image exist locally
//docker images | grep imageName
var imageExist = function(imageName){
return true;
// return _.contains(dockerImages, imageName);
};
var addImageName = function(imageName){
var oldImages = dockerImages; //get a local reference
oldImages.push(imageName);
var configPath = path.join(__dirname, '../docker_config');
fs.writeFileSync(configPath + '/image_list.json', JSON.stringify(oldImages), 'utf8');
};
var createImage = function(imageName){
//build docker image
buildImage(imageName);
//save the image name
addImageName(imageName);
};
var findOrCreateImage = module.exports = function(imageName){
if( imageExist(imageName) ){
//docker image exist, pass
console.log('exist');
} else {
//create image
console.log('Not exist');
createImage(imageName);
}
}; | var _ = require('underscore'),
fs = require('fs'),
path = require('path'),
buildImage = require('./docker_build_image').buildImage,
dockerImages = require('../docker_config/image_list.json');
//check whether the image exist locally
//docker images | grep imageName
var imageExist = function(imageName){
return _.contains(dockerImages, imageName);
};
var addImageName = function(imageName){
var oldImages = dockerImages; //get a local reference
oldImages.push(imageName);
var configPath = path.join(__dirname, '../docker_config');
fs.writeFileSync(configPath + '/image_list.json', JSON.stringify(oldImages), 'utf8');
};
var createImage = function(imageName){
//build docker image
buildImage(imageName);
//save the image name
addImageName(imageName);
};
var findOrCreateImage = module.exports = function(imageName){
if( imageExist(imageName) ){
//docker image exist, pass
console.log('exist');
} else {
//create image
console.log('Not exist');
createImage(imageName);
}
}; |
Fix a formatting issue when formatting time | var exports = {};
exports.simplePrint = function(video) {
return `**${video.title}**`;
};
exports.prettyPrint = function(video) {
viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};
exports.prettyPrintWithUser = function(video) {
return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};
exports.simplify = function(video) {
return {
vid: video.vid,
title: video.title,
author: video.author,
view_count: video.view_count,
};
};
exports.prettyTime = function(ms) {
var seconds = ms / 1000;
var actualSeconds = Math.ceil(seconds % 60);
var paddedSeconds = String('00' + actualSeconds).slice(-2);
var minutes = Math.round((seconds - actualSeconds) / 60);
return `${minutes}:${paddedSeconds}`;
};
module.exports = exports;
| var exports = {};
exports.simplePrint = function(video) {
return `**${video.title}**`;
};
exports.prettyPrint = function(video) {
viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};
exports.prettyPrintWithUser = function(video) {
return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};
exports.simplify = function(video) {
return {
vid: video.vid,
title: video.title,
author: video.author,
view_count: video.view_count,
};
};
exports.prettyTime = function(ms) {
var seconds = ms / 1000;
var actualSeconds = Math.ceil(seconds % 60);
var minutes = Math.round((seconds - actualSeconds) / 60);
return `${minutes}:${actualSeconds}`;
};
module.exports = exports;
|
Update to copy new scripts | import os
import shutil
def main():
cwd = os.getcwd()
if not cwd.endswith(os.path.join('FRENSIE', 'scripts')):
print 'This script must be run in \"FRENSIE/scipts\"'
print 'Your CWD is', cwd
return 1
os.chdir('../../')
os.mkdir('frensie_build_tree')
#os.renames('FRENSIE', 'frensie_build_tree/FRENSIE')
os.symlink(os.path.abspath('FRENSIE'), 'frensie_build_tree/FRENSIE')
os.chdir('frensie_build_tree')
os.symlink('FRENSIE', 'src')
os.mkdir('deps')
os.mkdir('deps/install')
os.mkdir('deps/tars')
os.mkdir('build')
shutil.copyfile('src/scripts/makefile.deps', 'deps/makefile')
shutil.copyfile('src/scripts/lazy.sh', 'deps/lazy.sh')
shutil.copyfile('src/scripts/frensie.sh', 'build/frensie.sh')
#shutil.copyfile('src/scripts/source_deps.sh', 'build/source_deps.sh')
print """
To build dependencies move necessary tars to deps/tars.
cd to frensie_build_tree/deps and run make all.
To once all dependecies exist in frensie_build_tree/deps/install
cd to frensie_build_tree/build and run bash frensie.sh
"""
if __name__ == '__main__':
main()
| import os
import shutil
def main():
cwd = os.getcwd()
if not cwd.endswith(os.path.join('FRENSIE', 'scripts')):
print 'This script must be run in \"FRENSIE/scipts\"'
print 'Your CWD is', cwd
return 1
os.chdir('../../')
os.mkdir('frensie_build_tree')
#os.renames('FRENSIE', 'frensie_build_tree/FRENSIE')
os.symlink(os.path.abspath('FRENSIE'), 'frensie_build_tree/FRENSIE')
os.chdir('frensie_build_tree')
os.symlink('FRENSIE', 'src')
os.mkdir('deps')
os.mkdir('deps/install')
os.mkdir('deps/tars')
os.mkdir('build')
shutil.copyfile('src/scripts/makefile.deps', 'deps/makefile')
shutil.copyfile('src/scripts/frensie.sh', 'build/frensie.sh')
print """
To build dependencies move necessary tars to deps/tars.
cd to frensie_build_tree/deps and run make all.
To once all dependecies exist in frensie_build_tree/deps/install
cd to frensie_build_tree/build and run bash frensie.sh
"""
if __name__ == '__main__':
main()
|
Add email to contact form | <?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'normington@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: robot@normo.uk\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
| <?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?> |
Add group list command to docs | import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (list | create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
| import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
|
Add tokenization to the WordNik demo | import nltk
from wordnik import swagger, WordApi, AccountApi
client = swagger.ApiClient(
'dd3d32ae6b4709e1150040139c308fb77446e0a8ecc93db31',
'https://api.wordnik.com/v4')
word_api = WordApi.WordApi(client)
toktok = nltk.ToktokTokenizer()
words = ['paint', 'mimic', 'mimics', 'francie', 'frolic', 'funhouse']
for word in words:
print('=== {} ==='.format(word))
defs = word_api.getDefinitions(word)
if not defs:
print("no definitions")
continue
for def_ in defs:
fmt_str = "{} --- {}"
tokenized_def = toktok.tokenize(def_.text.lower())
tokenized_def = [s.encode('utf-8') for s in tokenized_def]
print(fmt_str.format(def_.sourceDictionary,
tokenized_def))
account_api = AccountApi.AccountApi(client)
for i in range(5):
print("Attempt {}".format(i))
status = account_api.getApiTokenStatus()
print("Remaining_calls: {}".format(status.remainingCalls))
| from wordnik import swagger, WordApi, AccountApi
client = swagger.ApiClient(
'dd3d32ae6b4709e1150040139c308fb77446e0a8ecc93db31',
'https://api.wordnik.com/v4')
word_api = WordApi.WordApi(client)
words = ['paint', 'mimic', 'mimics', 'francie', 'frolic', 'funhouse']
for word in words:
print('=== {} ==='.format(word))
defs = word_api.getDefinitions(word)
if not defs:
print("no definitions")
continue
for def_ in defs:
fmt_str = "{} --- {}"
print(fmt_str.format(def_.sourceDictionary, def_.text.encode('utf-8')))
account_api = AccountApi.AccountApi(client)
for i in range(5):
print("Attempt {}".format(i))
status = account_api.getApiTokenStatus()
print("Remaining_calls: {}".format(status.remainingCalls))
|
Fix bug: dont use obs[0] as first obstacle
Should check if obstacle is in front of tRex | var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
ai.speedDroping = false;
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 350 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
var next = 0;
if (distance < 0)
next = 1;
distance = (obs[next].xPos + obs[next].width) - api.getPlayer().xPos;
var player = api.getPlayer();
if (0 < distance && distance < bound && obs[next].yPos != 50 && obs[next].yPos != 75 && player.status != 'JUMPING'){
api.duckStop();
api.jump();
}
else if (player.status == 'JUMPING'){
if (player.xPos > obs[0].xPos + obs[0].width / 2 && !this.speedDroping){
api.speedDrop();
this.speedDroping = true;
}
}
else{
this.speedDroping = false;
api.duck();
}
}
} | var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
ai.speedDroping = false;
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
var player = api.getPlayer();
if (0 < distance && distance < bound && obs[0].yPos != 50 && obs[0].yPos != 75 && player.status != 'JUMPING'){
api.duckStop();
api.jump();
}
else if (player.status == 'JUMPING'){
if (player.xPos > obs[0].xPos + obs[0].width && !this.speedDroping){
api.speedDrop();
this.speedDroping = true;
}
}
else{
this.speedDroping = false;
api.duck();
}
}
} |
Support reverse lookup of partnership when it is an MDN | package org.openas2.partner;
import java.util.List;
import java.util.Map;
import org.openas2.Component;
import org.openas2.OpenAS2Exception;
import org.openas2.message.Message;
import org.openas2.message.MessageMDN;
/**
* original author unknown
*
* added getPartners method
* @author joseph mcverry
*
*/
public interface PartnershipFactory extends Component {
public static final String COMPID_PARTNERSHIP_FACTORY = "partnershipfactory";
// throws an exception if the partnership doesn't exist
public Partnership getPartnership(Partnership p, boolean reverseLookup) throws OpenAS2Exception;
// looks up and fills in any header info for a specific msg's partnership
public void updatePartnership(Message msg, boolean overwrite) throws OpenAS2Exception;
// looks up and fills in any header info for a specific msg's partnership
public void updatePartnership(MessageMDN mdn, boolean overwrite) throws OpenAS2Exception;
public void setPartnerships(List<Partnership> list);
public List<Partnership> getPartnerships();
public Map<String,Object> getPartners();
} | package org.openas2.partner;
import java.util.List;
import java.util.Map;
import org.openas2.Component;
import org.openas2.OpenAS2Exception;
import org.openas2.message.Message;
import org.openas2.message.MessageMDN;
/**
* original author unknown
*
* added getPartners method
* @author joseph mcverry
*
*/
public interface PartnershipFactory extends Component {
public static final String COMPID_PARTNERSHIP_FACTORY = "partnershipfactory";
// throws an exception if the partnership doesn't exist
public Partnership getPartnership(Partnership p) throws OpenAS2Exception;
// looks up and fills in any header info for a specific msg's partnership
public void updatePartnership(Message msg, boolean overwrite) throws OpenAS2Exception;
// looks up and fills in any header info for a specific msg's partnership
public void updatePartnership(MessageMDN mdn, boolean overwrite) throws OpenAS2Exception;
public void setPartnerships(List<Partnership> list);
public List<Partnership> getPartnerships();
public Map<String,Object> getPartners();
} |
Watch files which fail before emitting a resource
Regression introduced by the CSS watching code (specifically, f230eba62)
by the sourceIsWatched check. We need to be able to tell the difference
between "source handler didn't do anything because there was an error"
and "source handler didn't do anything because it's web-specific and
this is an os arch".
A simple fix would have been to interpret compileStep.error as
"sourceIsWatched = true", but I didn't think of that until after doing
it the slightly more complicated but more precise way :)
Also, ensure that if the runner rebuilds the client and there's an
error, it properly kills the app process (and the watchers and the
keepalive interval, etc). | var fs = Npm.require('fs');
var stylus = Npm.require('stylus');
var nib = Npm.require('nib');
var path = Npm.require('path');
var Future = Npm.require('fibers/future');
Plugin.registerSourceHandler("styl", {archMatching: 'web'}, function (compileStep) {
var f = new Future;
stylus(compileStep.read().toString('utf8'))
.use(nib())
.set('filename', compileStep.inputPath)
// Include needed to allow relative @imports in stylus files
.include(path.dirname(compileStep._fullInputPath))
.render(f.resolver());
try {
var css = f.wait();
} catch (e) {
compileStep.error({
message: "Stylus compiler error: " + e.message
});
return;
}
compileStep.addStylesheet({
path: compileStep.inputPath + ".css",
data: css
});
});
// Register import.styl files with the dependency watcher, without actually
// processing them. There is a similar rule in the less package.
Plugin.registerSourceHandler("import.styl", function () {
// Do nothing
});
| var fs = Npm.require('fs');
var stylus = Npm.require('stylus');
var nib = Npm.require('nib');
var path = Npm.require('path');
var Future = Npm.require('fibers/future');
Plugin.registerSourceHandler("styl", function (compileStep) {
// XXX annoying that this is replicated in .css, .less, and .styl
if (! compileStep.archMatches('web')) {
// XXX in the future, might be better to emit some kind of a
// warning if a stylesheet is included on the server, rather than
// silently ignoring it. but that would mean you can't stick .css
// at the top level of your app, which is kind of silly.
return;
}
var f = new Future;
stylus(compileStep.read().toString('utf8'))
.use(nib())
.set('filename', compileStep.inputPath)
// Include needed to allow relative @imports in stylus files
.include(path.dirname(compileStep._fullInputPath))
.render(f.resolver());
try {
var css = f.wait();
} catch (e) {
compileStep.error({
message: "Stylus compiler error: " + e.message
});
return;
}
compileStep.addStylesheet({
path: compileStep.inputPath + ".css",
data: css
});
});
// Register import.styl files with the dependency watcher, without actually
// processing them. There is a similar rule in the less package.
Plugin.registerSourceHandler("import.styl", function () {
// Do nothing
});
|
Revert "fixed the bug where the server wouldn't die when project wasn't opened" | "use strict";
let StepNC = require('../../../../../STEPNode/build/Release/StepNC');
let fs = require("fs");
//Query for a json file that maps all projects in the data directory
//to a particular path in the data folder
let path;
let find;
let apt;
let tol;
let ms;
function init(path, machinetool){
this.find = new StepNC.Finder();
this.apt = new StepNC.AptStepMaker();
this.tol = new StepNC.Tolerance();
this.ms = new StepNC.machineState(path);
if(machinetool !== ""){
if(!this.ms.LoadMachine(machinetool))
console.log("ERROR: Machinetool was not loaded");
else
console.log("Loaded Machine Successfully")
}
this.find.OpenProject(path);
this.apt.OpenProject(path);
return;
}
module.exports.init = init;
module.exports.find = find;
module.exports.apt = apt;
module.exports.tol = tol;
module.exports.ms = ms; | "use strict";
let StepNC = require('../../../../../STEPNode/build/Release/StepNC');
let fs = require("fs");
//Query for a json file that maps all projects in the data directory
//to a particular path in the data folder
let path;
let find;
let apt;
let tol;
let ms;
function init(path, machinetool){
this.find = new StepNC.Finder();
this.apt = new StepNC.AptStepMaker();
this.tol = new StepNC.Tolerance();
this.ms = new StepNC.machineState(path);
if(!this.ms)
process.exit();
if(machinetool !== ""){
if(!this.ms.LoadMachine(machinetool))
console.log("ERROR: Machinetool was not loaded");
else
console.log("Loaded Machine Successfully")
}
if(!this.find.OpenProject(path))
process.exit();
if(!this.apt.OpenProject(path))
process.exit();
return;
}
module.exports.init = init;
module.exports.find = find;
module.exports.apt = apt;
module.exports.tol = tol;
module.exports.ms = ms; |
Fix export of footnote labels. | import { findChild, findAllChildren } from '../util/domHelpers'
import { getLabel } from '../../shared/nodeHelpers'
// TODO: at some point we want to retain the label and determine if the label should be treated as custom
// or be generated.
export default class FootnoteConverter {
get type () { return 'fn' }
get tagName () { return 'fn' }
import (el, node, importer) {
let labelEl = findChild(el, 'label')
let pEls = findAllChildren(el, 'p')
if (labelEl) {
node.label = labelEl.text()
}
node._childNodes = pEls.map(el => importer.convertElement(el).id)
}
export (node, el, exporter) {
const $$ = exporter.$$
// We gonna need to find another way for node states. I.e. for labels we will have
// a hybrid scenario where the labels are either edited manually, and thus we need to record ops,
// or they are generated without persisting operations (e.g. think about undo/redo, or collab)
// my suggestion would be to introduce volatile ops, they would be excluded from the DocumentChange, that is stored in the change history,
// or used for collaborative editing.
let label = getLabel(node)
if (label) {
el.append($$('label').text(label))
}
el.append(node.getChildren().map(p => exporter.convertNode(p)))
}
}
| import { findChild, findAllChildren } from '../util/domHelpers'
export default class FootnoteConverter {
get type () { return 'fn' }
get tagName () { return 'fn' }
import (el, node, importer) {
// TODO: at some point we want to retain the label and determine if the label should be treated as custom
// or be generated
let labelEl = findChild(el, 'label')
let pEls = findAllChildren(el, 'p')
if (labelEl) {
node.label = labelEl.text()
}
node._childNodes = pEls.map(el => importer.convertElement(el).id)
}
export (node, el, exporter) {
const $$ = exporter.$$
el.append($$('label').text(node.label))
el.append(node.getChildren().map(p => exporter.convertNode(p)))
}
}
|
Fix git URL so Atmosphere shows it | Package.describe({
name: 'astrocoders:infinite-scroll',
version: '0.0.1',
summary: 'Simple infinite scroll',
git: 'https://github.com/Astrocoders/meteor-infinite-scroll/',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.2.0.2');
api.use([
'ecmascript',
'jquery',
'ui',
'blaze',
'templating',
'underscore'
]);
api.addFiles([
'infinite-scroll.js'
], 'client');
api.export('InfiniteScroll', 'client');
});
Package.onTest(function(api) {
api.use('ecmascript');
api.use('tinytest');
api.use('astrocoders:infinite-scroll');
api.addFiles('infinite-scroll-tests.js');
});
| Package.describe({
name: 'astrocoders:infinite-scroll',
version: '0.0.1',
summary: 'Simple infinite scroll',
git: 'git@github.com:Astrocoders/meteor-infinite-scroll.git',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.2.0.2');
api.use([
'ecmascript',
'jquery',
'ui',
'blaze',
'templating',
'underscore'
]);
api.addFiles([
'infinite-scroll.js'
], 'client');
api.export('InfiniteScroll', 'client');
});
Package.onTest(function(api) {
api.use('ecmascript');
api.use('tinytest');
api.use('astrocoders:infinite-scroll');
api.addFiles('infinite-scroll-tests.js');
});
|
Make external static folder be *nix like
When Windows paths are received, like `C:\Users\USERNAME\AppData\Local\Temp\external\`, they will be changed to `C:/Users/USERNAME/AppData/Local/Temp/external`. | package spark.staticfiles;
import static spark.utils.StringUtils.removeLeadingAndTrailingSlashesFrom;
import java.nio.file.Paths;
/**
* Created by Per Wendel on 2016-11-05.
*/
public class StaticFilesFolder {
private static volatile String local;
private static volatile String external;
public static final void localConfiguredTo(String folder) {
local = removeLeadingAndTrailingSlashesFrom(folder);
}
public static final void externalConfiguredTo(String folder) {
external = removeLeadingAndTrailingSlashesFrom(
Paths.get(folder).toAbsolutePath().toString().replace("\\", "/")
);
}
public static final String local() {
return local;
}
public static final String external() {
return external;
}
}
| package spark.staticfiles;
import static spark.utils.StringUtils.removeLeadingAndTrailingSlashesFrom;
/**
* Created by Per Wendel on 2016-11-05.
*/
public class StaticFilesFolder {
private static volatile String local;
private static volatile String external;
public static final void localConfiguredTo(String folder) {
local = removeLeadingAndTrailingSlashesFrom(folder);
}
public static final void externalConfiguredTo(String folder) {
external = removeLeadingAndTrailingSlashesFrom(folder);
}
public static final String local() {
return local;
}
public static final String external() {
return external;
}
}
|
Disable django.contrib.sites tests in Jenkins. | # NOTE: local.py must be an empty file when using this configuration.
from .defaults import *
# Put jenkins environment specific overrides below.
INSTALLED_APPS += ('django_jenkins',)
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DEBUG = False
TEMPLATE_DEBUG = False
# Test all INSTALLED_APPS by default
PROJECT_APPS = list(INSTALLED_APPS)
# Some of these tests fail, and it's not our fault
# https://code.djangoproject.com/ticket/17966
PROJECT_APPS.remove('django.contrib.auth')
# This app fails with a strange error:
# DatabaseError: no such table: django_comments
# Not sure what's going on so it's disabled for now.
PROJECT_APPS.remove('django.contrib.sites')
# https://github.com/django-extensions/django-extensions/issues/154
PROJECT_APPS.remove('django_extensions')
PROJECT_APPS.remove('django_extensions.tests')
# FIXME: We need to fix the django_polymorphic tests
PROJECT_APPS.remove('polymorphic')
# Disable pylint becasue it seems to be causing problems
JENKINS_TASKS = (
# 'django_jenkins.tasks.run_pylint',
'django_jenkins.tasks.with_coverage',
'django_jenkins.tasks.django_tests',
)
| # NOTE: local.py must be an empty file when using this configuration.
from .defaults import *
# Put jenkins environment specific overrides below.
INSTALLED_APPS += ('django_jenkins',)
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DEBUG = False
TEMPLATE_DEBUG = False
# Test all INSTALLED_APPS by default
PROJECT_APPS = list(INSTALLED_APPS)
# Some of these tests fail, and it's not our fault
# https://code.djangoproject.com/ticket/17966
PROJECT_APPS.remove('django.contrib.auth')
# https://github.com/django-extensions/django-extensions/issues/154
PROJECT_APPS.remove('django_extensions')
PROJECT_APPS.remove('django_extensions.tests')
# FIXME: We need to fix the django_polymorphic tests
PROJECT_APPS.remove('polymorphic')
# Disable pylint becasue it seems to be causing problems
JENKINS_TASKS = (
# 'django_jenkins.tasks.run_pylint',
'django_jenkins.tasks.with_coverage',
'django_jenkins.tasks.django_tests',
)
|
Revert "Add custom launcher for karma"
This reverts commit dd80f254f407429aeaf5ca5c4fb414363836c267. | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
}; | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
singleRun: false
});
};
|
Adjust plugin references to new covistra-system name | /**
Copyright 2015 Covistra Technologies Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
var P = require('bluebird'),
Calibrate = require('calibrate'),
_ = require('lodash');
module.exports = function(server) {
var SystemStatus = server.plugins['covistra-system'].SystemStatus;
function handler(req, reply) {
server.log(['plugin', 'users', 'debug'], "Handling system status");
SystemStatus.reportSystemStatus().catch(Calibrate.error).then(reply);
}
return {
method: 'GET',
path: '/status',
handler: handler,
config: {
tags: ['api']
}
};
};
| /**
Copyright 2015 Covistra Technologies Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
var P = require('bluebird'),
Calibrate = require('calibrate'),
_ = require('lodash');
module.exports = function(server) {
var SystemStatus = server.plugins['system'].SystemStatus;
function handler(req, reply) {
server.log(['plugin', 'users', 'debug'], "Handling system status");
SystemStatus.reportSystemStatus().catch(Calibrate.error).then(reply);
}
return {
method: 'GET',
path: '/status',
handler: handler,
config: {
tags: ['api']
}
};
};
|
Change the way to find the controller (inside the component) | // Dependencies
import Ember from 'ember';
import layout from '../templates/components/yebo-search';
/**
The search form
@class YeboDetails
@namespace Component
@extends Ember.Component
*/
export default Ember.Component.extend({
layout: layout,
// The text that is going to be searched
searchText: '',
actions: {
/**
* Transition to the /products route with param search
*/
search: function() {
// Search Text
let searchText = this.get('searchText');
// Check if the searchText is higher than 2
// @todo Show some kind of error
if( searchText.length < 3 )
return;
// Get the current controller
let controller = this.get('container').lookup('controller:application');
// Transition to the products page
controller.transitionToRoute('yebo.products', { queryParams: { search: searchText } });
}
}
});
| // Dependencies
import Ember from 'ember';
import layout from '../templates/components/yebo-search';
/**
The search form
@class YeboDetails
@namespace Component
@extends Ember.Component
*/
export default Ember.Component.extend({
layout: layout,
// The text that is going to be searched
searchText: '',
actions: {
/**
* Transition to the /products route with param search
*/
search: function() {
// Search Text
let searchText = this.get('searchText');
// Check if the searchText is higher than 2
// @todo Show some kind of error
if( searchText.length < 3 )
return;
// Get the current controller
// @todo Check if _controller is the correct to use in this case
let controller = this._controller;
// Transition to the products page
controller.transitionToRoute('yebo.products', { queryParams: { search: searchText } });
}
}
});
|
Add offer_id to channel interface | <?php
namespace MssPhp\Schema\Response;
use JMS\Serializer\Annotation\Type;
class Channel {
/**
* @Type("string")
*/
public $channel_id;
/**
* @Type("integer")
*/
public $offer_id;
/**
* @Type("MssPhp\Schema\Response\OfferDescription")
*/
public $offer_description;
/**
* @Type("MssPhp\Schema\Response\RoomPrices")
*/
public $room_price;
/**
* @Type("MssPhp\Schema\Response\RoomDescription")
*/
public $room_description;
/**
* @Type("MssPhp\Schema\Response\ServicePrice")
*/
public $service_price;
/**
* @Type("integer")
*/
public $from_price;
/**
* @Type("MssPhp\Schema\Response\BasePrice")
*/
public $base_price;
/**
* @Type("MssPhp\Schema\Response\CancelPolicies")
*/
public $cancel_policies;
/**
* @Type("MssPhp\Schema\Response\PaymentTerms")
*/
public $payment_terms;
}
| <?php
namespace MssPhp\Schema\Response;
use JMS\Serializer\Annotation\Type;
class Channel {
/**
* @Type("string")
*/
public $channel_id;
/**
* @Type("MssPhp\Schema\Response\OfferDescription")
*/
public $offer_description;
/**
* @Type("MssPhp\Schema\Response\RoomPrices")
*/
public $room_price;
/**
* @Type("MssPhp\Schema\Response\RoomDescription")
*/
public $room_description;
/**
* @Type("MssPhp\Schema\Response\ServicePrice")
*/
public $service_price;
/**
* @Type("integer")
*/
public $from_price;
/**
* @Type("MssPhp\Schema\Response\BasePrice")
*/
public $base_price;
/**
* @Type("MssPhp\Schema\Response\CancelPolicies")
*/
public $cancel_policies;
/**
* @Type("MssPhp\Schema\Response\PaymentTerms")
*/
public $payment_terms;
}
|
Add base path to test application constructor | <?php
namespace AlgoWeb\PODataLaravel\Models;
use Illuminate\Foundation\Application;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\ProviderRepository;
class TestApplication extends Application
{
protected $filesys;
protected $inConsole = true;
public function __construct(Filesystem $file)
{
parent::__construct(dirname(__DIR__));
$this->filesys = $file;
}
/**
* Register all of the configured providers.
*
* @return void
*/
public function registerConfiguredProviders()
{
$this->basePath = dirname(__DIR__);
$manifestPath = $this->getCachedServicesPath();
(new ProviderRepository($this, $this->filesys, $manifestPath))
->load($this->config['app.providers']);
}
public function runningInConsole()
{
return $this->inConsole;
}
public function setConsole($flag)
{
$this->inConsole = true === $flag;
}
}
| <?php
namespace AlgoWeb\PODataLaravel\Models;
use Illuminate\Foundation\Application;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\ProviderRepository;
class TestApplication extends Application
{
protected $filesys;
protected $inConsole = true;
public function __construct(Filesystem $file)
{
parent::__construct();
$this->filesys = $file;
}
/**
* Register all of the configured providers.
*
* @return void
*/
public function registerConfiguredProviders()
{
$this->basePath = dirname(__DIR__);
$manifestPath = $this->getCachedServicesPath();
(new ProviderRepository($this, $this->filesys, $manifestPath))
->load($this->config['app.providers']);
}
public function runningInConsole()
{
return $this->inConsole;
}
public function setConsole($flag)
{
$this->inConsole = true === $flag;
}
} |
Fix JS require for hotwired/turbo | /* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
require("@hotwired/turbo-rails")
import { preferredDistanceUnit, preferredElevationUnit, distanceToPreferred, elevationToPreferred } from 'utils/units';
global.preferredDistanceUnit = preferredDistanceUnit;
global.preferredElevationUnit = preferredElevationUnit;
global.distanceToPreferred = distanceToPreferred;
global.elevationToPreferred = elevationToPreferred;
import 'utils/growl';
import TurboLinksAdapter from 'vue-turbolinks';
Vue.use(TurboLinksAdapter);
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"
const application = Application.start()
const context = require.context("controllers", true, /.js$/)
application.load(definitionsFromContext(context))
| /* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
import { preferredDistanceUnit, preferredElevationUnit, distanceToPreferred, elevationToPreferred } from 'utils/units';
global.preferredDistanceUnit = preferredDistanceUnit;
global.preferredElevationUnit = preferredElevationUnit;
global.distanceToPreferred = distanceToPreferred;
global.elevationToPreferred = elevationToPreferred;
import "@hotwired/turbo"
import 'utils/growl';
import TurboLinksAdapter from 'vue-turbolinks';
Vue.use(TurboLinksAdapter);
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"
const application = Application.start()
const context = require.context("controllers", true, /.js$/)
application.load(definitionsFromContext(context))
|
Trim the team name before adding new team. | function viewTeams() {
getTeams(
success = function (data) {
populateTeamsTable(data.teams);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateTeamsTable(data) {
var teams = _.sortBy(data, function (d) {return d.name.toLowerCase()});
var teamsHtml = templates.teamList(teams);
$('.section').html(teamsHtml);
$('.collections-select-table tbody tr').click(function () {
$('.collections-select-table tbody tr').removeClass('selected');
$(this).addClass('selected');
var teamId = $(this).attr('data-id');
viewTeamDetails(teamId);
});
$('.form-create-team').submit(function (e) {
e.preventDefault();
var teamName = $('#create-team-name').val();
if (teamName.length < 1) {
sweetAlert("Please enter a user name.");
return;
}
teamName = teamName.trim();
postTeam(teamName);
});
}
}
| function viewTeams() {
getTeams(
success = function (data) {
populateTeamsTable(data.teams);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateTeamsTable(data) {
var teams = _.sortBy(data, function (d) {return d.name.toLowerCase()});
var teamsHtml = templates.teamList(teams);
$('.section').html(teamsHtml);
$('.collections-select-table tbody tr').click(function () {
$('.collections-select-table tbody tr').removeClass('selected');
$(this).addClass('selected');
var teamId = $(this).attr('data-id');
viewTeamDetails(teamId);
});
$('.form-create-team').submit(function (e) {
e.preventDefault();
var teamName = $('#create-team-name').val();
if (teamName.length < 1) {
sweetAlert("Please enter a user name.");
return;
}
postTeam(teamName);
});
}
}
|
Use the existing version of params from secrets
This way we don't need to add them manually! | #!/usr/bin/env python
from email.mime.text import MIMEText
import os
from subprocess import call
import sys
def send(recipient, sender, sender_name, subject, body):
email_params_file = 'configuration-secure/jenkins/cut-release-branch/email_params.txt'
email_params_file = os.environ.get('CONFIGURATION_EMAIL_PARAMS', email_params_file)
with open(email_params_file, 'rt') as fin:
with open('email.txt', 'wt') as fout:
for line in fin:
line = line.replace('{RECIPIENT}', recipient).replace('{SENDER}', sender).replace('{SENDER_NAME}', sender_name).replace('{SUBJECT}', subject).replace('{BODY}', body)
fout.write(line)
cmd = ['openssl', 's_client', '-crlf', '-quiet', '-connect', 'email-smtp.us-east-1.amazonaws.com:465']
with open('email.txt') as fout:
call(cmd, stdin=fout)
call(['rm', 'email.txt'])
if __name__ == '__main__':
recipient = sys.argv[1]
sender = sys.argv[2]
sender_name = sys.argv[3]
subject = sys.argv[4]
path_file = sys.argv[5]
with open(path_file) as file_input:
body = file_input.read()
result = send(recipient, sender, sender_name, subject, body)
| #!/usr/bin/env python
from email.mime.text import MIMEText
from subprocess import call
import sys
def send(recipient, sender, sender_name, subject, body):
with open('configuration/stanford/bin/email_params.txt', 'rt') as fin:
with open('email.txt', 'wt') as fout:
for line in fin:
line = line.replace('{RECIPIENT}', recipient).replace('{SENDER}', sender).replace('{SENDER_NAME}', sender_name).replace('{SUBJECT}', subject).replace('{BODY}', body)
fout.write(line)
cmd = ['openssl', 's_client', '-crlf', '-quiet', '-connect', 'email-smtp.us-east-1.amazonaws.com:465']
with open('email.txt') as fout:
call(cmd, stdin=fout)
call(['rm', 'email.txt'])
if __name__ == '__main__':
recipient = sys.argv[1]
sender = sys.argv[2]
sender_name = sys.argv[3]
subject = sys.argv[4]
path_file = sys.argv[5]
with open(path_file) as file_input:
body = file_input.read()
result = send(recipient, sender, sender_name, subject, body)
|
[FIX] Use sudo to prevent errors with signup_get_auth_param. | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, fields, api, _
class SaleOrder(models.Model):
_inherit = 'sale.order'
activity_date_deadline = fields.Date(
groups="base.group_user,"
"portal_sale_distributor.group_portal_distributor"
)
def action_confirm_distributor(self):
self.sudo().message_post(
body=_("Pedido confirmado por %s") % self.env.user.name,
subtype='mt_comment')
self = self.sudo()
return self.action_confirm()
@api.onchange('partner_id')
def onchange_partner_id_warning(self):
""" desactivamos warning para portal distributor
"""
if self.env.user.has_group(
'portal_sale_distributor.group_portal_distributor'):
return {}
else:
return super().onchange_partner_id_warning()
| ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, fields, api, _
class SaleOrder(models.Model):
_inherit = 'sale.order'
activity_date_deadline = fields.Date(
groups="base.group_user,"
"portal_sale_distributor.group_portal_distributor"
)
def action_confirm_distributor(self):
self.message_post(
body=_("Pedido confirmado por %s") % self.env.user.name,
subtype='mt_comment')
self = self.sudo()
return self.action_confirm()
@api.onchange('partner_id')
def onchange_partner_id_warning(self):
""" desactivamos warning para portal distributor
"""
if self.env.user.has_group(
'portal_sale_distributor.group_portal_distributor'):
return {}
else:
return super().onchange_partner_id_warning()
|
Sort remove unecessary parametar default value | const sorter = function(direction, sortBy, thenBy, depth, a, b) {
const valA = sortBy(a);
const valB = sortBy(b);
if (valA === valB) {
if (thenBy && thenBy.length > depth) {
return sorter(direction, thenBy[depth], thenBy, depth + 1, a, b);
}
return 0;
}
if (valA == null) return 1;
if (valB == null) return -1;
if (valA < valB) return -direction;
return direction;
};
const ascSorter = sorter.bind(null, 1);
const descSorter = sorter.bind(null, -1);
const emptySortBy = (a) => a;
const sort = function(ctx, _sorter, sortBy = emptySortBy) {
if (Array.isArray(ctx)) {
return Array.isArray(sortBy)
? ctx.sort(_sorter.bind(undefined, sortBy.shift(), sortBy, 0))
: ctx.sort(_sorter.bind(undefined, sortBy, undefined, 0));
}
return ctx;
};
// Public
module.exports = function(ctx) {
return {
asc(sortBy) {
return sort(ctx, ascSorter, sortBy);
},
desc(sortBy) {
return sort(ctx, descSorter, sortBy);
}
};
};
| const sorter = function(direction, sortBy, thenBy, depth = 0, a, b) {
const valA = sortBy(a);
const valB = sortBy(b);
if (valA === valB) {
if (thenBy && thenBy.length > depth) {
return sorter(direction, thenBy[depth], thenBy, depth + 1, a, b);
}
return 0;
}
if (valA == null) return 1;
if (valB == null) return -1;
if (valA < valB) return -direction;
return direction;
};
const ascSorter = sorter.bind(null, 1);
const descSorter = sorter.bind(null, -1);
const emptySortBy = (a) => a;
const sort = function(ctx, _sorter, sortBy = emptySortBy) {
if (Array.isArray(ctx)) {
return Array.isArray(sortBy)
? ctx.sort(_sorter.bind(undefined, sortBy.shift(), sortBy, 0))
: ctx.sort(_sorter.bind(undefined, sortBy, undefined, 0));
}
return ctx;
};
// Public
module.exports = function(ctx) {
return {
asc(sortBy) {
return sort(ctx, ascSorter, sortBy);
},
desc(sortBy) {
return sort(ctx, descSorter, sortBy);
}
};
};
|
Fix typo in write aborted description | /**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* 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.kaazing.k3po.lang.internal.ast;
public final class AstWriteAbortedNode extends AstEventNode {
@Override
public <R, P> R accept(Visitor<R, P> visitor, P parameter) {
return visitor.visit(this, parameter);
}
@Override
protected int hashTo() {
return getClass().hashCode();
}
@Override
protected boolean equalTo(AstRegion that) {
return that instanceof AstWriteAbortedNode;
}
@Override
protected void describe(StringBuilder buf) {
super.describe(buf);
buf.append("write aborted\n");
}
}
| /**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* 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.kaazing.k3po.lang.internal.ast;
public final class AstWriteAbortedNode extends AstEventNode {
@Override
public <R, P> R accept(Visitor<R, P> visitor, P parameter) {
return visitor.visit(this, parameter);
}
@Override
protected int hashTo() {
return getClass().hashCode();
}
@Override
protected boolean equalTo(AstRegion that) {
return that instanceof AstWriteAbortedNode;
}
@Override
protected void describe(StringBuilder buf) {
super.describe(buf);
buf.append("read aborted\n");
}
}
|
Replace basestring to six.string_types. Now python 3.3, 3.2 pass tests.
Take django.utils.six dependency | from django.utils import six
from rq.decorators import job as _rq_job
from .queues import get_queue
def job(func_or_queue, connection=None, *args, **kwargs):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection`` argument from RQ_QUEUES.
And also, it allows simplified ``@job`` syntax to put job into
default queue.
"""
if callable(func_or_queue):
func = func_or_queue
queue = 'default'
else:
func = None
queue = func_or_queue
if isinstance(queue, six.string_types):
try:
queue = get_queue(queue)
if connection is None:
connection = queue.connection
except KeyError:
pass
decorator = _rq_job(queue, connection=connection, *args, **kwargs)
if func:
return decorator(func)
return decorator
| from rq.decorators import job as _rq_job
from .queues import get_queue
def job(func_or_queue, connection=None, *args, **kwargs):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection`` argument from RQ_QUEUES.
And also, it allows simplified ``@job`` syntax to put job into
default queue.
"""
if callable(func_or_queue):
func = func_or_queue
queue = 'default'
else:
func = None
queue = func_or_queue
if isinstance(queue, basestring):
try:
queue = get_queue(queue)
if connection is None:
connection = queue.connection
except KeyError:
pass
decorator = _rq_job(queue, connection=connection, *args, **kwargs)
if func:
return decorator(func)
return decorator
|
Adjust path for location on production drive | <?php
/**
* Sloth-PHP
* Tiny php framework, not actually as slow as it sounds.
*
* Written and copyrighted 2014+
* by Sven Marc 'cybrox' Gehring
*/
/* Allow user to switch app dir */
define("APPDIR", "app");
define("SUBDIR", "giftfox/");
/* Require needed fiels */
require_once('./core/base.class.php');
require_once('./core/router.class.php');
require_once('./core/uri.class.php');
require_once('./core/autoloader.class.php');
try {
/* Invoke base boot to get data we need */
Base::boot();
/* Register the autloader and load our files */
Autoloader::register();
Autoloader::load_app();
Autoloader::load_dbs();
/* Create function alias for simple templating */
function __($name){ echo Registry::get($name); }
/* Actually render page or catch errors */
Router::route_process($_SERVER);
} catch(Exception $e) {
if(get_class($e) == "LazySloth") Error::shutdown($e);
else Error::shutdown(new LazySloth($e));
}
?> | <?php
/**
* Sloth-PHP
* Tiny php framework, not actually as slow as it sounds.
*
* Written and copyrighted 2014+
* by Sven Marc 'cybrox' Gehring
*/
/* Allow user to switch app dir */
define("APPDIR", "app");
define("SUBDIR", "/git/giftfox/");
/* Require needed fiels */
require_once('./core/base.class.php');
require_once('./core/router.class.php');
require_once('./core/uri.class.php');
require_once('./core/autoloader.class.php');
try {
/* Invoke base boot to get data we need */
Base::boot();
/* Register the autloader and load our files */
Autoloader::register();
Autoloader::load_app();
Autoloader::load_dbs();
/* Create function alias for simple templating */
function __($name){ echo Registry::get($name); }
/* Actually render page or catch errors */
Router::route_process($_SERVER);
} catch(Exception $e) {
if(get_class($e) == "LazySloth") Error::shutdown($e);
else Error::shutdown(new LazySloth($e));
}
?> |
Trim argument for sort command | package seedu.doit.logic.parser;
import static seedu.doit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import seedu.doit.logic.commands.Command;
import seedu.doit.logic.commands.IncorrectCommand;
import seedu.doit.logic.commands.SortCommand;
/**
* Parses input arguments and creates a new SortCommand object
*/
public class SortCommandParser {
public static final String SORT_VALIDATION_REGEX = "(priority)|(deadline)|(start time)";
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns an FindCommand object for execution.
*/
public Command parse(String args) {
if (args.trim().matches(SORT_VALIDATION_REGEX)) {
return new SortCommand(args.trim());
} else {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE));
}
}
}
| package seedu.doit.logic.parser;
import static seedu.doit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import seedu.doit.logic.commands.Command;
import seedu.doit.logic.commands.IncorrectCommand;
import seedu.doit.logic.commands.SortCommand;
/**
* Parses input arguments and creates a new SortCommand object
*/
public class SortCommandParser {
public static final String SORT_VALIDATION_REGEX = "(priority)|(deadline)|(start time)";
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns an FindCommand object for execution.
*/
public Command parse(String args) {
if (args.matches(SORT_VALIDATION_REGEX)) {
return new SortCommand(args);
} else {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE));
}
}
}
|
Remove fixed range from loop. | package main
import (
"log"
"net"
)
const PORT = "2525"
func main() {
server := createServer(PORT)
defer server.Close()
for {
conn, err := server.Accept()
if err != nil {
log.Fatalf("Error accepting: %v\n", err)
}
go handleConnection(conn)
}
}
func createServer(port string) (net.Listener) {
server, err := net.Listen("tcp", ":" + PORT)
if err != nil {
log.Fatalf("Error listening to port %s\n", PORT)
}
return server
}
func handleConnection(conn net.Conn) {
defer conn.Close()
conn.Write([]byte("220 OK\n"))
for {
buffer := make([]byte, 1024)
n, _ := conn.Read(buffer)
if string(buffer[:n]) == "DATA\r\n" {
break
}
conn.Write([]byte("250 OK\n"))
}
}
| package main
import (
"log"
"net"
)
const PORT = "2525"
func main() {
server := createServer(PORT)
defer server.Close()
for {
conn, err := server.Accept()
if err != nil {
log.Fatalf("Error accepting: %v\n", err)
}
go handleConnection(conn)
}
}
func createServer(port string) (net.Listener) {
server, err := net.Listen("tcp", ":" + PORT)
if err != nil {
log.Fatalf("Error listening to port %s\n", PORT)
}
return server
}
func handleConnection(conn net.Conn) {
defer conn.Close()
conn.Write([]byte("220 OK\n"))
for i := 1; i <= 5; i++ {
buffer := make([]byte, 1024)
n, _ := conn.Read(buffer)
if string(buffer[:n]) == "DATA\r\n" {
break
}
conn.Write([]byte("250 OK\n"))
}
}
|
Fix bug in javscript, when clearing the repo_name. | $('form#submit-repo').submit(
function(evt){
evt.preventDefault();
var status = $('#status');
var repo = $('label[for="repo_name"]').text() + $('input[name="repo_name"]').val();
var text = 'Processing to create ' + repo + ' ...';
$('#status').children().remove();
var processing = $('<span id="processing">').text(text)
status.append(processing);
var xhr = $.post(
'/manage',
$(this).serialize(),
function(data, status_code, jqxhr) {
$('#status').children().remove()
status.append($('<p>').text(data.message));
}
);
$('input[name="repo_name"]').val('');
}
);
| $('form#submit-repo').submit(
function(evt){
evt.preventDefault();
var status = $('#status');
var repo = $('label[for="repo_name"]').text() + $('input[name="repo_name"]').val();
var text = 'Processing to create ' + repo + ' ...';
$('#status').children().remove();
$('input[name="repo_name"]').val('');
var processing = $('<span id="processing">').text(text)
status.append(processing);
var xhr = $.post(
'/manage',
$(this).serialize(),
function(data, status_code, jqxhr) {
$('#status').children().remove()
status.append($('<p>').text(data.message));
}
)
}
);
|
Change /hello to respond to POST requests | package com.twilio.starter;
import com.twilio.Twilio;
import com.twilio.starter.controller.CallController;
import com.twilio.starter.controller.MessageController;
import com.twilio.starter.controller.TwimlController;
import static spark.Spark.*;
public class Application {
private static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
private static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
staticFileLocation("/public");
post("/call", CallController.handlePost);
post("/message", MessageController.handlePost);
post("/hello", TwimlController.handleGet);
}
}
| package com.twilio.starter;
import com.twilio.Twilio;
import com.twilio.starter.controller.CallController;
import com.twilio.starter.controller.MessageController;
import com.twilio.starter.controller.TwimlController;
import static spark.Spark.*;
public class Application {
private static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
private static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
staticFileLocation("/public");
post("/call", CallController.handlePost);
post("/message", MessageController.handlePost);
get("/hello", TwimlController.handleGet);
}
}
|
Improve formatting of API error details | <?php
namespace Platformsh\Cli\Exception;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
use Platformsh\Client\Exception\ApiResponseException;
class HttpException extends \RuntimeException
{
protected $message = 'An API error occurred.';
/**
* @param string $message
* @param RequestInterface $request
* @param ResponseInterface $response
*/
public function __construct($message = null, RequestInterface $request = null, ResponseInterface $response = null)
{
$message = $message ?: $this->message;
if ($request !== null && $response !== null) {
$details = "[url] " . $request->getUrl();
$details .= " [status code] " . $response->getStatusCode();
$details .= " [reason phrase] " . $response->getReasonPhrase();
$details .= ApiResponseException::getErrorDetails($response);
$message .= "\n\nDetails:\n" . $details;
}
parent::__construct($message, $this->code);
}
}
| <?php
namespace Platformsh\Cli\Exception;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
use Platformsh\Client\Exception\ApiResponseException;
class HttpException extends \RuntimeException
{
protected $message = 'An API error occurred.';
/**
* @param string $message
* @param RequestInterface $request
* @param ResponseInterface $response
*/
public function __construct($message = null, RequestInterface $request = null, ResponseInterface $response = null)
{
$message = $message ?: $this->message;
if ($request !== null && $response !== null) {
$details = "[url] " . $request->getUrl();
$details .= " [status code] " . $response->getStatusCode();
$details .= " [reason phrase] " . $response->getReasonPhrase();
$details .= ApiResponseException::getErrorDetails($response);
$message .= "\nDetails:\n " . wordwrap($details);
}
parent::__construct($message, $this->code);
}
}
|
Set required_sortable to True for logical operations | from cupy import core
logical_and = core.create_comparison(
'logical_and', '&&',
'''Computes the logical AND of two arrays.
.. seealso:: :data:`numpy.logical_and`
''',
require_sortable_dtype=True)
logical_or = core.create_comparison(
'logical_or', '||',
'''Computes the logical OR of two arrays.
.. seealso:: :data:`numpy.logical_or`
''',
require_sortable_dtype=True)
logical_not = core.create_ufunc(
'cupy_logical_not',
('?->?', 'b->?', 'B->?', 'h->?', 'H->?', 'i->?', 'I->?', 'l->?', 'L->?',
'q->?', 'Q->?', 'e->?', 'f->?', 'd->?'),
'out0 = !in0',
doc='''Computes the logical NOT of an array.
.. seealso:: :data:`numpy.logical_not`
''')
logical_xor = core.create_ufunc(
'cupy_logical_xor',
('??->?', 'bb->?', 'BB->?', 'hh->?', 'HH->?', 'ii->?', 'II->?', 'll->?',
'LL->?', 'qq->?', 'QQ->?', 'ee->?', 'ff->?', 'dd->?'),
'out0 = !in0 != !in1',
doc='''Computes the logical XOR of two arrays.
.. seealso:: :data:`numpy.logical_xor`
''')
| from cupy import core
logical_and = core.create_comparison(
'logical_and', '&&',
'''Computes the logical AND of two arrays.
.. seealso:: :data:`numpy.logical_and`
''',
require_sortable_dtype=False)
logical_or = core.create_comparison(
'logical_or', '||',
'''Computes the logical OR of two arrays.
.. seealso:: :data:`numpy.logical_or`
''',
require_sortable_dtype=False)
logical_not = core.create_ufunc(
'cupy_logical_not',
('?->?', 'b->?', 'B->?', 'h->?', 'H->?', 'i->?', 'I->?', 'l->?', 'L->?',
'q->?', 'Q->?', 'e->?', 'f->?', 'd->?'),
'out0 = !in0',
doc='''Computes the logical NOT of an array.
.. seealso:: :data:`numpy.logical_not`
''')
logical_xor = core.create_ufunc(
'cupy_logical_xor',
('??->?', 'bb->?', 'BB->?', 'hh->?', 'HH->?', 'ii->?', 'II->?', 'll->?',
'LL->?', 'qq->?', 'QQ->?', 'ee->?', 'ff->?', 'dd->?'),
'out0 = !in0 != !in1',
doc='''Computes the logical XOR of two arrays.
.. seealso:: :data:`numpy.logical_xor`
''')
|
Add comment justifying the use of UNSAFE. | package org.jctools.util;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import sun.misc.Unsafe;
/**
* Why should we resort to using Unsafe?<br>
* <ol>
* <li>To construct class fields which allow volatile/ordered/plain access: This requirement is covered by
* {@link AtomicReferenceFieldUpdater} and similar but their performance is arguably worse than the DIY approach
* (depending on JVM version) while Unsafe intrinsification is a far lesser challenge for JIT compilers.
* <li>To construct flavors of {@link AtomicReferenceArray}.
* <li>Other use cases exist but are not present in this library yet.
* <ol>
*
* @author nitsanw
*
*/
public class UnsafeAccess {
public static final Unsafe UNSAFE;
static {
try {
/*
* This is a bit of voodoo to force the unsafe object into visibility and acquire it. This is not playing
* nice, but as an established back door it is not likely to be taken away.
*/
final Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
UNSAFE = (Unsafe) field.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| package org.jctools.util;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeAccess {
public static final Unsafe UNSAFE;
static {
try {
// This is a bit of voodoo to force the unsafe object into
// visibility and acquire it.
// This is not playing nice, but as an established back door it is
// not likely to be
// taken away.
final Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
UNSAFE = (Unsafe) field.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
Use constructor injection for Jersey sample | /*
* Copyright 2012-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 sample.jersey;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Path("/hello")
public class Endpoint {
private Service service;
@Autowired
public Endpoint(Service service) {
this.service = service;
}
@GET
public String message() {
return "Hello " + this.service.message();
}
}
| /*
* Copyright 2012-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 sample.jersey;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Path("/hello")
public class Endpoint {
@Autowired
private Service service;
@GET
public String message() {
return "Hello " + this.service.message();
}
}
|
Change estimator script based on modifications to estimator | #!/usr/bin/env python2
import numpy as np
import matplotlib.pyplot as plt
import argparse
import sys
import os
parser = argparse.ArgumentParser(
prog='plot_tracking_vector_estimator')
parser.add_argument('directory', type=str, help='Data directory')
args = parser.parse_args()
data = np.genfromtxt(
os.path.join(
args.directory,
'tracking_vector_estimator'),
delimiter=',', names=True)
state_labels = ['Marker_x', 'Marker_y', 'Marker_z']
noise_labels = ['Noise_x', 'Noise_y', 'Noise_z']
meas_labels = ['Measured_Marker_x', 'Measured_Marker_y', 'Measured_Marker_y']
meas_noise_labels = ['Meas_noise_x', 'Meas_noise_y', 'Meas_noise_z']
ts = (data['Time'] - data['Time'][0]) / 1e9
plt.figure(1)
for i in range(3):
plt.subplot(2, 3, i+1)
plt.errorbar(ts, data[meas_labels[i]], yerr=data[meas_noise_labels[i]])
plt.errorbar(ts, data[state_labels[i]], yerr=data[noise_labels[i]])
plt.ylabel(state_labels[i])
plt.xlabel('Time (seconds)')
plt.legend([meas_labels[i], state_labels[i]])
plt.show()
| #!/usr/bin/env python2
import numpy as np
import matplotlib.pyplot as plt
import argparse
import sys
import os
parser = argparse.ArgumentParser(
prog='plot_tracking_vector_estimator')
parser.add_argument('directory', type=str, help='Data directory')
args = parser.parse_args()
data = np.genfromtxt(
os.path.join(
args.directory,
'tracking_vector_estimator'),
delimiter=',', names=True)
state_labels = ['Marker_x', 'Marker_y', 'Marker_z', 'Velocity_x', 'Velocity_y', 'Velocity_z']
noise_labels = ['Noise_x', 'Noise_y', 'Noise_z', 'Noise_vx', 'Noise_vy', 'Noise_vz']
meas_labels = ['Measured_Marker_x', 'Measured_Marker_y', 'Measured_Marker_y', 'Measured_Velocity_x', 'Measured_Velocity_y', 'Measured_Velocity_z']
ts = (data['Time'] - data['Time'][0]) / 1e9
plt.figure(1)
for i in range(6):
plt.subplot(2, 3, i+1)
plt.plot(ts, data[meas_labels[i]])
plt.errorbar(ts, data[state_labels[i]], yerr=data[noise_labels[i]])
plt.ylabel(state_labels[i])
plt.xlabel('Time (seconds)')
plt.legend([meas_labels[i], state_labels[i]])
plt.show()
|
Fix tests not passing for Django 2.X | import dj_database_url
DEBUG = True
TEMPLATE_DEBUG = True
SECRET_KEY = 'this is my secret key' # NOQA
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
DATABASES = {
'default': dj_database_url.config(default='postgres:///localized_fields')
}
DATABASES['default']['ENGINE'] = 'psqlextra.backend'
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', 'English'),
('ro', 'Romanian'),
('nl', 'Dutch')
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.admin',
'localized_fields',
'tests',
)
# set to a lower number than the default, since
# we want the tests to be fast, default is 100
LOCALIZED_FIELDS_MAX_RETRIES = 3
LOCALIZED_FIELDS_EXPERIMENTAL = False
| import dj_database_url
DEBUG = True
TEMPLATE_DEBUG = True
SECRET_KEY = 'this is my secret key' # NOQA
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
DATABASES = {
'default': dj_database_url.config(default='postgres:///localized_fields')
}
DATABASES['default']['ENGINE'] = 'psqlextra.backend'
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', 'English'),
('ro', 'Romanian'),
('nl', 'Dutch')
)
INSTALLED_APPS = (
'localized_fields',
'tests',
)
# set to a lower number than the default, since
# we want the tests to be fast, default is 100
LOCALIZED_FIELDS_MAX_RETRIES = 3
LOCALIZED_FIELDS_EXPERIMENTAL = False
|
Set default ordering for user and group API endpoints | from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups').order_by('username')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user')).order_by('name')
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
| from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user'))
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
|
Use triggerHandler() instead of trigger() | /**
* Events.
*
* @mixin
* @namespace Bolt.events
*
* @param {Object} bolt - The Bolt module.
*/
(function (bolt) {
'use strict';
/*
* Bolt.events mixin container.
*
* @private
* @type {Object}
*/
var events = {};
/*
* Event broker object.
*
* @private
* @type {Object}
*/
var broker = $({});
/**
* Fires an event.
*
* @static
* @function fire
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {object} [parameter] - Additional parameters to pass along to the event handler
*/
events.fire = function (event, parameter) {
broker.triggerHandler(event, parameter);
};
/**
* Attach an event handler.
*
* @static
* @function on
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {function} handler - Event handler
*/
events.on = function (event, handler) {
broker.on(event, handler);
};
// Apply mixin container
bolt.events = events;
})(Bolt || {});
| /**
* Events.
*
* @mixin
* @namespace Bolt.events
*
* @param {Object} bolt - The Bolt module.
*/
(function (bolt) {
'use strict';
/*
* Bolt.events mixin container.
*
* @private
* @type {Object}
*/
var events = {};
/*
* Event broker object.
*
* @private
* @type {Object}
*/
var broker = $({});
/**
* Fires an event.
*
* @static
* @function fire
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {object} [parameter] - Additional parameters to pass along to the event handler
*/
events.fire = function (event, parameter) {
broker.trigger(event, parameter);
};
/**
* Attach an event handler.
*
* @static
* @function on
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {function} handler - Event handler
*/
events.on = function (event, handler) {
broker.on(event, handler);
};
// Apply mixin container
bolt.events = events;
})(Bolt || {});
|
Add prop inverse for spinner | const React = require('react');
const classNames = require('classnames');
const SIZES = require('./SIZES');
const Spinner = React.createClass({
propTypes: {
centered: React.PropTypes.bool,
inverse: React.PropTypes.bool,
size: React.PropTypes.oneOf(SIZES)
},
getDefaultProps: function() {
return {
centered: true,
size: 'md'
};
},
render: function() {
let className = classNames('gb-spinner', 'spinner-' + this.props.size, {
'spinner-inverse': this.props.inverse,
'spinner-centered': this.props.centered
});
return <div className={className}></div>;
}
});
/**
* Block div representing a loading area
*/
const SpinnerSlate = React.createClass({
render: function() {
return <div className="gb-spinner-slate">
<Spinner {...this.props} />
</div>;
}
});
module.exports = Spinner;
module.exports.Slate = SpinnerSlate;
| const React = require('react');
const classNames = require('classnames');
const SIZES = require('./SIZES');
const Spinner = React.createClass({
propTypes: {
centered: React.PropTypes.bool,
size: React.PropTypes.oneOf(SIZES)
},
getDefaultProps: function() {
return {
centered: true,
size: 'md'
};
},
render: function() {
let className = classNames('gb-spinner', 'spinner-' + this.props.size, {
'spinner-inverse': this.props.inverse,
'spinner-centered': this.props.centered
});
return <div className={className}></div>;
}
});
/**
* Block div representing a loading area
*/
const SpinnerSlate = React.createClass({
render: function() {
return <div className="gb-spinner-slate">
<Spinner {...this.props} />
</div>;
}
});
module.exports = Spinner;
module.exports.Slate = SpinnerSlate;
|
Reformat code post prettier update :memo: | const createFixer =
({range, left, right, operator}, source) =>
fixer => {
const [leftStart, leftEnd] = left.range;
const [rightStart] = right.range;
const operatorRange = [leftEnd, rightStart];
const operatorText = source.slice(...operatorRange);
if (operator === '||') {
const leftText = source.slice(leftStart, leftEnd);
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`))
];
}
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')),
fixer.insertTextAfterRange(range, ' : null')
];
};
const create = context => ({
LogicalExpression: node => {
if (node.right.type === 'JSXElement') {
context.report({
node,
message: 'JSX should not use logical expression',
fix: createFixer(node, context.getSourceCode().getText())
});
}
}
});
module.exports = {
create,
createFixer,
meta: {
docs: {
description: 'Prevent falsy values to be printed'
},
fixable: 'code'
}
};
| const createFixer = ({range, left, right, operator}, source) => fixer => {
const [leftStart, leftEnd] = left.range;
const [rightStart] = right.range;
const operatorRange = [leftEnd, rightStart];
const operatorText = source.slice(...operatorRange);
if (operator === '||') {
const leftText = source.slice(leftStart, leftEnd);
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`))
];
}
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')),
fixer.insertTextAfterRange(range, ' : null')
];
};
const create = context => ({
LogicalExpression: node => {
if (node.right.type === 'JSXElement') {
context.report({
node,
message: 'JSX should not use logical expression',
fix: createFixer(node, context.getSourceCode().getText())
});
}
}
});
module.exports = {
create,
createFixer,
meta: {
docs: {
description: 'Prevent falsy values to be printed'
},
fixable: 'code'
}
};
|
Add test for 27250 Heading | var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));
chai.use(require('signalk-schema').chaiModule);
describe('127250 Heading', function () {
it('Magnetic sentence converts', function () {
var tree = require("../n2kMapper.js").toNested(
JSON.parse('{"timestamp":"2013-10-08-15:47:28.263","prio":"2","src":"204","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"Heading":"129.7","Reference":"Magnetic"}}'));
tree.should.have.with.deep.property('navigation.headingMagnetic.value', 129.7);
tree.should.be.validSignalK;
});
it('Variation sentence converts', function () {
var tree = require("../n2kMapper.js").toNested(
JSON.parse('{"timestamp":"2013-10-08-15:47:28.264","prio":"2","src":"1","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"SID":"68","Variation":"8.0","Reference":"True"}}'));
tree.should.have.with.deep.property('navigation.magneticVariation.value', 8);
tree.should.be.validSignalK;
});
});
| var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));
describe('127250 Heading', function () {
it('Magnetic sentence converts', function () {
var tree = require("../n2kMapper.js").toNested(
JSON.parse('{"timestamp":"2013-10-08-15:47:28.263","prio":"2","src":"204","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"Heading":"129.7","Reference":"Magnetic"}}'));
tree.should.have.with.deep.property('navigation.headingMagnetic.value', 129.7);
});
it('Variation sentence converts', function () {
var tree = require("../n2kMapper.js").toNested(
JSON.parse('{"timestamp":"2013-10-08-15:47:28.264","prio":"2","src":"1","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"SID":"68","Variation":"8.0","Reference":"True"}}'));
tree.should.have.with.deep.property('navigation.magneticVariation.value', 8);
});
});
|
Fix functions into Session class | <?php
/*
----------------------------------------------------------------------
FusionInventory
Copyright (C) 2010-2011 by the FusionInventory Development Team.
http://www.fusioninventory.org/ http://forge.fusioninventory.org/
----------------------------------------------------------------------
LICENSE
This file is part of FusionInventory.
FusionInventory is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
FusionInventory is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
Original Author of file: David DURIEUX
Co-authors of file:
Purpose of file:
----------------------------------------------------------------------
*/
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT . "/inc/includes.php");
header("Content-Type: text/html; charset=UTF-8");
header_nocache();
Session::checkRight('rule_ocs', 'r');
$rule = new PluginFusinvinventoryRuleEntity();
include (GLPI_ROOT."/ajax/rule.common.tabs.php");
?> | <?php
/*
----------------------------------------------------------------------
FusionInventory
Copyright (C) 2010-2011 by the FusionInventory Development Team.
http://www.fusioninventory.org/ http://forge.fusioninventory.org/
----------------------------------------------------------------------
LICENSE
This file is part of FusionInventory.
FusionInventory is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
FusionInventory is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
Original Author of file: David DURIEUX
Co-authors of file:
Purpose of file:
----------------------------------------------------------------------
*/
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT . "/inc/includes.php");
header("Content-Type: text/html; charset=UTF-8");
header_nocache();
checkRight('rule_ocs', 'r');
$rule = new PluginFusinvinventoryRuleEntity();
include (GLPI_ROOT."/ajax/rule.common.tabs.php");
?> |
Fix minor typo: possessive "its" | /*
* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime;
import org.antlr.v4.runtime.misc.Pair;
/** The default mechanism for creating tokens. It's used by default in Lexer and
* the error handling strategy (to create missing tokens). Notifying the parser
* of a new factory means that it notifies its token source and error strategy.
*/
public interface TokenFactory<Symbol extends Token> {
/** This is the method used to create tokens in the lexer and in the
* error handling strategy. If text!=null, than the start and stop positions
* are wiped to -1 in the text override is set in the CommonToken.
*/
Symbol create(Pair<TokenSource, CharStream> source, int type, String text,
int channel, int start, int stop,
int line, int charPositionInLine);
/** Generically useful */
Symbol create(int type, String text);
}
| /*
* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime;
import org.antlr.v4.runtime.misc.Pair;
/** The default mechanism for creating tokens. It's used by default in Lexer and
* the error handling strategy (to create missing tokens). Notifying the parser
* of a new factory means that it notifies it's token source and error strategy.
*/
public interface TokenFactory<Symbol extends Token> {
/** This is the method used to create tokens in the lexer and in the
* error handling strategy. If text!=null, than the start and stop positions
* are wiped to -1 in the text override is set in the CommonToken.
*/
Symbol create(Pair<TokenSource, CharStream> source, int type, String text,
int channel, int start, int stop,
int line, int charPositionInLine);
/** Generically useful */
Symbol create(int type, String text);
}
|
Enable DBMS pool pre-pinging to avoid connection errors | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after database becomes temporarily
# unreachable, then becomes reachable again.
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
| """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
|
Fix 'calling set on destroyed object' error | import Ember from 'ember';
import layout from '../templates/components/freestyle-collection';
const { computed, inject } = Ember;
export default Ember.Component.extend({
layout,
classNames: ['FreestyleCollection'],
classNameBindings: ['inline:FreestyleCollection--inline'],
emberFreestyle: inject.service(),
showLabels: computed.and('emberFreestyle.notFocused', 'emberFreestyle.showLabels'),
hasLabels: computed.and('showLabels', 'title'),
showVariantList: computed.not('emberFreestyle.focus'),
defaultKey: 'all',
activeKey: computed('defaultKey', 'key', 'emberFreestyle.focus', function() {
if (this.get('emberFreestyle.focus')) {
return 'all';
}
return this.get('key') || this.get('defaultKey');
}),
registerVariant(variantKey) {
Ember.run.next(() => {
if (this.isDestroyed) { return; }
let variants = this.get('variants') || Ember.A(['all']);
if (!variants.includes(variantKey)) {
variants.pushObject(variantKey);
}
this.set('variants', variants);
});
},
actions: {
setKey(key) {
this.set('key', key);
}
}
});
| import Ember from 'ember';
import layout from '../templates/components/freestyle-collection';
const { computed, inject } = Ember;
export default Ember.Component.extend({
layout,
classNames: ['FreestyleCollection'],
classNameBindings: ['inline:FreestyleCollection--inline'],
emberFreestyle: inject.service(),
showLabels: computed.and('emberFreestyle.notFocused', 'emberFreestyle.showLabels'),
hasLabels: computed.and('showLabels', 'title'),
showVariantList: computed.not('emberFreestyle.focus'),
defaultKey: 'all',
activeKey: computed('defaultKey', 'key', 'emberFreestyle.focus', function() {
if (this.get('emberFreestyle.focus')) {
return 'all';
}
return this.get('key') || this.get('defaultKey');
}),
registerVariant(variantKey) {
Ember.run.next(() => {
let variants = this.get('variants') || Ember.A(['all']);
if (!variants.includes(variantKey)) {
variants.pushObject(variantKey);
}
this.set('variants', variants);
});
},
actions: {
setKey(key) {
this.set('key', key);
}
}
});
|
Raise an exception when DtraceTestCase (and subclasses) is used on non-darwin machines | #!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This file is part of my GSoC'15 project for Cuckoo Sandbox:
# http://www.cuckoosandbox.org
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
import os
import unittest
import platform
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
if platform.system() != "Darwin":
raise Exception("%s: This test suite must be run on OS X" % cls.__name__)
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target)
| #!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This file is part of my GSoC'15 project for Cuckoo Sandbox:
# http://www.cuckoosandbox.org
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
import os
import unittest
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target)
|
Add etl002 FQDN to Celos Oozie default properties. | var CELOS_USER = "celos";
var CELOS_DEFAULT_OOZIE = "http://oozie002.ny7.collective-media.net:11000/oozie";
var CELOS_DEFAULT_HDFS = "hdfs://nameservice1";
var NAME_NODE = CELOS_DEFAULT_HDFS;
var JOB_TRACKER = "admin1.ny7.collective-media.net:8032";
var HIVE_METASTORE = "thrift://hive002.ny7.collective-media.net:9083";
var ETL002 = "etl002.ny7.collective-media.net";
var OUTPUT_ROOT = NAME_NODE + "/output";
var CELOS_DEFAULT_OOZIE_PROPERTIES = {
"user.name": CELOS_USER,
"jobTracker" : JOB_TRACKER,
"nameNode" : CELOS_DEFAULT_HDFS,
"hiveMetastore": HIVE_METASTORE,
"hiveDefaults": NAME_NODE + "/deploy/TheOneWorkflow/hive/hive-site.xml",
"oozie.use.system.libpath": "true",
"outputRoot": OUTPUT_ROOT,
"etl002": ETL002
};
| var CELOS_USER = "celos";
var CELOS_DEFAULT_OOZIE = "http://oozie002.ny7.collective-media.net:11000/oozie";
var CELOS_DEFAULT_HDFS = "hdfs://nameservice1";
var NAME_NODE = CELOS_DEFAULT_HDFS;
var JOB_TRACKER = "admin1.ny7.collective-media.net:8032";
var HIVE_METASTORE = "thrift://hive002.ny7.collective-media.net:9083";
var OUTPUT_ROOT = NAME_NODE + "/output";
var CELOS_DEFAULT_OOZIE_PROPERTIES = {
"user.name": CELOS_USER,
"jobTracker" : JOB_TRACKER,
"nameNode" : CELOS_DEFAULT_HDFS,
"hiveMetastore": HIVE_METASTORE,
"hiveDefaults": NAME_NODE + "/deploy/TheOneWorkflow/hive/hive-site.xml",
"oozie.use.system.libpath": "true",
"outputRoot": OUTPUT_ROOT
};
|
Add support for RN 0.55 | package ca.jaysoo.extradimensions;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class ExtraDimensionsPackage implements ReactPackage {
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.asList();
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ExtraDimensionsModule(reactContext));
return modules;
}
}
| package ca.jaysoo.extradimensions;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class ExtraDimensionsPackage implements ReactPackage {
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.asList();
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ExtraDimensionsModule(reactContext));
return modules;
}
}
|
Fix bug when following an user | <?php
trait Trait_currentMember
{
protected $_current_member = null;
protected function _checkCurrentMember()
{
if(isset($_SESSION['connected_user_id']))
{
$this->_current_member = Model_Users::getById($_SESSION['connected_user_id']);
$this->_current_member->prop('last_login', date('Y-m-d H:i:s'));
$this->_current_member->load('user_group');
$this->_current_member->load('locale_website');
$this->_current_member->load('locales_comics');
$this->_current_member->load('follows');
Model_Users::update($this->_current_member);
if($this->_current_member->prop('is_banned'))
$this->_current_member = new Model_Users();
}
else
$this->_current_member = new Model_Users();
Library_i18n::defineLocale($this->_current_member);
\Eliya\Tpl::set(['current_member' => $this->_current_member]);
if(!isset($_SESSION['token_logout']))
$_SESSION['token_logout'] = uniqid(rand(), true); //Protection contre les failles CSRF
}
protected function _redirectToCurrentMemberProfile()
{
$this->response->redirect($this->request->getBaseUrl().'profile/'.$this->_current_member->getId());
exit;
}
} | <?php
trait Trait_currentMember
{
protected $_current_member = null;
protected function _checkCurrentMember()
{
if(isset($_SESSION['connected_user_id']))
{
$this->_current_member = Model_Users::getById($_SESSION['connected_user_id']);
$this->_current_member->prop('last_login', date('Y-m-d H:i:s'));
Model_Users::update($this->_current_member);
if($this->_current_member->prop('is_banned'))
$this->_current_member = new Model_Users();
}
else
$this->_current_member = new Model_Users();
Library_i18n::defineLocale($this->_current_member);
\Eliya\Tpl::set(['current_member' => $this->_current_member]);
if(!isset($_SESSION['token_logout']))
$_SESSION['token_logout'] = uniqid(rand(), true); //Protection contre les failles CSRF
}
protected function _redirectToCurrentMemberProfile()
{
$this->response->redirect($this->request->getBaseUrl().'profile/'.$this->_current_member->getId());
exit;
}
} |
Fix URLLIb3 Insecure Platform Warning | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from sys import exit as sys_exit
import requests
from click import echo, group, version_option
from platformio_api import __version__
from platformio_api.crawler import (process_pending_libs, rotate_libs_dlstats,
sync_libs)
from platformio_api.database import sync_db
from platformio_api.web import app
@group()
@version_option(__version__, prog_name="PlatformIO-API")
def cli():
pass
@cli.command()
def syncdb():
sync_db()
echo("The database has been successfully synchronized!")
@cli.command()
def pendinglibs():
process_pending_libs()
@cli.command()
def synclibs():
sync_libs()
@cli.command()
def rotatelibsdlstats():
rotate_libs_dlstats()
@cli.command("run")
def runserver():
app.run(debug=True, reloader=True)
def main():
# https://urllib3.readthedocs.org
# /en/latest/security.html#insecureplatformwarning
requests.packages.urllib3.disable_warnings()
cli()
if __name__ == "__main__":
sys_exit(main())
| # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from sys import exit as sys_exit
from click import echo, group, version_option
from platformio_api import __version__
from platformio_api.crawler import (process_pending_libs, rotate_libs_dlstats,
sync_libs)
from platformio_api.database import sync_db
from platformio_api.web import app
@group()
@version_option(__version__, prog_name="PlatformIO-API")
def cli():
pass
@cli.command()
def syncdb():
sync_db()
echo("The database has been successfully synchronized!")
@cli.command()
def pendinglibs():
process_pending_libs()
@cli.command()
def synclibs():
sync_libs()
@cli.command()
def rotatelibsdlstats():
rotate_libs_dlstats()
@cli.command("run")
def runserver():
app.run(debug=True, reloader=True)
def main():
cli()
if __name__ == "__main__":
sys_exit(main())
|
Remove commented test code from sign up saga | import { take, takeEvery, call, put } from 'redux-saga/effects';
import * as actions from '../actions/auth';
import { authActions } from '../actions/action-types.js';
import * as auth from '../fetch/auth';
import { browserHistory } from 'react-router';
function* signUp(action) {
const { name, email, password } = action;
let response = yield call(auth.signUp, name, email, password);
switch (response.status) {
case 200:
yield put(actions.signUpSuccess());
break;
case 409:
yield put(actions.signUpFail("Email is already in use"));
break;
default:
yield put(actions.signUpFail("Sign up failed"));
}
}
export function* watchSignUpRequest() {
yield takeEvery(authActions.AUTH_SIGNUP_REQUEST, signUp);
}
| import { take, takeEvery, call, put } from 'redux-saga/effects';
import * as actions from '../actions/auth';
import * as auth from '../fetch/auth';
import { browserHistory } from 'react-router';
function* signUp(action) {
const { name, email, password } = action;
let response = yield call(auth.signUp, name, email, password);
switch (response.status) {
case 200:
yield put(actions.signUpSuccess());
break;
case 409:
yield put(actions.signUpFail("Email is already in use"));
break;
default:
yield put(actions.signUpFail("Sign up failed"));
}
//response.json().then(data => console.log(data));
}
export function* watchSignUpRequest() {
yield takeEvery('AUTH_SIGNUP_REQUEST', signUp);
}
|
Add speech on minute change. | var Clock = (function() {
var display = document.getElementById('timedisplay'),
hourDisplay = document.getElementById('hour'),
minuteDisplay = document.getElementById('minute'),
secondDisplay = document.getElementById('second'),
initTime = new Date(),
initHour = initTime.getHours(),
initMinute = initTime.getMinutes();
var checkMinute = function(min) {
if (initMinute < min) {
console.log('hello new minute', min);
responsiveVoice.speak('The time is now ' + initHour + ':' + min);
initMinute = min;
}
};
var timer = setInterval(function() {
var time = new Date(),
s = time.getSeconds(),
m = time.getMinutes(),
h = time.getHours();
hourDisplay.innerHTML = h;
minuteDisplay.innerHTML = m;
secondDisplay.innerHTML = s;
checkMinute(m);
}, 500);
})(); | var Clock = (function() {
var display = document.getElementById('timedisplay'),
hourdisplay = document.getElementById('hour'),
minutedisplay = document.getElementById('minute'),
seconddisplay = document.getElementById('second');
var timer = setInterval(function() {
var time = new Date(),
s = time.getSeconds(),
m = time.getMinutes(),
h = time.getHours();
hourdisplay.innerHTML = h;
minutedisplay.innerHTML = m;
seconddisplay.innerHTML = s;
}, 500);
setTimeout(function() {
responsiveVoice.speak("Hello World");
}, 2000);
})(); |
Fix script, hope working now | document.getElementById("ayuda").setAttribute("aria-current", "page");
var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "addonsButton");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);
addons = [
"clipContentsDesigner",
"emoticons",
"eMule",
"placeMarkers",
"readFeeds",
"reportSymbols",
]
var addonsLength = addons.length;
$(document).ready(function () {
$("#addonsButton").click(function () {
for (var i = 0; i < addonsLength; i++) {
details = document.createElement("DETAILS");
var summary = document.createElement("SUMMARY");
var t = document.createTextNode(addons[i]);
summary.appendChild(t);
details.appendChild(summary);
$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
var name = json.name;
var p = document.createElement("P");
var t = document.createTextNode(name);
p.appendChild(t);
details.appendChild(p);
});
aside.appendChild(details);
}
});
});
| document.getElementById("ayuda").setAttribute("aria-current", "page");
var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "addonsButton");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);
addons = [
"clipContentsDesigner",
"emoticons",
"eMule",
"placeMarkers",
"readFeeds",
"reportSymbols",
]
var addonsLength = addons.length;
$(document).ready(function () {
$("#addonsButton").click(function () {
for (var i = 0; i < addonsLength; i++) {
var details = document.createElement("DETAILS");
var summary = document.createElement("SUMMARY");
var t = document.createTextNode(addons[i]);
summary.appendChild(t);
details.appendChild(summary);
$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
name = json.name;
});
var p = document.createElement("P");
var t = document.createTextNode(name);
p.appendChild(t);
details.appendChild(p);
aside.appendChild(details);
}
});
});
|
Switch to main method in examples | #!/usr/bin/env python
'''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
def main():
# construct the query variables (the explict names are optional)
obama, relation, value = BNode("Obama"), BNode("relation"), BNode("value")
# construct the query itself, selecting the relation and value variables
q = Query(result_vars=[relation, value])
# get everyone with the name Barack Obama
q.add(subject=obama, relationship=FOAF.name,
object=Literal("Barack Obama", lang="en"))
# get every relation these people have to any object
q.add(subject=obama, relationship=relation, object=value)
# limit the results to the first 50 distince pairs
q.result_limit = 50
print(str(q))
print(pprint(q.execute()))
if __name__ == "__main__":
main()
| #!/usr/bin/env python
'''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
if __name__ == "__main__":
# construct the query variables (the explict names are optional)
obama, relation, value = BNode("Obama"), BNode("relation"), BNode("value")
# construct the query itself, selecting the relation and value variables
q = Query(result_vars=[relation, value])
# get everyone with the name Barack Obama
q.add(subject=obama, relationship=FOAF.name,
object=Literal("Barack Obama", lang="en"))
# get every relation these people have to any object
q.add(subject=obama, relationship=relation, object=value)
# limit the results to the first 50 distince pairs
q.result_limit = 50
print(str(q))
print(pprint(q.execute()))
|
Disable menu image popup (temporarily hopefully) | // ASPC namespace
var ASPC = ASPC || {};
/**
* @module
* @description Methods for the menu
*/
ASPC.menu = function () {
/**
* @private
*/
var my = {
self: this,
bind_qtip: function () {
var item_element = $(this);
var image_url = item_element.attr('image_url');
if (!!image_url && image_url != 'None') {
item_element.qtip({
content: '<img width="100px" height="100px" src="' + image_url + '">',
position: {
at: 'bottom center'
},
show: {
event: 'mouseover',
solo: true,
ready: true
},
hide: {
event: 'mouseout'
},
style: {
classes: 'qtip-bootstrap',
tip: {
width: 16,
height: 8
}
}
});
}
}
};
/**
* @public
* @description Binds a mouseover event on all item elements that assigns the qtip
*/
my.self.init = function () {
// .one() makes the qtip assignment happen only once
//$('#menu_table tr td ul li').one('mouseover', my.bind_qtip);
};
return my.self;
};
ASPC.Menu = new ASPC.menu();
$('document').ready(ASPC.Menu.init);
| // ASPC namespace
var ASPC = ASPC || {};
/**
* @module
* @description Methods for the menu
*/
ASPC.menu = function () {
/**
* @private
*/
var my = {
self: this,
bind_qtip: function () {
var item_element = $(this);
var image_url = item_element.attr('image_url');
if (!!image_url && image_url != 'None') {
item_element.qtip({
content: '<img width="100px" height="100px" src="' + image_url + '">',
position: {
at: 'bottom center'
},
show: {
event: 'mouseover',
solo: true,
ready: true
},
hide: {
event: 'mouseout'
},
style: {
classes: 'qtip-bootstrap',
tip: {
width: 16,
height: 8
}
}
});
}
}
};
/**
* @public
* @description Binds a mouseover event on all item elements that assigns the qtip
*/
my.self.init = function () {
// .one() makes the qtip assignment happen only once
$('#menu_table tr td ul li').one('mouseover', my.bind_qtip);
};
return my.self;
};
ASPC.Menu = new ASPC.menu();
$('document').ready(ASPC.Menu.init);
|
Revert test db to postgress | import os
class Config(object):
"""Parent configuration class."""
DEBUG = False
CSRF_ENABLED = True
SECRET_KEY = os.getenv('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
class DevelopmentConfig(Config):
"""Configurations for Development."""
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_db'
class TestingConfig(Config):
"""Configurations for Testing, with a separate test database."""
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/test_db'
DEBUG = True
class StagingConfig(Config):
"""Configurations for Staging."""
DEBUG = True
class ProductionConfig(Config):
"""Configurations for Production."""
DEBUG = False
TESTING = False
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'staging': StagingConfig,
'production': ProductionConfig,
}
| import os
class Config(object):
"""Parent configuration class."""
DEBUG = False
CSRF_ENABLED = True
SECRET_KEY = os.getenv('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
class DevelopmentConfig(Config):
"""Configurations for Development."""
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_db'
class TestingConfig(Config):
"""Configurations for Testing, with a separate test database."""
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///test_db.db'
DEBUG = True
class StagingConfig(Config):
"""Configurations for Staging."""
DEBUG = True
class ProductionConfig(Config):
"""Configurations for Production."""
DEBUG = False
TESTING = False
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'staging': StagingConfig,
'production': ProductionConfig,
}
|
[Correct]: Check if path is circular or not. Write from correct
repository. | '''
URL: http://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/
====
Python 2.7 compatible
Problem statement:
====================
Given a sequence of moves for a robot, check if the sequence is circular or not. A sequence of moves is circular if first and last positions of robot are same. A move can be on of the following.
G - Go one unit
L - Turn left
R - Turn right
'''
from operator import add
import math
moves = raw_input("Enter the moves: ")
start_position = [0,0]
current_position = [0,0]
'''
heading = [1,90] - 1 step North
[1, -90] - 1 step South
[1,0] - East
[1,360] - West
'''
heading = [1,0]
for move in moves:
if move.upper() == "G":
angle = heading[1]
step = heading[0]
# move_coord holds the x and y coordinate movement for the robot
move_coord = [ round(step*math.cos(math.radians(angle))), round(step*math.sin(math.radians(angle))) ]
current_position = map(add, current_position, move_coord)
elif move.upper() == "L":
# turn the robot 90 degrees anti-clockwise
heading = map(add, heading, [0, 90])
elif move.upper() == "R":
# turn the robot 90 degrees clockwise
heading = map(add, heading, [0, -90])
if start_position == current_position:
print "Given sequence of moves is circular"
else:
print "Given sequence of moves is NOT circular" | from operator import add
import math
moves = raw_input("Enter the moves: ")
start_position = [0,0]
current_position = [0,0]
'''
heading = [1,90] - 1 step North
[1, -90] - 1 step South
[1,0] - East
[1,360] - West
'''
heading = [1,0]
for move in moves:
if move.upper() == "G":
angle = heading[1]
step = heading[0]
move_coord = [ round(step*math.cos(math.radians(angle))), round(step*math.sin(math.radians(angle))) ]
current_position = map(add, current_position, move_coord)
elif move.upper() == "L":
heading = map(add, heading, [0, 90])
elif move.upper() == "R":
heading = map(add, heading, [0, -90])
if start_position == current_position:
print "Given sequence of moves is circular"
else:
print "Given sequence of moves is NOT circular" |
Fix return type of addStorageWrapper in PHPDoc | <?php
/**
* Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OCP\Files\Storage;
/**
* Creates storage instances and manages and applies storage wrappers
*/
interface IStorageFactory {
/**
* allow modifier storage behaviour by adding wrappers around storages
*
* $callback should be a function of type (string $mountPoint, Storage $storage) => Storage
*
* @param string $wrapperName
* @param callable $callback
* @return bool true if the wrapper was added, false if there was already a wrapper with this
* name registered
*/
public function addStorageWrapper($wrapperName, $callback);
/**
* @param string|boolean $mountPoint
* @param string $class
* @param array $arguments
* @return \OCP\Files\Storage
*/
public function getInstance($mountPoint, $class, $arguments);
}
| <?php
/**
* Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OCP\Files\Storage;
/**
* Creates storage instances and manages and applies storage wrappers
*/
interface IStorageFactory {
/**
* allow modifier storage behaviour by adding wrappers around storages
*
* $callback should be a function of type (string $mountPoint, Storage $storage) => Storage
*
* @param string $wrapperName
* @param callable $callback
* @return true if the wrapper was added, false if there was already a wrapper with this
* name registered
*/
public function addStorageWrapper($wrapperName, $callback);
/**
* @param string|boolean $mountPoint
* @param string $class
* @param array $arguments
* @return \OCP\Files\Storage
*/
public function getInstance($mountPoint, $class, $arguments);
}
|
Add classes to identify Upload Field interface actions. | jQuery(document).ready(function() {
jQuery('.field-upload').each(function() {
var field = jQuery(this);
var file = field.find('.file');
var upload = field.find('.upload');
var hidden = upload.find('input[type = "hidden"]');
if (file.length) {
var clear = jQuery('<a />')
.text('Change')
.addClass('action-change')
.prependTo(field.find('.label'));
var keep = jQuery('<a />')
.addClass('action-keep')
.text('Keep')
.prependTo(field.find('.label'))
.hide();
clear.bind('click', function() {
var file = jQuery('<input type="file" />');
file.attr('name', hidden.attr('name'));
clear.hide();
keep.show();
upload.show();
hidden.remove();
file.appendTo(upload);
});
keep.bind('click', function() {
var file = upload.find('input[type = "file"]');
clear.show();
keep.hide();
upload.hide();
file.remove();
hidden.appendTo(upload);
});
upload.hide();
}
});
}); | jQuery(document).ready(function() {
jQuery('.field-upload').each(function() {
var field = jQuery(this);
var file = field.find('.file');
var upload = field.find('.upload');
var hidden = upload.find('input[type = "hidden"]');
if (file.length) {
var clear = jQuery('<a />')
.text('Change')
.prependTo(field.find('.label'));
var keep = jQuery('<a />')
.text('Keep')
.prependTo(field.find('.label'))
.hide();
clear.bind('click', function() {
var file = jQuery('<input type="file" />');
file.attr('name', hidden.attr('name'));
clear.hide();
keep.show();
upload.show();
hidden.remove();
file.appendTo(upload);
});
keep.bind('click', function() {
var file = upload.find('input[type = "file"]');
clear.show();
keep.hide();
upload.hide();
file.remove();
hidden.appendTo(upload);
});
upload.hide();
}
});
}); |
Use phantomjs for snippets testing | const syrup = require('../../');
syrup.enableDebug()
.config(`${__dirname}/config.yaml`)
.scenario({
name: 'snippets - 1',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'PhantomJsBrowser'
})
.scenario({
name: 'snippets - 2',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'PhantomJsBrowser'
})
.scenario({
name: 'snippets - 3',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'PhantomJsBrowser'
})
.scenario({
name: 'snippets - 4',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'PhantomJsBrowser'
})
.pour();
| const syrup = require('../../');
syrup.enableDebug()
.config(`${__dirname}/config.yaml`)
.scenario({
name: 'snippets - 1',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'ChromeBrowser'
})
.scenario({
name: 'snippets - 2',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'ChromeBrowser'
})
.scenario({
name: 'snippets - 3',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'ChromeBrowser'
})
.scenario({
name: 'snippets - 4',
entrypoint: `${__dirname}/test-snippets`,
dependsOn: [],
worker: 'ChromeBrowser'
})
.pour();
|
Replace English "e-mail" by its translation | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
'password' => 'Les mots de passe doivent contenir au moins six caractères et doivent être identiques.',
'reset' => 'Votre mot de passe a été réinitialisé !',
'sent' => 'Nous vous avons envoyé par courriel le lien de réinitialisation du mot de passe !',
'token' => "Ce jeton de réinitialisation du mot de passe n'est pas valide.",
'user' => "Aucun utilisateur n'a été trouvé avec cette adresse mél.",
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
'password' => 'Les mots de passe doivent contenir au moins six caractères et doivent être identiques.',
'reset' => 'Votre mot de passe a été réinitialisé !',
'sent' => 'Nous vous avons envoyé par courriel le lien de réinitialisation du mot de passe !',
'token' => "Ce jeton de réinitialisation du mot de passe n'est pas valide.",
'user' => "Aucun utilisateur n'a été trouvé avec cette adresse e-mail.",
];
|
Add progress notification to clean cache command | 'use babel';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
import addProgressNotification from '../add-progress-notification';
const cleanCache = async () => {
let progress;
const options = {
onStart: () => {
progress = addProgressNotification('Cleaning global package cache...');
},
};
const success = await yarnExec(null, 'cache', ['clean'], options);
progress.dismiss();
if (!success) {
atom.notifications.addError(
'An error occurred whilst cleaning global cache. See output for more information.',
);
return;
}
atom.notifications.addSuccess('Global package cache has been cleaned');
};
const confirmation = async () => {
atom.confirm({
message: 'Are you sure you want to clean the global Yarn cache?',
detailedMessage:
'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.',
buttons: {
'Clean Cache': () => {
cleanCache().catch(reportError);
},
Cancel: null,
},
});
};
export default confirmation;
| 'use babel';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
const cleanCache = async () => {
const success = await yarnExec(null, 'cache', ['clean']);
if (!success) {
atom.notifications.addError(
'An error occurred whilst cleaning cache. See output for more information.',
);
return;
}
atom.notifications.addSuccess('Global package cache has been cleaned');
};
const confirmation = async () => {
atom.confirm({
message: 'Are you sure you want to clean the global Yarn cache?',
detailedMessage:
'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.',
buttons: {
'Clean Cache': () => {
cleanCache().catch(reportError);
},
Cancel: null,
},
});
};
export default confirmation;
|
Add case insensitive matching feature | chrome.storage.local.get(['pattern', 'case_insensitive', 'color', 'opacity'], function(items) {
var pattern, case_insensitive, color, opacity;
var re, flags;
pattern = items.pattern;
if (!pattern) {
pattern = 'WIP';
}
case_insensitive = !!items.case_insensitive;
if (case_insensitive) {
flags = 'i';
} else {
flags = '';
}
re = new RegExp(pattern, flags);
color = items.color || 'lightgray';
opacity = items.opacity || 0.7;
var unhighlighter = function(element, re, color, opacity) {
if (element.querySelector('.list-group-item-name').innerText.match(re)) {
element.style.backgroundColor = color;
element.style.opacity = opacity;
}
};
var target = document.querySelector('body');
var config = {
childList: true,
subtree: true
};
var observer = new MutationObserver(function(mutations, self) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
var elements = document.querySelectorAll('.pulls-list-group li.list-group-item');
Array.prototype.forEach.call(elements, function(element) {
unhighlighter(element, re, color, opacity);
});
}
});
});
observer.observe(target, config);
});
| chrome.storage.local.get(['pattern', 'color', 'opacity'], function(items) {
var pattern, color, opacity;
pattern = items.pattern;
if (!pattern) {
pattern = 'WIP';
}
pattern = new RegExp(pattern, 'i');
color = items.color || 'lightgray';
opacity = items.opacity || 0.7;
var unhighlighter = function(element, pattern, color, opacity) {
if (element.querySelector('.list-group-item-name').innerText.match(pattern)) {
element.style.backgroundColor = color;
element.style.opacity = opacity;
}
};
var target = document.querySelector('body');
var config = {
childList: true,
subtree: true
};
var observer = new MutationObserver(function(mutations, self) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
var elements = document.querySelectorAll('.pulls-list-group li.list-group-item');
Array.prototype.forEach.call(elements, function(element) {
unhighlighter(element, pattern, color, opacity);
});
}
});
});
observer.observe(target, config);
});
|
Update todo example. fixes 'Create' that shouldn't happen
Currently, an `onBlur` creates a new todo on `TodoTextInput`. This makes sense for existing items but not for new items. I.e consider the following:
1. cursor on new item ("What needs to be done?")
2. click 'x' on the first item.
This results in two actions being fired:
1. TODO_CREATE, with an empty string as 'text'
2. TODO_DESTROY
The proposed fix doesn't send a TODO_CREATE if `text.trim() === "")` | /**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @jsx React.DOM
*/
var React = require('react');
var TodoActions = require('../actions/TodoActions');
var TodoTextInput = require('./TodoTextInput.react');
var Header = React.createClass({
/**
* @return {object}
*/
render: function() {
return (
<header id="header">
<h1>todos</h1>
<TodoTextInput
id="new-todo"
placeholder="What needs to be done?"
onSave={this._onSave}
/>
</header>
);
},
/**
* Event handler called within TodoTextInput.
* Defining this here allows TodoTextInput to be used in multiple places
* in different ways.
* @param {string} text
*/
_onSave: function(text) {
if(text.trim()){
TodoActions.create(text);
}
}
});
module.exports = Header;
| /**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @jsx React.DOM
*/
var React = require('react');
var TodoActions = require('../actions/TodoActions');
var TodoTextInput = require('./TodoTextInput.react');
var Header = React.createClass({
/**
* @return {object}
*/
render: function() {
return (
<header id="header">
<h1>todos</h1>
<TodoTextInput
id="new-todo"
placeholder="What needs to be done?"
onSave={this._onSave}
/>
</header>
);
},
/**
* Event handler called within TodoTextInput.
* Defining this here allows TodoTextInput to be used in multiple places
* in different ways.
* @param {string} text
*/
_onSave: function(text) {
TodoActions.create(text);
}
});
module.exports = Header;
|
Fix trigger not returning itself, but undefined
`Array.prototype.forEach` returns `undefined` | module.exports = function() {
let subscribers = [], self
return self = {
// remove all subscribers
clear: (eventName) => {
subscribers = eventName != null
? subscribers.filter(subscriber => subscriber.eventName !== eventName)
: []
return self // return self to support chaining
},
// remove a subscriber
off: (eventName, callback) => {
const index = subscribers.findIndex(subscriber => subscriber.eventName === eventName && subscriber.callback === callback)
if (index >= 0) {
subscribers.splice(index, 1)
}
return self
},
// subscribe to an event
on: (eventName, callback) => {
subscribers.push({ eventName, callback })
return self
},
// trigger an event; all subscribers will be called
trigger: (eventName, data) => {
subscribers
.filter(subscriber => subscriber.eventName === eventName)
.forEach(subscriber => subscriber.callback(data))
return self
}
}
}
| module.exports = function() {
let subscribers = [], self
return self = {
// remove all subscribers
clear: (eventName) => {
subscribers = eventName != null
? subscribers.filter(subscriber => subscriber.eventName !== eventName)
: []
return self // return self to support chaining
},
// remove a subscriber
off: (eventName, callback) => {
const index = subscribers.findIndex(subscriber => subscriber.eventName === eventName && subscriber.callback === callback)
if (index >= 0) {
subscribers.splice(index, 1)
}
return self
},
// subscribe to an event
on: (eventName, callback) => {
subscribers.push({ eventName, callback })
return self
},
// trigger an event; all subscribers will be called
trigger: (eventName, data) => {
subscribers
.filter(subscriber => subscriber.eventName === eventName)
.forEach(subscriber => subscriber.callback(data))
return self
}
}
}
|
Change the position of popup | import React from 'react'
import { Popup, Image, Segment, Container, Statistic, Icon } from 'semantic-ui-react'
const User = ({ user, children }) => {
const url = user.url || `https://twitter.com/${user.screen_name}`
const profile_banner_url = user.profile_banner_url
const items = [
{label: 'Tweets', value: user.statuses_count},
{label: 'Following', value: user.friends_count},
{label: 'Followers', value: user.followers_count},
]
return (
<Popup
trigger={children}
position='bottom left'
hoverable
wide
size='huge'
>
<a href={url}>{user.name}</a>
{profile_banner_url ? (
<Image src={profile_banner_url} fluid />
) : null}
{user.description && user.description.length > 0 ? (
<Segment basic>
{user.description}
</Segment>
) : null}
<Statistic.Group items={items} size='mini' horizontal />
</Popup>
)
}
export default User
| import React from 'react'
import { Popup, Image, Segment, Container, Statistic, Icon } from 'semantic-ui-react'
const User = ({ user, children }) => {
const url = user.url || `https://twitter.com/${user.screen_name}`
const profile_banner_url = user.profile_banner_url
const items = [
{label: 'Tweets', value: user.statuses_count},
{label: 'Following', value: user.friends_count},
{label: 'Followers', value: user.followers_count},
]
return (
<Popup
trigger={children}
position='bottom right'
hoverable
wide
size='huge'
>
<a href={url}>{user.name}</a>
{profile_banner_url ? (
<Image src={profile_banner_url} fluid />
) : null}
{user.description && user.description.length > 0 ? (
<Segment basic>
{user.description}
</Segment>
) : null}
<Statistic.Group items={items} size='mini' horizontal />
</Popup>
)
}
export default User
|
Remove used of deprecated has_key() and replace with in | import li
import unittest
class LIAPITestSequence(unittest.TestCase):
def setup(self):
pass
def test_get_permits(self):
"""Returns the first 1,000 most recent permits as a list/JSON
"""
results = li.get_permits({})
self.assertEqual(type(results), list)
self.assertEqual(len(results), 1000)
def test_get_permit(self):
"""Returns details for a single permit
"""
results = li.get_permit(333274)
self.assertEqual(type(results), dict)
self.assertTrue('permit_type_code' in results.keys())
def test_get_permit_with_related(self):
"""Returns details for a specific permit
"""
results = li.get_permit(333274, related=True)
self.assertEqual(type(results), dict)
self.assertTrue('permit_type_code' in results.keys())
self.assertTrue('results' in results['zoningboardappeals'].keys())
self.assertTrue('street_name' in results['locations'].keys())
self.assertTrue('results' in results['buildingboardappeals'].keys())
if __name__ == '__main__':
unittest.main()
| import li
import unittest
class LIAPITestSequence(unittest.TestCase):
def setup(self):
pass
def test_get_permits(self):
"""Returns the first 1,000 most recent permits as a list/JSON
"""
results = li.get_permits({})
self.assertEqual(type(results), list)
self.assertEqual(len(results), 1000)
def test_get_permit(self):
"""Returns details for a single permit
"""
results = li.get_permit(333274)
self.assertEqual(type(results), dict)
self.assertTrue(results.has_key('permit_type_code'))
def test_get_permit_with_related(self):
"""Returns details for a specific permit
"""
results = li.get_permit(333274, related=True)
self.assertEqual(type(results), dict)
self.assertTrue(results.has_key('permit_type_code'))
self.assertTrue(results['zoningboardappeals'].has_key('results'))
self.assertTrue(results['locations'].has_key('street_name'))
self.assertTrue(results['buildingboardappeals'].has_key('results'))
if __name__ == '__main__':
unittest.main()
|
Fix error message of composer version | <?php
/*
* This file is part of the Foxy package.
*
* (c) François Pluchino <francois.pluchino@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Foxy\Util;
use Foxy\Exception\RuntimeException;
/**
* Helper for Composer.
*
* @author François Pluchino <francois.pluchino@gmail.com>
*/
class ComposerUtil
{
/**
* Validate the composer version.
*
* @param string $requiredVersion The composer required version
* @param string $composerVersion The composer version
*/
public static function validateVersion($requiredVersion, $composerVersion)
{
if (false === strpos($composerVersion, '@') && !version_compare($composerVersion, $requiredVersion, '>=')) {
$msg = 'Foxy requires the Composer\'s minimum version "%s", current version is "%s"';
throw new RuntimeException(sprintf($msg, $requiredVersion, $composerVersion));
}
}
}
| <?php
/*
* This file is part of the Foxy package.
*
* (c) François Pluchino <francois.pluchino@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Foxy\Util;
use Foxy\Exception\RuntimeException;
/**
* Helper for Composer.
*
* @author François Pluchino <francois.pluchino@gmail.com>
*/
class ComposerUtil
{
/**
* Validate the composer version.
*
* @param string $requiredVersion The composer required version
* @param string $composerVersion The composer version
*/
public static function validateVersion($requiredVersion, $composerVersion)
{
if (false === strpos($composerVersion, '@') && !version_compare($composerVersion, $requiredVersion, '>=')) {
$msg = 'Foxy requires the Composer\'s minimum version "%s", current version is "%s"';
throw new RuntimeException(sprintf($msg, $composerVersion, $requiredVersion));
}
}
}
|
Use correct repository in debug thing | package net.hillsdon.reviki.vc.impl;
import net.hillsdon.reviki.vc.AttachmentHistory;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
public class AttachmentListingDebug {
public static void main(String[] args) throws Exception {
DAVRepositoryFactory.setup();
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded("https://svn-dev-plaintext.int.corefiling.com/svn/web/wiki/dsl"));
repository.setAuthenticationManager(SVNWCUtil.createDefaultAuthenticationManager());
RepositoryBasicSVNOperations operations = new RepositoryBasicSVNOperations(repository, null);
SVNPageStore store = new SVNPageStore("wiki", new InMemoryDeletedRevisionTracker(), operations, null, null);
for (AttachmentHistory attachment : store.attachments(new PageReferenceImpl("Printing"))) {
System.err.println(attachment.getName());
}
}
}
| package net.hillsdon.reviki.vc.impl;
import net.hillsdon.reviki.vc.AttachmentHistory;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
public class AttachmentListingDebug {
public static void main(String[] args) throws Exception {
DAVRepositoryFactory.setup();
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded("http://svn.dsl.local/svn/web/wiki/dsl"));
repository.setAuthenticationManager(SVNWCUtil.createDefaultAuthenticationManager());
RepositoryBasicSVNOperations operations = new RepositoryBasicSVNOperations(repository, null);
SVNPageStore store = new SVNPageStore("wiki", new InMemoryDeletedRevisionTracker(), operations, null, null);
for (AttachmentHistory attachment : store.attachments(new PageReferenceImpl("Printing"))) {
System.err.println(attachment.getName());
}
}
}
|
Fix tests by switching to es5 syntax in finding bundles | /**
* ES6 not supported here
*/
import Ember from "ember";
import config from 'ember-get-config';
export default Ember.Mixin.create({
bundleLoader: Ember.inject.service("bundle-loader"),
findBundleNameByRoute: function(routeName){
//Find bundle for route
var bundleName = null;
var bundleNames = Object.keys(config.bundles);
bundleNames.forEach(function(name) {
var bundle = config.bundles[name];
if(bundle.routes.indexOf(routeName) >= 0) {
bundleName = name;
}
});
return bundleName;
},
beforeModel: function(transition, queryParams){
this._super(transition,queryParams);
let service = this.get("bundleLoader");
let bundleName = this.findBundleNameByRoute(transition.targetName);
return service.loadBundle(bundleName);
}
});
| /**
* ES6 not supported here
*/
import Ember from "ember";
import config from 'ember-get-config';
export default Ember.Mixin.create({
bundleLoader: Ember.inject.service("bundle-loader"),
findBundleNameByRoute: function(routeName){
//Find bundle for route
var foundBundleName = Object.keys(config.bundles)
.find((name)=> {
let bundle = config.bundles[name];
return bundle.routes.indexOf(routeName)>-1;
});
return foundBundleName;
},
beforeModel: function(transition, queryParams){
this._super(transition,queryParams);
let service = this.get("bundleLoader");
let bundleName = this.findBundleNameByRoute(transition.targetName);
return service.loadBundle(bundleName);
}
}); |
Add comment to example regarding source. |
var BurpImporter = require(__dirname + '/../index'),
util = require('util');
// source below may be stream or filename.
var importer = new BurpImporter(__dirname + '/example1.xml');
importer.on('start', function (info) {
console.log('Dump: start');
console.log(' burpVersion: ' + info.burpVersion);
console.log(' exportTime: ' + info.exportTime);
console.log('********');
});
importer.on('item', function (item) {
console.log(' url: ' + item.url);
console.log(' port: ' + item.port);
console.log(' path: ' + item.path);
console.log(' method: ' + item.method);
console.log(' host: ' + item.host);
console.log(' protocol: ' + item.protocol);
console.log(' status: ' + item.status);
console.log(' time: ' + item.time);
console.log(' responselength: ' + item.responselength);
console.log(' mimetype: ' + item.mimetype);
console.log(' extension: ' + item.extension);
console.log(' request: ' + item.request.toString().substring(0, 10) + '...');
console.log(' response: ' + item.response.toString().substring(0, 10) + '...');
console.log('********');
});
importer.on('end', function () {
console.log('Dump: end');
});
importer.import();
|
var BurpImporter = require(__dirname + '/../index'),
util = require('util');
var importer = new BurpImporter(__dirname + '/example1.xml');
importer.on('start', function (info) {
console.log('Dump: start');
console.log(' burpVersion: ' + info.burpVersion);
console.log(' exportTime: ' + info.exportTime);
console.log('********');
});
importer.on('item', function (item) {
console.log(' url: ' + item.url);
console.log(' port: ' + item.port);
console.log(' path: ' + item.path);
console.log(' method: ' + item.method);
console.log(' host: ' + item.host);
console.log(' protocol: ' + item.protocol);
console.log(' status: ' + item.status);
console.log(' time: ' + item.time);
console.log(' responselength: ' + item.responselength);
console.log(' mimetype: ' + item.mimetype);
console.log(' extension: ' + item.extension);
console.log(' request: ' + item.request.toString().substring(0, 10) + '...');
console.log(' response: ' + item.response.toString().substring(0, 10) + '...');
console.log('********');
});
importer.on('end', function () {
console.log('Dump: end');
});
importer.import();
|
Add static root path to tests | """Evaluates all the tests that live in `scss/tests/files`.
A test is any file with a `.scss` extension. It'll be compiled, and the output
will be compared to the contents of a file named `foo.css`.
Currently, test files must be nested exactly one directory below `files/`.
This limitation is completely arbitrary.
"""
from __future__ import absolute_import
import glob
import os.path
import logging
import pytest
import scss
console = logging.StreamHandler()
logger = logging.getLogger('scss')
logger.setLevel(logging.ERROR)
logger.addHandler(console)
def test_pair_programmatic(scss_file_pair):
scss_fn, css_fn, pytest_trigger = scss_file_pair
if pytest_trigger:
pytest_trigger()
with open(scss_fn) as fh:
source = fh.read()
with open(css_fn) as fh:
expected = fh.read()
directory, _ = os.path.split(scss_fn)
include_dir = os.path.join(directory, 'include')
scss.config.STATIC_ROOT = os.path.join(directory, 'static')
compiler = scss.Scss(scss_opts=dict(compress=0), search_paths=[include_dir])
actual = compiler.compile(source)
# Normalize leading and trailing newlines
actual = actual.strip('\n')
expected = expected.strip('\n')
assert expected == actual
| """Evaluates all the tests that live in `scss/tests/files`.
A test is any file with a `.scss` extension. It'll be compiled, and the output
will be compared to the contents of a file named `foo.css`.
Currently, test files must be nested exactly one directory below `files/`.
This limitation is completely arbitrary.
"""
from __future__ import absolute_import
import glob
import os.path
import logging
import pytest
from scss import Scss
console = logging.StreamHandler()
logger = logging.getLogger('scss')
logger.setLevel(logging.ERROR)
logger.addHandler(console)
def test_pair_programmatic(scss_file_pair):
scss_fn, css_fn, pytest_trigger = scss_file_pair
if pytest_trigger:
pytest_trigger()
with open(scss_fn) as fh:
source = fh.read()
with open(css_fn) as fh:
expected = fh.read()
directory, _ = os.path.split(scss_fn)
include_dir = os.path.join(directory, 'include')
compiler = Scss(scss_opts=dict(compress=0), search_paths=[include_dir])
actual = compiler.compile(source)
# Normalize leading and trailing newlines
actual = actual.strip('\n')
expected = expected.strip('\n')
assert expected == actual
|
Fix django custom template tag importing | #!/usr/bin/env python
import env_setup; env_setup.setup(); env_setup.setup_django()
from django.template import add_to_builtins
add_to_builtins('agar.django.templatetags')
from webapp2 import RequestHandler, Route, WSGIApplication
from agar.env import on_production_server
from agar.config import Config
from agar.django.templates import render_template
class MainApplicationConfig(Config):
"""
:py:class:`~agar.config.Config` settings for the ``main`` `webapp2.WSGIApplication`_.
Settings are under the ``main_application`` namespace.
The following settings (and defaults) are provided::
main_application_NOOP = None
To override ``main`` `webapp2.WSGIApplication`_ settings, define values in the ``appengine_config.py`` file in the
root of your project.
"""
_prefix = 'main_application'
#: A no op.
NOOP = None
config = MainApplicationConfig.get_config()
class MainHandler(RequestHandler):
def get(self):
render_template(self.response, 'index.html')
application = WSGIApplication(
[
Route('/', MainHandler, name='main'),
],
debug=not on_production_server)
def main():
from google.appengine.ext.webapp import template, util
template.register_template_library('agar.django.templatetags')
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from env_setup import setup_django
setup_django()
from env_setup import setup
setup()
from webapp2 import RequestHandler, Route, WSGIApplication
from agar.env import on_production_server
from agar.config import Config
from agar.django.templates import render_template
class MainApplicationConfig(Config):
"""
:py:class:`~agar.config.Config` settings for the ``main`` `webapp2.WSGIApplication`_.
Settings are under the ``main_application`` namespace.
The following settings (and defaults) are provided::
main_application_NOOP = None
To override ``main`` `webapp2.WSGIApplication`_ settings, define values in the ``appengine_config.py`` file in the
root of your project.
"""
_prefix = 'main_application'
#: A no op.
NOOP = None
config = MainApplicationConfig.get_config()
class MainHandler(RequestHandler):
def get(self):
render_template(self.response, 'index.html')
application = WSGIApplication(
[
Route('/', MainHandler, name='main'),
],
debug=not on_production_server)
def main():
from google.appengine.ext.webapp import template, util
template.register_template_library('agar.django.templatetags')
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
|
Fix build event listener method name | <?php
/**
*
* @author h.woltersdorf
*/
namespace Fortuneglobe\IceHawk;
use Fortuneglobe\IceHawk\Exceptions\EventListenerMethodNotCallable;
use Fortuneglobe\IceHawk\Interfaces\ListensToIceHawkEvents;
use Fortuneglobe\IceHawk\Interfaces\ServesIceHawkEventData;
/**
* Class IceHawkEventListener
*
* @package Fortuneglobe\IceHawk
*/
abstract class IceHawkEventListener implements ListensToIceHawkEvents
{
/**
* @param ServesIceHawkEventData $event
*
* @return bool
*/
public function acceptsEvent( ServesIceHawkEventData $event )
{
return in_array( get_class( $event ), $this->getAcceptedEvents() );
}
/**
* @param ServesIceHawkEventData $event
*
* @throws EventListenerMethodNotCallable
*/
public function notify( ServesIceHawkEventData $event )
{
$namespaceComponents = explode( "\\", get_class( $event ) );
$methodName = sprintf( 'when%s', preg_replace( "#Event$#", '', end( $namespaceComponents ) ) );
if ( is_callable( [ $this, $methodName ] ) )
{
$this->{$methodName}( $event );
}
else
{
throw new EventListenerMethodNotCallable( $methodName );
}
}
}
| <?php
/**
*
* @author h.woltersdorf
*/
namespace Fortuneglobe\IceHawk;
use Fortuneglobe\IceHawk\Exceptions\EventListenerMethodNotCallable;
use Fortuneglobe\IceHawk\Interfaces\ListensToIceHawkEvents;
use Fortuneglobe\IceHawk\Interfaces\ServesIceHawkEventData;
/**
* Class IceHawkEventListener
*
* @package Fortuneglobe\IceHawk
*/
abstract class IceHawkEventListener implements ListensToIceHawkEvents
{
/**
* @param ServesIceHawkEventData $event
*
* @return bool
*/
public function acceptsEvent( ServesIceHawkEventData $event )
{
return in_array( get_class( $event ), $this->getAcceptedEvents() );
}
/**
* @param ServesIceHawkEventData $event
*
* @throws EventListenerMethodNotCallable
*/
public function notify( ServesIceHawkEventData $event )
{
$methodName = sprintf( 'when', preg_replace( '#Event$#', '', get_class( $event ) ) );
if ( is_callable( [ $this, $methodName ] ) )
{
$this->{$methodName}( $event );
}
else
{
throw new EventListenerMethodNotCallable( $methodName );
}
}
}
|
Add getter for restapi instance | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;
/**
* @author bjorncs
*/
public abstract class RestApiRequestHandler<T extends RestApiRequestHandler<T>> extends LoggingRequestHandler {
private final RestApi restApi;
@FunctionalInterface public interface RestApiProvider<T> { RestApi createRestApi(T self); }
/**
* RestApi will usually refer to handler methods of subclass, which are not accessible before super constructor has completed.
* This is hack to leak reference to subclass instance's "this" reference.
* Caller must ensure that provider instance does not try to access any uninitialized fields.
*/
@SuppressWarnings("unchecked")
protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApiProvider<T> provider) {
super(context);
this.restApi = provider.createRestApi((T)this);
}
protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) {
super(context);
this.restApi = restApi;
}
@Override public final HttpResponse handle(HttpRequest request) { return restApi.handleRequest(request); }
protected RestApi restApi() { return restApi; }
}
| // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;
/**
* @author bjorncs
*/
public abstract class RestApiRequestHandler<T extends RestApiRequestHandler<T>> extends LoggingRequestHandler {
private final RestApi restApi;
@FunctionalInterface public interface RestApiProvider<T> { RestApi createRestApi(T self); }
/**
* RestApi will usually refer to handler methods of subclass, which are not accessible before super constructor has completed.
* This is hack to leak reference to subclass instance's "this" reference.
* Caller must ensure that provider instance does not try to access any uninitialized fields.
*/
@SuppressWarnings("unchecked")
protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApiProvider<T> provider) {
super(context);
this.restApi = provider.createRestApi((T)this);
}
protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) {
super(context);
this.restApi = restApi;
}
@Override public final HttpResponse handle(HttpRequest request) { return restApi.handleRequest(request); }
}
|
Add base test for getSVG function. It fails | defaultConf = {
height: 100,
width: 300,
fingerprintLength: 4
};
describe("The constructor is supposed a proper Captcha object", function() {
it('Constructor Captcha exists', function(){
expect(Captcha).toBeDefined();
});
var captcha = new Captcha();
it("Captcha object is not null", function(){
expect(captcha).not.toBeNull();
});
it('captcha object should be an instance of Captcha class', function(){
expect(captcha instanceof Captcha).toBeTruthy();
});
it('the height of the svg should be set to the configured height', function(){
expect(Number(captcha.height)).toEqual(defaultConf.height);
});
it('the width of the svg should be set to the configured width', function(){
expect(Number(captcha.width)).toEqual(defaultConf.width);
});
it('the length of the fingerprint should be set to the configured fingerprintLength', function(){
expect(Number(captcha.fingerprintLength)).toEqual(defaultConf.fingerprintLength);
});
});
describe('The setData method of Captcha objects is supposed to generate the captcha as SVG', function(){
var captcha = new Captcha();
it('getSVG method is supposed to be a function', function(){
expect(typeof captcha.getSVG()).toEqual('function');
});
});
| defaultConf = {
height: 100,
width: 300,
fingerprintLength: 4
};
describe("The constructor is supposed a proper Captcha object", function() {
it('Constructor Captcha exists', function(){
expect(Captcha).toBeDefined();
});
var captcha = new Captcha();
it("Captcha object is not null", function(){
expect(captcha).not.toBeNull();
});
it('captcha object should be an instance of Captcha class', function(){
expect(captcha instanceof Captcha).toBeTruthy();
});
it('the height of the svg should be set to the configured height', function(){
expect(Number(captcha.height)).toEqual(defaultConf.height);
});
it('the width of the svg should be set to the configured width', function(){
expect(Number(captcha.width)).toEqual(defaultConf.width);
});
it('the length of the fingerprint should be set to the configured fingerprintLength', function(){
expect(Number(captcha.fingerprintLength)).toEqual(defaultConf.fingerprintLength);
});
});
|
FE: Send GA event when print page button is clicked | (function () {
'use strict';
moj.Modules.PrintPageButton = {
init: function() {
this.initTemplates();
this.renderButton();
},
renderButton: function() {
var contentArea = $('.confirmation');
if(!contentArea.length || !this.printButton || !this.printButton.length) {
return;
}
contentArea.append(this.printButton);
this.printButton.on('click', function() {
window.print();
if(window.ga) {
window.ga('send', 'event', 'confirmation', 'printed');
}
});
},
initTemplates: function() {
var template = $('#printButtonTemplate');
if(template.length) {
this.printButton = $(_.template(template.html())());
}
}
};
}());
| (function () {
'use strict';
moj.Modules.PrintPageButton = {
init: function() {
this.initTemplates();
this.renderButton();
},
renderButton: function() {
var contentArea = $('.confirmation');
if(!contentArea.length || !this.printButton || !this.printButton.length) {
return;
}
contentArea.append(this.printButton);
this.printButton.on('click', function() {
window.print();
});
},
initTemplates: function() {
var template = $('#printButtonTemplate');
if(template.length) {
this.printButton = $(_.template(template.html())());
}
}
};
}());
|
Add ws4py to normal requirements in an attempt to get Travis to install it | from setuptools import setup, find_packages
setup(
name="echidna",
version="0.0.1-dev",
url='http://github.com/praekelt/echidna',
license='BSD',
description='A scalable pub-sub WebSocket service.',
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
install_requires=[
'Twisted',
'cyclone',
'txzookeeper',
'redis',
'zope.dottedname',
'ws4py',
],
tests_require=[
'ws4py',
'requests',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Cyclone',
'Framework :: Twisted',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Communications',
'Topic :: Internet',
'Topic :: System :: Networking',
]
)
| from setuptools import setup, find_packages
setup(
name="echidna",
version="0.0.1-dev",
url='http://github.com/praekelt/echidna',
license='BSD',
description='A scalable pub-sub WebSocket service.',
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
install_requires=[
'Twisted',
'cyclone',
'txzookeeper',
'redis',
'zope.dottedname',
],
tests_require=[
'ws4py',
'requests',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Cyclone',
'Framework :: Twisted',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Communications',
'Topic :: Internet',
'Topic :: System :: Networking',
]
)
|
Remove error levels for PHP | <?php
/**
* @desc Bootstrap base engine classes
* @package M2 Micro Framework
* @subpackage Main
* @author Alexander Chaika
*/
// start session
if (isset($_COOKIE['PHPSESSID'])) {
session_id($_COOKIE['PHPSESSID']);
}
session_start();
// set working mode
date_default_timezone_set('Europe/Minsk');
ini_set('display_errors', 1);
// Simple ACL hook
define('M2_MICRO', 1);
// define globals
define('NL', chr(13).chr(10));
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_PATH', __DIR__);
define('LIB_PATH', ROOT_PATH . DS . 'includes');
// errors & messages levels
define('ERROR', 1);
define('WARNING', 2);
define('NOTICE', 6);
define('MESSAGE', 8);
// system classes
require_once LIB_PATH . DS . '_function.php';
require_once LIB_PATH . DS . '_autoload.php'; | <?php
/**
* @desc Bootstrap base engine classes
* @package M2 Micro Framework
* @subpackage Main
* @author Alexander Chaika
*/
// start session
if (isset($_COOKIE['PHPSESSID'])) {
session_id($_COOKIE['PHPSESSID']);
}
session_start();
// set working mode
date_default_timezone_set('Europe/Minsk');
ini_set('display_errors', 1);
ini_set('error_reporting', 'E_ALL & ~E_NOTICE & ~E_DEPRECATED');
// Simple ACL hook
define('M2_MICRO', 1);
// define globals
define('NL', chr(13).chr(10));
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_PATH', __DIR__);
define('LIB_PATH', ROOT_PATH . DS . 'includes');
// errors & messages levels
define('ERROR', 1);
define('WARNING', 2);
define('NOTICE', 6);
define('MESSAGE', 8);
// system classes
require_once LIB_PATH . DS . '_function.php';
require_once LIB_PATH . DS . '_autoload.php'; |
Use from dials_regression.image_examples.get_all_working_images import get_all_working_images method to get list of images | def tst_dxtbx():
import libtbx.load_env
import os
dials_regression = libtbx.env.dist_path('dials_regression')
from boost.python import streambuf
from dxtbx import read_uint16
from dxtbx.format.Registry import Registry
from dials_regression.image_examples.get_all_working_images import \
get_all_working_images
for directory, image in get_all_working_images():
file_path = os.path.join(dials_regression, 'image_examples',
directory, image)
format = Registry.find(file_path)
i = format(file_path)
size = i.get_detector().get_image_size()
print 'OK'
tst_dxtbx()
| def tst_dxtbx():
import libtbx.load_env
import os
dials_regression = libtbx.env.dist_path('dials_regression')
from boost.python import streambuf
from dxtbx import read_uint16
from dxtbx.format.Registry import Registry
for directory, image in [('SLS_X06SA', 'mar225_2_001.img')]:
file_path = os.path.join(dials_regression, 'image_examples',
directory, image)
format = Registry.find(file_path)
i = format(file_path)
size = i.get_detector().get_image_size()
print 'OK'
tst_dxtbx()
|
Update alexa pi server script. | from flask import Flask
from flask_ask import Ask, statement, convert_errors
import logging
from rfsend import rf_send
app = Flask(__name__)
ask = Ask(app, '/')
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.intent('LocationControlIntent', mapping={'status': 'status', 'location': 'location'})
def location_control(status, location):
render_message(location, status)
return statement('Turning {} {}!'.format(location, status))
def render_message(location, status):
loc = location.lower()
status = status.lower()
if loc == 'lights':
rf_send('4', status)
rf_send('5', status)
rf_send('2', status)
elif loc == 'christmas':
rf_send('2', status)
elif location == 'kettle':
rf_send('1', status)
if __name__ == '__main__':
port = 5500 #the custom port you want
app.run(host='0.0.0.0', port=port)
| from flask import Flask
from flask_ask import Ask, statement, convert_errors
import logging
from rfsend import rf_send
GPIO.setmode(GPIO.BCM)
app = Flask(__name__)
ask = Ask(app, '/')
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.intent('LocationControlIntent', mapping={'status': 'status', 'location': 'location'})
def location_control(status, location):
render_message(location, status)
return statement('Turning {} {}!'.format(location, status))
def render_message(location, status):
loc = location.lower()
status = status.lower()
if loc == 'lights':
rf_send('4', status)
rf_send('5', status)
rf_send('2', status)
elif loc == 'christmas':
rf_send('2', status)
elif location == 'kettle':
rf_send('1', status)
if __name__ == '__main__':
port = 5500 #the custom port you want
app.run(host='0.0.0.0', port=port)
|
Fix additional missing return statement. | var AsyncDiskCache = require('async-disk-cache');
var Promise = require('rsvp').Promise;
module.exports = {
_cache: {},
init: function(ctx) {
if (!ctx.constructor._persistentCacheKey) {
ctx.constructor._persistentCacheKey = this.cacheKey(ctx);
}
this._cache = new AsyncDiskCache(ctx.constructor._persistentCacheKey, {
compression: 'deflate'
});
},
cacheKey: function(ctx) {
return ctx.cacheKey();
},
processString: function(ctx, contents, relativePath) {
var key = ctx.cacheKeyProcessString(contents, relativePath);
var cache = this._cache;
return cache.get(key).then(function(entry) {
if (entry.isCached) {
return entry.value;
} else {
var string = Promise.resolve(ctx.processString(contents, relativePath));
return string.then(function(string) {
return cache.set(key, string).then(function() {
return string;
});
});
}
});
}
};
| var AsyncDiskCache = require('async-disk-cache');
var Promise = require('rsvp').Promise;
module.exports = {
_cache: {},
init: function(ctx) {
if (!ctx.constructor._persistentCacheKey) {
ctx.constructor._persistentCacheKey = this.cacheKey(ctx);
}
this._cache = new AsyncDiskCache(ctx.constructor._persistentCacheKey, {
compression: 'deflate'
});
},
cacheKey: function(ctx) {
return ctx.cacheKey();
},
processString: function(ctx, contents, relativePath) {
var key = ctx.cacheKeyProcessString(contents, relativePath);
var cache = this._cache;
return cache.get(key).then(function(entry) {
if (entry.isCached) {
return entry.value;
} else {
var string = Promise.resolve(ctx.processString(contents, relativePath));
string.then(function(string) {
return cache.set(key, string).then(function() {
return string;
});
});
}
});
}
};
|
Fix bug where auth would pass on after failure | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const jwt = require('jsonwebtoken');
const secretToken = require('../config').secretToken;
const validate = require('jsonschema').validate;
/**
* Middleware function to force a route to require authentication
* Verifies the request's token against the server's secret token
*/
module.exports = (req, res, next) => {
const token = req.headers.token || req.body.token || req.query.token;
const validParams = {
type: 'string'
};
if (!validate(token, validParams).valid) {
res.sendStatus(400);
} else if (token) {
jwt.verify(token, secretToken, (err, decoded) => {
if (err) {
res.status(401).json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
next();
}
});
} else {
res.status(403).send({
success: false,
message: 'No token provided.'
});
}
};
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const jwt = require('jsonwebtoken');
const secretToken = require('../config').secretToken;
const validate = require('jsonschema').validate;
/**
* Middleware function to force a route to require authentication
* Verifies the request's token against the server's secret token
*/
module.exports = (req, res, next) => {
const token = req.headers.token || req.body.token || req.query.token;
const validParams = {
type: 'string'
};
if (!validate(token, validParams).valid) {
res.sendStatus(400);
} else if (token) {
jwt.verify(token, secretToken, (err, decoded) => {
if (err) {
res.status(401).json({ success: false, message: 'Failed to authenticate token.' });
}
req.decoded = decoded;
next();
});
} else {
res.status(403).send({
success: false,
message: 'No token provided.'
});
}
};
|
Change to better argument name | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input_value):
"""
Writes text to a textbox.
``locator`` is the locator of the text box.
``input_value`` is the text to write.
"""
textBox = self.state._get_typed_item_by_locator(TextBox, locator)
textBox.Text = input_value
@keyword
def verify_text_in_textbox(self, locator, expected):
"""
Verifies text in a text box.
``locator`` is the locator of the text box.
``expected`` is the expected text of the text box.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
self.state._verify_value(expected, textbox.Text)
@keyword
def get_text_from_textbox(self, locator):
"""
Gets text from text box.
``locator`` is the locator of the text box.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
return textbox.Text
| from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input):
"""
Writes text to a textbox.
``locator`` is the locator of the text box.
``input`` is the text to write.
"""
textBox = self.state._get_typed_item_by_locator(TextBox, locator)
textBox.Text = input
@keyword
def verify_text_in_textbox(self, locator, expected):
"""
Verifies text in a text box.
``locator`` is the locator of the text box.
``expected`` is the expected text of the text box.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
self.state._verify_value(expected, textbox.Text)
@keyword
def get_text_from_textbox(self, locator):
"""
Gets text from text box.
``locator`` is the locator of the text box.
"""
textbox = self.state._get_typed_item_by_locator(TextBox, locator)
return textbox.Text
|
Add the consumer key to the identifier
Used for rate limiting by API key.
Refs #17338 | """
Tastypie API Authorization handlers
"""
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
class ApplicationAuthentication(Authentication):
"""
Authenticate the API request by checking the application key.
"""
def is_authenticated(self, request, **kwargs):
"""
Check that the request is signed by the application.
"""
consumer = getattr(request, 'consumer', None)
return consumer is not None
def get_identifier(self, request):
"""
Return a combination of the consumer, the IP address and the host
"""
consumer = getattr(request, 'consumer', None)
return '%s_%s' % (
consumer.key(),
super(ApplicationAuthentication, self).get_identifier(request))
class ApplicationAuthorization(Authorization):
"""
Authorize the API request by checking the application key.
"""
#
# pylint:disable=W0613,W0622,R0201
# Redefining built-in 'object'
# Unused argument 'object'
# Method could be a function
#
# Part of Tastypie API - cannot change any of the above
#
def is_authorized(self, request, object=None):
"""
Check that the request is signed by the application.
"""
consumer = getattr(request, 'consumer', None)
return consumer is not None
| """
Tastypie API Authorization handlers
"""
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
class ApplicationAuthentication(Authentication):
"""
Authenticate the API request by checking the application key.
"""
def is_authenticated(self, request, **kwargs):
"""
Check that the request is signed by the application.
"""
consumer = getattr(request, 'consumer', None)
return consumer is not None
class ApplicationAuthorization(Authorization):
"""
Authorize the API request by checking the application key.
"""
#
# pylint:disable=W0613,W0622,R0201
# Redefining built-in 'object'
# Unused argument 'object'
# Method could be a function
#
# Part of Tastypie API - cannot change any of the above
#
def is_authorized(self, request, object=None):
"""
Check that the request is signed by the application.
"""
consumer = getattr(request, 'consumer', None)
return consumer is not None
|
Add comment to HTMLValidator factory. | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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
*/
foam.CLASS({
package: 'foam.u2',
name: 'HTMLValidator',
extends: 'foam.u2.DefaultValidator',
axioms: [ foam.pattern.Singleton.create() ],
methods: [
function sanitizeText(text) {
// TODO: validate text
return text;
}
]
});
// An Element which does not escape HTML content
foam.CLASS({
package: 'foam.u2',
name: 'HTMLElement',
extends: 'foam.u2.Element',
requires: [ 'foam.u2.HTMLValidator' ],
exports: [ 'validator as elementValidator' ],
properties: [
{
class: 'Proxy',
of: 'foam.u2.DefaultValidator',
name: 'validator',
factory: function() {
// Note that HTMLValidator is a singleton so only once instance of
// HTMLValidator should ever be created here.
return this.HTMLValidator.create()
}
}
]
});
| /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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
*/
foam.CLASS({
package: 'foam.u2',
name: 'HTMLValidator',
extends: 'foam.u2.DefaultValidator',
axioms: [ foam.pattern.Singleton.create() ],
methods: [
function sanitizeText(text) {
// TODO: validate text
return text;
}
]
});
// An Element which does not escape HTML content
foam.CLASS({
package: 'foam.u2',
name: 'HTMLElement',
extends: 'foam.u2.Element',
requires: [ 'foam.u2.HTMLValidator' ],
exports: [ 'validator as elementValidator' ],
properties: [
{
class: 'Proxy',
of: 'foam.u2.DefaultValidator',
name: 'validator',
factory: function() { return this.HTMLValidator.create() }
}
]
});
|
Implement compile the entire input directory and output to the (current working|speciy) directory | import path from "path";
import objectAssign from "object-assign";
import defaultOptions from "./default-options";
import Config from "../config";
import Kotori from "../index";
/**
* Create a new instance of the core CLI engine
* @param {CLIEngineOptions} options - Kotori CLI options object (see: ./default-options.js)
*/
export default class CLIEngline {
constructor(options) {
this.currentOptions = objectAssign(defaultOptions, options);
this.config = new Config(this.currentOptions.config);
}
/**
* Executes the current configuration on an array of file and directory names
* @param {String[]} patterns - An array of file and directory names
* @returns {Stream} Readable/Writable stream
*/
executeOnFiles(patterns) {
if (patterns.length > 1) {
throw new Error("Specify input path of too many");
} else if (patterns.length < 1) {
throw new Error("Must be specify input path");
}
const kotori = new Kotori();
let src = patterns[0];
if (path.extname(src) === "") {
src = `${src}/*.*`;
}
return kotori.src(src)
.pipe(kotori.build(this.config))
.pipe(kotori.dest(this.currentOptions.output));
}
}
| import objectAssign from "object-assign";
import defaultOptions from "./default-options";
import Config from "../config";
import Kotori from "../index";
/**
* Create a new instance of the core CLI engine
* @param {CLIEngineOptions} options - Kotori CLI options object (see: ./default-options.js)
*/
export default class CLIEngline {
constructor(options) {
this.currentOptions = objectAssign(defaultOptions, options);
this.config = new Config(this.currentOptions.config);
}
/**
* Executes the current configuration on an array of file and directory names
* @param {String[]} patterns - An array of file and directory names
* @returns {Stream} Readable/Writable stream
*/
executeOnFiles(patterns) {
if (patterns.length > 1) {
throw new Error("Specify input path of too many");
} else if (patterns.length < 1) {
throw new Error("Must be specify input path");
}
const kotori = new Kotori();
return kotori.src(patterns[0])
.pipe(kotori.build(this.config))
.pipe(kotori.dest(this.currentOptions.output));
}
}
|
partner_industry_Secondary: Make api constrains multi to avoid error when create a company with 2 contacts | # Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
industry_id = fields.Many2one(string='Main Industry')
secondary_industry_ids = fields.Many2many(
comodel_name='res.partner.industry', string="Secondary Industries",
domain="[('id', '!=', industry_id)]")
@api.constrains('industry_id', 'secondary_industry_ids')
def _check_industries(self):
for partner in self:
if partner.industry_id in partner.secondary_industry_ids:
raise exceptions.ValidationError(
_('The main industry must be different '
'from the secondary industries.'))
| # Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
industry_id = fields.Many2one(string='Main Industry')
secondary_industry_ids = fields.Many2many(
comodel_name='res.partner.industry', string="Secondary Industries",
domain="[('id', '!=', industry_id)]")
@api.constrains('industry_id', 'secondary_industry_ids')
def _check_industries(self):
if self.industry_id in self.secondary_industry_ids:
raise exceptions.ValidationError(
_('The main industry must be different '
'from the secondary industries.'))
|
Remove PHP < 7.1.3 code | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Translation\Dumper;
use Symfony\Component\Translation\MessageCatalogue;
/**
* JsonFileDumper generates an json formatted string representation of a message catalogue.
*
* @author singles
*/
class JsonFileDumper extends FileDumper
{
/**
* {@inheritdoc}
*/
public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = array())
{
if (isset($options['json_encoding'])) {
$flags = $options['json_encoding'];
} else {
$flags = JSON_PRETTY_PRINT;
}
return json_encode($messages->all($domain), $flags);
}
/**
* {@inheritdoc}
*/
protected function getExtension()
{
return 'json';
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Translation\Dumper;
use Symfony\Component\Translation\MessageCatalogue;
/**
* JsonFileDumper generates an json formatted string representation of a message catalogue.
*
* @author singles
*/
class JsonFileDumper extends FileDumper
{
/**
* {@inheritdoc}
*/
public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = array())
{
if (isset($options['json_encoding'])) {
$flags = $options['json_encoding'];
} else {
$flags = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
}
return json_encode($messages->all($domain), $flags);
}
/**
* {@inheritdoc}
*/
protected function getExtension()
{
return 'json';
}
}
|
Add logging to server PUT | 'use strict';
var env = require('./env.json');
function httpPost(req, cb) {
var https = req.deps.https;
console.log('env:', env);
var postData = JSON.stringify({
metadata: req.data.s3Object.Metadata,
sizes: req.data.sizes
});
var options = {
hostname: 'plaaant.com',
port: 443,
path: '/api/image-complete?token=' + env.PLANT_IMAGE_COMPLETE,
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
console.log('About to PUT to server...');
var request = https.request(options, function() {});
request.write(postData);
request.end();
console.log('Completed PUT to server...');
cb(null, req);
}
module.exports = {
httpPost: httpPost
};
| 'use strict';
var env = require('./env.json');
function httpPost(req, cb) {
var https = req.deps.https;
console.log('env:', env);
var postData = JSON.stringify({
metadata: req.data.s3Object.Metadata,
sizes: req.data.sizes
});
var options = {
hostname: 'plaaant.com',
port: 443,
path: '/api/image-complete?token=' + env.PLANT_IMAGE_COMPLETE,
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
var request = https.request(options, function() {});
request.write(postData);
request.end();
cb();
}
module.exports = {
httpPost: httpPost
};
|
[native] Update default server URLs to use comm instead of squadcal
Summary: This fixes the `dev_environment.md` setup instructions.
Test Plan: Make sure that everything works on `http://localhost/comm/` after I update `server/facts/url.json` and `/private/etc/apache2/users/$USER.conf`
Reviewers: atul, subnub, palys-swm
Reviewed By: atul
Subscribers: KatPo, zrebcu411, Adrian
Differential Revision: https://phabricator.ashoat.com/D584 | // @flow
import invariant from 'invariant';
import { Platform } from 'react-native';
const productionServer = 'https://squadcal.org';
const localhostServer = 'http://localhost/comm';
const localhostServerFromAndroidEmulator = 'http://10.0.2.2/comm';
const natServer = 'http://192.168.1.4/comm';
function defaultURLPrefix() {
if (!__DEV__) {
return productionServer;
} else if (Platform.OS === 'android') {
// Uncomment below and update IP address if testing on physical device
//return natServer;
return localhostServerFromAndroidEmulator;
} else if (Platform.OS === 'ios') {
// Uncomment below and update IP address if testing on physical device
//return natServer;
return localhostServer;
} else {
invariant(false, 'unsupported platform');
}
}
const serverOptions = [productionServer];
if (Platform.OS === 'android') {
serverOptions.push(localhostServerFromAndroidEmulator);
} else {
serverOptions.push(localhostServer);
}
const setCustomServer = 'SET_CUSTOM_SERVER';
export { defaultURLPrefix, serverOptions, natServer, setCustomServer };
| // @flow
import invariant from 'invariant';
import { Platform } from 'react-native';
const productionServer = 'https://squadcal.org';
const localhostServer = 'http://localhost/squadcal';
const localhostServerFromAndroidEmulator = 'http://10.0.2.2/squadcal';
const natServer = 'http://192.168.1.4/squadcal';
function defaultURLPrefix() {
if (!__DEV__) {
return productionServer;
} else if (Platform.OS === 'android') {
// Uncomment below and update IP address if testing on physical device
//return natServer;
return localhostServerFromAndroidEmulator;
} else if (Platform.OS === 'ios') {
// Uncomment below and update IP address if testing on physical device
//return natServer;
return localhostServer;
} else {
invariant(false, 'unsupported platform');
}
}
const serverOptions = [productionServer];
if (Platform.OS === 'android') {
serverOptions.push(localhostServerFromAndroidEmulator);
} else {
serverOptions.push(localhostServer);
}
const setCustomServer = 'SET_CUSTOM_SERVER';
export { defaultURLPrefix, serverOptions, natServer, setCustomServer };
|
Change repeat command to return a list of the results of the repeated commands | import vx
from contextlib import contextmanager
from functools import partial
import sys
from io import StringIO
def _expose(f=None, name=None):
if f is None:
return partial(_expose, name=name)
if name is None:
name = f.__name__.lstrip('_')
if getattr(vx, name, None) is not None:
raise AttributeError("Cannot expose duplicate name: '{}'".format(name))
setattr(vx, name, f)
return f
vx.expose = _expose
@vx.expose
def _repeat(c, times=4):
res = []
for _ in range(times):
res.append(c())
return res
@vx.expose
@contextmanager
def _cursor_wander(command=None, window=None):
if window is None:
window = vx.window.focused_window
y, x = vx.get_linecol_window(window)
if command is not None:
command()
yp, xp = vx.get_linecol_window(window)
yield (yp, xp)
vx.set_linecol_window(window, y, x)
@contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
| import vx
from contextlib import contextmanager
from functools import partial
import sys
from io import StringIO
def _expose(f=None, name=None):
if f is None:
return partial(_expose, name=name)
if name is None:
name = f.__name__.lstrip('_')
if getattr(vx, name, None) is not None:
raise AttributeError("Cannot expose duplicate name: '{}'".format(name))
setattr(vx, name, f)
return f
vx.expose = _expose
@vx.expose
def _repeat(c, times=4):
for _ in range(times):
c()
@vx.expose
@contextmanager
def _cursor_wander(command=None, window=None):
if window is None:
window = vx.window.focused_window
y, x = vx.get_linecol_window(window)
if command is not None:
command()
yp, xp = vx.get_linecol_window(window)
yield (yp, xp)
vx.set_linecol_window(window, y, x)
@contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
|
Fix URL to be HTTPS.
random.org now redirects to HTTPS and we don't handle the redirect
correctly, but if we start on HTTPS there is no redirect. | //
// TrueRandom.java -- Java class TrueRandom
// Project OrcSites
//
// Copyright (c) 2009 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//
package orc.lib.net;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import orc.error.runtime.JavaException;
import orc.error.runtime.TokenException;
import orc.values.sites.compatibility.Args;
import orc.values.sites.compatibility.EvalSite;
public class TrueRandom extends EvalSite {
private static String baseURL = "https://www.random.org/integers/?num=1&col=1&base=10&format=plain&rnd=new";
@Override
public Object evaluate(final Args args) throws TokenException {
try {
final String number = HTTPUtils.getURL(new URL(baseURL + "&min=" + args.longArg(0) + "&max=" + (args.longArg(1) - 1)));
return new Long(number.trim());
} catch (final MalformedURLException e) {
throw new JavaException(e);
} catch (final IOException e) {
throw new JavaException(e);
}
}
}
| //
// TrueRandom.java -- Java class TrueRandom
// Project OrcSites
//
// Copyright (c) 2009 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//
package orc.lib.net;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import orc.error.runtime.JavaException;
import orc.error.runtime.TokenException;
import orc.values.sites.compatibility.Args;
import orc.values.sites.compatibility.EvalSite;
public class TrueRandom extends EvalSite {
private static String baseURL = "http://www.random.org/integers/?num=1&col=1&base=10&format=plain&rnd=new";
@Override
public Object evaluate(final Args args) throws TokenException {
try {
final String number = HTTPUtils.getURL(new URL(baseURL + "&min=" + args.longArg(0) + "&max=" + (args.longArg(1) - 1)));
return new Long(number.trim());
} catch (final MalformedURLException e) {
throw new JavaException(e);
} catch (final IOException e) {
throw new JavaException(e);
}
}
}
|
Fix loading of update transaction after changing tax rate | <?
include '../scat.php';
include '../lib/txn.php';
$txn_id= (int)$_REQUEST['txn'];
if (!$txn_id)
die_jsonp("no transaction specified.");
$txn= txn_load($db, $txn_id);
if ($txn['paid']) {
die_jsonp("This order is already paid!");
}
$tax_rate= (float)$_REQUEST['tax_rate'];
if (!strcmp($_REQUEST['tax_rate'], 'def')) {
$tax_rate= DEFAULT_TAX_RATE;
}
$q= "UPDATE txn SET tax_rate = $tax_rate WHERE id = $txn_id";
$r= $db->query($q)
or die_jsonp($db->error);
$txn= txn_load($db, $txn_id);
echo jsonp(array("success" => "Updated tax rate.", "txn" => $txn));
| <?
include '../scat.php';
include '../lib/txn.php';
$txn_id= (int)$_REQUEST['txn'];
if (!$txn_id)
die_jsonp("no transaction specified.");
$txn= txn_load($db, $txn_id);
if ($txn['paid']) {
die_jsonp("This order is already paid!");
}
$tax_rate= (float)$_REQUEST['tax_rate'];
if (!strcmp($_REQUEST['tax_rate'], 'def')) {
$tax_rate= DEFAULT_TAX_RATE;
}
$q= "UPDATE txn SET tax_rate = $tax_rate WHERE id = $txn_id";
$r= $db->query($q)
or die_jsonp($db->error);
$txn= txn_load($db, $txn);
echo jsonp(array("success" => "Updated tax rate.", "txn" => $txn));
|
Fix accepatble media types in controller | package de.digitalcollections.iiif.image.config;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* IIIF image API specific configuration.
*/
@Configuration
@ComponentScan(basePackages = {
"de.digitalcollections.iiif.image.frontend.impl.springmvc.controller"
})
@EnableWebMvc
public class SpringConfigFrontendImage extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// support for @ResponseBody of type String
final StringHttpMessageConverter stringHMC = new StringHttpMessageConverter(StandardCharsets.UTF_8);
// supported MediaTypes for stringHMC are by default set to: "text/plain" and MediaType.ALL
converters.add(stringHMC);
// support for @ResponseBody of type byte[]
ByteArrayHttpMessageConverter bc = new ByteArrayHttpMessageConverter();
List<MediaType> supported = new ArrayList<>();
supported.add(MediaType.ALL);
bc.setSupportedMediaTypes(supported);
converters.add(bc);
}
}
| package de.digitalcollections.iiif.image.config;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* IIIF image API specific configuration.
*/
@Configuration
@ComponentScan(basePackages = {
"de.digitalcollections.iiif.image.frontend.impl.springmvc.controller"
})
@EnableWebMvc
public class SpringConfigFrontendImage extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// support for @ResponseBody of type String
final StringHttpMessageConverter stringHMC = new StringHttpMessageConverter(StandardCharsets.UTF_8);
// supported MediaTypes for stringHMC are by default set to: "text/plain" and MediaType.ALL
converters.add(stringHMC);
// support for @ResponseBody of type byte[]
ByteArrayHttpMessageConverter bc = new ByteArrayHttpMessageConverter();
List<MediaType> supported = new ArrayList<>();
supported.add(MediaType.IMAGE_JPEG);
bc.setSupportedMediaTypes(supported);
converters.add(bc);
}
}
|
FIX populateModuleFixture to insert module objects correctly | import { Modules } from '../database-controller/module/module';
import { retrieveAllModule } from '../database-controller/module/methods';
export const populateModuleFixture = function populateModuleFixture() {
const moduleCodes = ['CS1010', 'CS1010E', 'CS1010J', 'CS1010S', 'CS1010X', 'CS1020', 'CS2010', 'CS3230'];
const moduleNames = ['Programming Methodology', 'Programming Methodology', 'Programming Methodology', 'Programming Methodology', 'Programming Methodology', 'Data Structures and Algorithms I', 'Data Structures and Algorithms II', 'Design and Analysis of Algorithms'];
for (var i = 0; i < 8; i++) {
const testModule = {
moduleCode: moduleCodes[i],
moduleName: moduleNames[i],
moduleDescription: 'Lorem ipsum',
modulePrerequisite: 'Lorem ipsum',
moduleCorequisite: 'Lorem ipsum',
modulePreclusion: 'Lorem ipsum',
moduleMC: 4,
termOffered: [{Sem1: 'Sem 1', Sem2: 'Sem 2'}]
};
Modules.insert(testModule);
}
return retrieveAllModule();
};
export const dePopulateModuleFixture = function dePopulateModuleFixture() {
const modules = retrieveAllModule();
for (var i = 0; i < modules.length; i++) {
Modules.remove({_id: modules[i]._id});
}
return retrieveAllModule();
}
| import { Modules } from '../database-controller/module/module';
import { createModuleCollection,
insertToModuleCollection,
removeOneModule,
retrieveAllModule} from '../database-controller/module/methods';
export const populateModuleFixture = function populateModuleFixture() {
const moduleCodes = ['CS1010', 'CS1010E', 'CS1010J', 'CS1010S', 'CS1010X', 'CS1020', 'CS2010', 'CS3230'];
const moduleNames = ['Programming Methodology', 'Programming Methodology', 'Programming Methodology', 'Programming Methodology', 'Programming Methodology', 'Data Structures and Algorithms I', 'Data Structures and Algorithms II', 'Design and Analysis of Algorithms'];
for (var i = 0; i < 8; i++) {
const testModule = {
moduleCode: moduleCodes[i],
moduleName: moduleNames[i],
moduleDescription: 'Lorem ipsum',
modulePrerequisite: 'Lorem ipsum',
moduleCorequisite: 'Lorem ipsum',
modulePreclusion: 'Lorem ipsum',
moduleMC: 4,
termOffered: {Sem1: 'Sem 1', Sem2: 'Sem 2'}
};
Modules.insert(testModule);
}
return retrieveAllModule();
};
export const dePopulateModuleFixture = function dePopulateModuleFixture() {
const modules = retrieveAllModule();
for (var i = 0; i < modules.length; i++) {
Modules.remove({_id: modules[i]._id});
}
return retrieveAllModule();
}
|
Update base user model for inheritence. | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model
var User = new keystone.List('User', {
track: true,
autokey: { path: 'key', from: 'email', unique: true },
map: { name: 'email' },
defaultSort: 'email'
});
// Create fields
User.add('Permissions', {
permissions: {
isVerified: { type: Boolean, label: 'has a verified email address', default: false, noedit: true },
isActive: { type: Boolean, label: 'is active', default: true, noedit: true }
}
}, 'General Information', {
email: { type: Types.Email, label: 'email address', unique: true, required: true, index: true, initial: true },
password: { type: Types.Password, label: 'password', required: true, initial: true }
});
// Define default columns in the admin interface and register the model
User.defaultColumns = 'email, permissions.isActive, permissions.isVerified';
User.register(); | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model
var User = new keystone.List('User', {
track: true,
autokey: { path: 'key', from: 'email', unique: true },
map: { name: 'email' },
defaultSort: 'email'
});
// Create fields
User.add('Permissions', {
permissions: {
isVerified: { type: Boolean, label: 'has a verified email address', default: false, noedit: true },
isActive: { type: Boolean, label: 'is active', default: true, noedit: true }
}
}, 'General Information', {
email: { type: Types.Email, label: 'email address', unique: true, required: true, index: true, initial: true },
password: { type: Types.Password, label: 'password', required: true, initial: true }
});
/* TODO: VERY IMPORTANT: Need to fix this to provide the link to access the keystone admin panel again */
/* Changing names or reworking this file changed the check in node_modules/keystone/templates/views/signin.jade
/* for user.isAdmin on line 14 */
// Provide access to Keystone
User.schema.virtual('canAccessKeystone').get(function() {
'use strict';
return true;
});
// Define default columns in the admin interface and register the model
User.defaultColumns = 'name.full, email, isActive, isVerified';
User.register(); |
KCIAC-332: Implement COI event type of "IACUC Protocol" | /*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.iacuc.personnel;
import org.kuali.kra.iacuc.IacucProtocol;
import org.kuali.kra.protocol.personnel.ProtocolPerson;
public class IacucProtocolPerson extends ProtocolPerson {
private static final long serialVersionUID = 6676849646094141708L;
public IacucProtocol getIacucProtocol() {
return (IacucProtocol) getProtocol();
}
}
| /*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.iacuc.personnel;
import org.kuali.kra.protocol.personnel.ProtocolPerson;
public class IacucProtocolPerson extends ProtocolPerson {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 6676849646094141708L;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.