text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use data attribute instead of val()
|
var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = 'base_load'
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).val(technology);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
$(this).val(actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
|
var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).val());
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = 'base_load'
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).val(technology);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
$(this).val(actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
|
Fix JS test causing navigation away from tests
|
module("Double click protection", {
setup: function(){
this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>');
$('#qunit-fixture').append(this.$form);
}
});
test('clicking submit input disables the button', function() {
GOVUK.doubleClickProtection();
var $submit_tag = this.$form.find('input[type=submit]');
ok(!$submit_tag.prop('disabled'));
this.$form.on('submit', function (e) {
e.preventDefault();
ok($submit_tag.prop('disabled'));
});
$submit_tag.click();
});
test('clicking submit input creates a hidden input with the same name and value', function() {
GOVUK.doubleClickProtection();
var $submit_tag = this.$form.find('input[type=submit]');
this.$form.on('submit', function (e) {
e.preventDefault();
equal($.find('form input[type=hidden][name=input_name][value=Save]').length, 1);
});
$submit_tag.click();
});
|
module("Double click protection", {
setup: function(){
this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>');
$('#qunit-fixture').append(this.$form);
}
});
test('clicking submit input disables the button', function() {
GOVUK.doubleClickProtection();
var $submit_tag = this.$form.find('input[type=submit]');
ok(!$submit_tag.prop('disabled'));
$submit_tag.on('click', function (e) {
e.preventDefault();
ok($submit_tag.prop('disabled'));
});
$submit_tag.click();
});
test('clicking submit input creates a hidden input with the same name and value', function() {
GOVUK.doubleClickProtection();
var $submit_tag = this.$form.find('input[type=submit]');
$submit_tag.on('click', function (e) {
e.preventDefault();
equal($.find('form input[type=hidden][name=input_name][value=Save]').length, 1);
});
$submit_tag.click();
});
|
Fix eslint config for v8
|
const path = require('path')
module.exports = {
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
],
overrides: [
{
files: ['*.js'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
},
},
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
project: path.join(__dirname, 'tsconfig.eslint.json'),
sourceType: 'module',
},
plugins: ['react', 'react-hooks', '@typescript-eslint', 'simple-import-sort'],
root: true,
rules: {
'@typescript-eslint/explicit-module-boundary-types': 'off',
'react-hooks/exhaustive-deps': 'warn',
'react-hooks/rules-of-hooks': 'error',
'react/jsx-sort-props': 'error',
'react/jsx-uses-react': 'off',
'react/react-in-jsx-scope': 'off',
'simple-import-sort/exports': 'error',
'simple-import-sort/imports': 'error',
'sort-imports': 'off',
'sort-keys': 'error',
},
settings: {
react: {
version: 'detect',
},
},
}
|
const path = require('path')
module.exports = {
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
overrides: [
{
files: ['*.js'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
},
},
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
project: path.join(__dirname, 'tsconfig.eslint.json'),
sourceType: 'module',
},
plugins: ['react', 'react-hooks', '@typescript-eslint', 'simple-import-sort'],
root: true,
rules: {
'@typescript-eslint/explicit-module-boundary-types': 'off',
'react-hooks/exhaustive-deps': 'warn',
'react-hooks/rules-of-hooks': 'error',
'react/jsx-sort-props': 'error',
'react/jsx-uses-react': 'off',
'react/react-in-jsx-scope': 'off',
'simple-import-sort/exports': 'error',
'simple-import-sort/imports': 'error',
'sort-imports': 'off',
'sort-keys': 'error',
},
settings: {
react: {
version: 'detect',
},
},
}
|
Truncate filename if it exceeds 50 characters
|
package com.thinksincode.tailstreamer.controller;
import com.thinksincode.tailstreamer.FileTailService;
import com.thinksincode.tailstreamer.TailStreamer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
/** The maximum filename length before truncation occurs. */
private static final int MAX_FILENAME_LENGTH = 50;
@Autowired
private FileTailService fileTailService;
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("file", maybeTruncate(fileTailService.getFileName()));
model.addAttribute("filePath", fileTailService.getFilePath());
model.addAttribute("version", TailStreamer.VERSION);
return "index";
}
private String maybeTruncate(String fileName) {
if (fileName.length() <= MAX_FILENAME_LENGTH) {
return fileName;
} else {
String extension = fileName.substring(fileName.lastIndexOf('.'));
return fileName.substring(0, MAX_FILENAME_LENGTH) + "..." + fileName.substring(fileName.length() - extension.length() - 1);
}
}
}
|
package com.thinksincode.tailstreamer.controller;
import com.thinksincode.tailstreamer.FileTailService;
import com.thinksincode.tailstreamer.TailStreamer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
@Autowired
private FileTailService fileTailService;
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("file", fileTailService.getFileName());
model.addAttribute("filePath", fileTailService.getFilePath());
model.addAttribute("version", TailStreamer.VERSION);
return "index";
}
}
|
Add url to check for incoming sms's.
|
# BULKSMS Configuration.
# BULKSMS base url.
BULKSMS_BASE_API_URL = 'https://bulksms.2way.co.za'
# Credentials required to use bulksms.com API.
BULKSMS_AUTH_USERNAME = ''
BULKSMS_AUTH_PASSWORD = ''
# URL for sending single and batch sms.
BULKSMS_API_URL = {
'batch': '/{}eapi/submission/send_batch/1/1.0'.format(BULKSMS_BASE_API_URL), # sends batch SMS's.
'single': '/{}eapi/submission/send_sms/2/2.0'.format(BULKSMS_BASE_API_URL), # sends single SMS.
'credits': '/{}user/get_credits/1/1.1'.format(BULKSMS_BASE_API_URL) # SMS credits balance.
'inbox': '/{}reception/get_inbox/1/1.1'.format(BULKSMS_BASE_API_URL) # get inbox.
}
# Whether to automatically insert country codes before sending sms.
CLEAN_MSISDN_NUMBER = False
|
# BULKSMS Configuration.
# BULKSMS base url.
BULKSMS_BASE_API_URL = 'https://bulksms.2way.co.za'
# Credentials required to use bulksms.com API.
BULKSMS_AUTH_USERNAME = ''
BULKSMS_AUTH_PASSWORD = ''
# URL for sending single and batch sms.
BULKSMS_API_URL = {
'batch': '/{}eapi/submission/send_batch/1/1.0'.format(BULKSMS_BASE_API_URL), # sends batch SMS's.
'single': '/{}eapi/submission/send_sms/2/2.0'.format(BULKSMS_BASE_API_URL), # sends single SMS.
'credits': '/{}user/get_credits/1/1.1'.format(BULKSMS_BASE_API_URL) # SMS credits balance.
}
# Whether to automatically insert country codes before sending sms.
CLEAN_MSISDN_NUMBER = False
|
Use a separate lock per ivorn database
|
# VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lock)
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.locks[db_path].acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.locks[db_path].release()
|
# VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root):
self.root = root
self.lock = Lock()
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.lock.acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.lock.release()
|
Add support for beforeEach / afterEach to ember-dev assertions.
|
/* globals QUnit */
export default function setupQUnit(assertion, _qunitGlobal) {
var qunitGlobal = QUnit;
if (_qunitGlobal) {
qunitGlobal = _qunitGlobal;
}
var originalModule = qunitGlobal.module;
qunitGlobal.module = function(name, _options) {
var options = _options || {};
var originalSetup = options.setup || options.beforeEach || function() { };
var originalTeardown = options.teardown || options.afterEach || function() { };
delete options.setup;
delete options.teardown;
options.beforeEach = function() {
assertion.reset();
assertion.inject();
return originalSetup.apply(this, arguments);
};
options.afterEach = function() {
let result = originalTeardown.apply(this, arguments);
assertion.assert();
assertion.restore();
return result;
};
return originalModule(name, options);
};
}
|
/* globals QUnit */
export default function setupQUnit(assertion, _qunitGlobal) {
var qunitGlobal = QUnit;
if (_qunitGlobal) {
qunitGlobal = _qunitGlobal;
}
var originalModule = qunitGlobal.module;
qunitGlobal.module = function(name, _options) {
var options = _options || {};
var originalSetup = options.setup || function() { };
var originalTeardown = options.teardown || function() { };
options.setup = function() {
assertion.reset();
assertion.inject();
return originalSetup.apply(this, arguments);
};
options.teardown = function() {
let result = originalTeardown.apply(this, arguments);
assertion.assert();
assertion.restore();
return result;
};
return originalModule(name, options);
};
}
|
Check if the x-frame-options header is already set
|
<?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;
class Response extends \Symfony\Component\HttpFoundation\Response {
public function send() {
$cleared = Cookie::getClearedCookies();
foreach($cleared as $cookie) {
$this->headers->clearCookie($cookie);
}
$cookies = Cookie::getCookies();
foreach($cookies as $cookie) {
$this->headers->setCookie($cookie);
}
if ($this->headers->has('X-Frame-Options') === false) {
$x_frame_options = Config::get('concrete.security.misc.x_frame_options');
if (Core::make('helper/validation/strings')->notempty($x_frame_options)) {
$this->headers->set('X-Frame-Options', $x_frame_options);
}
}
parent::send();
}
}
|
<?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;
class Response extends \Symfony\Component\HttpFoundation\Response {
public function send() {
$cleared = Cookie::getClearedCookies();
foreach($cleared as $cookie) {
$this->headers->clearCookie($cookie);
}
$cookies = Cookie::getCookies();
foreach($cookies as $cookie) {
$this->headers->setCookie($cookie);
}
$x_frame_options = Config::get('concrete.security.misc.x_frame_options');
if (Core::make('helper/validation/strings')->notempty($x_frame_options)) {
$this->headers->set('X-Frame-Options', $x_frame_options);
}
parent::send();
}
}
|
Update failure key in test
Signed-off-by: Zane Burstein <0b53c6e52ca2d19caefaa4da7d81393843bcf79a@anchore.com>
|
class TestOversizedImageReturns400:
# Expectation for this test is that the image with tag is greater than the value defined in config
def test_oversized_image_post(self, make_image_analysis_request):
resp = make_image_analysis_request("anchore/test_images:oversized_image")
details = resp.body["detail"]
msg = resp.body["message"]
assert resp.code == 400
assert (
msg
== "Image size is too large based on max size specified in the configuration"
)
assert (
details["requested_image_compressed_size_bytes"]
> details["max_compressed_image_size_mb"]
)
class TestValidImageReturns200:
def test_valid_image_returns_200(self, make_image_analysis_request):
resp = make_image_analysis_request("alpine:latest")
assert resp.code == 200
|
class TestOversizedImageReturns400:
# Expectation for this test is that the image with tag is greater than the value defined in config
def test_oversized_image_post(self, make_image_analysis_request):
resp = make_image_analysis_request("anchore/test_images:oversized_image")
details = resp.body["detail"]
msg = resp.body["message"]
assert resp.code == 400
assert (
msg
== "Image size is too large based on max size specified in the configuration"
)
assert (
details["requested_image_compressed_size"]
> details["max_compressed_image_size_mb"]
)
class TestValidImageReturns200:
def test_valid_image_returns_200(self, make_image_analysis_request):
resp = make_image_analysis_request("alpine:latest")
assert resp.code == 200
|
Update EEA Form Build Info Comments/Source
|
'use strict';
app.component("eeaFormBuild", {
template: '<div style="line-height: 10px;color: #f0f0f0;">Build date: {{$ctrl.date}}<br>{{$ctrl.diff}} ago<br>by {{$ctrl.user}}</div>',
bindings: {
date: '@',
user: '@'
},
controller: function() {
this.$onInit = function() {
// https://stackoverflow.com/questions/38714578/countdown-timer-with-progressbar
var delta = Math.abs(new Date().getTime() - new Date(this.date).getTime()) / 1000;
var days = Math.floor(delta / 86400);
delta -= days * 86400;
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
var seconds = Math.floor(delta % 60);
this.diff = days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " sec.";
};
}
});
|
'use strict';
app.component("eeaFormBuild", {
template: '<div style="line-height: 10px;color: #f0f0f0;">Build date: {{$ctrl.date}}<br>{{$ctrl.diff}} ago<br>by {{$ctrl.user}}</div>',
bindings: {
date: '@',
user: '@'
},
controller: function() {
this.$onInit = function() {
var delta = Math.abs(new Date().getTime() - new Date(this.date).getTime()) / 1000;
var days = Math.floor(delta / 86400);
delta -= days * 86400;
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
var seconds = Math.floor(delta % 60);
this.diff = days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " sec.";
};
}
});
|
Make video card a link
|
import * as _ from 'lodash'
import React from 'react'
import {connect} from 'react-redux'
import {Link} from 'react-router-dom'
import {compose} from 'recompose'
import {refreshVideo} from '../../actions/videos'
import {withDatabaseSubscribe} from '../hocs'
const mapStateToProps = ({videos}) => ({
videos
})
const enhance = compose(
connect(mapStateToProps),
withDatabaseSubscribe(
'value',
(props) => (`videos/${props.videoId}`),
(props) => (snapshot) => (
props.dispatch(refreshVideo(
{
videoId: props.videoId,
videoSnapshot: snapshot.val()
})
)
)
)
)
const VideoPreviewCard = ({videoId, videos}) => (
<div>
<Link to={`/videos/${videoId}`}>
{JSON.stringify(_.get(videos, videoId, {}))}
</Link>
</div>
)
export default enhance(VideoPreviewCard)
|
import * as _ from 'lodash'
import React from 'react'
import {connect} from 'react-redux'
import {compose} from 'recompose'
import {withDatabaseSubscribe} from '../hocs'
import {refreshVideo} from '../../actions/videos'
const mapStateToProps = ({videos}) => ({
videos
})
const enhance = compose(
connect(mapStateToProps),
withDatabaseSubscribe(
'value',
(props) => (`videos/${props.videoId}`),
(props) => (snapshot) => (
props.dispatch(refreshVideo(
{
videoId: props.videoId,
videoSnapshot: snapshot.val()
})
)
)
)
)
const VideoPreviewCard = ({videoId, videos}) => (
<div>
{JSON.stringify(_.get(videos, videoId, {}))}
</div>
)
export default enhance(VideoPreviewCard)
|
Update to not include test packages.
|
from setuptools import setup
import os
def read(fn):
"""
Read the contents of the provided filename.
Args:
fn: The filename to read in.
Returns:
The contents of the file.
"""
abs_fn = os.path.join(os.path.dirname(__file__), fn)
f = open(abs_fn)
contents = f.read()
f.close()
return contents
setup(
name = 'pyconll',
packages = ['pyconll', 'pyconll.unit'],
version = '1.0',
description = 'Read and maniuplate CoNLL files',
long_description = read('README.rst'),
author = 'Matias Grioni',
author_email = 'matgrioni@gmail.com',
url = 'https://github.com/pyconll/pyconll',
license = 'MIT',
keywords = ['nlp', 'conllu', 'conll', 'universal dependencies'],
install_requires =[
'requests >= 2.19'
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Scientific/Engineering',
'Topic :: Utilities'
]
)
|
from setuptools import setup, find_packages
import os
def read(fn):
"""
Read the contents of the provided filename.
Args:
fn: The filename to read in.
Returns:
The contents of the file.
"""
abs_fn = os.path.join(os.path.dirname(__file__), fn)
f = open(abs_fn)
contents = f.read()
f.close()
return contents
setup(
name = 'pyconll',
packages = find_packages(),
version = '1.0',
description = 'Read and maniuplate CoNLL files',
long_description = read('README.rst'),
author = 'Matias Grioni',
author_email = 'matgrioni@gmail.com',
url = 'https://github.com/pyconll/pyconll',
license = 'MIT',
keywords = ['nlp', 'conllu', 'conll', 'universal dependencies'],
install_requires =[
'requests >= 2.19'
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Scientific/Engineering',
'Topic :: Utilities'
]
)
|
Switch to current year's database URL
|
package be.digitalia.fosdem.api;
import java.util.Locale;
/**
* This class contains all FOSDEM Urls
*
* @author Christophe Beyls
*
*/
public class FosdemUrls {
private static final String SCHEDULE_URL = "https://fosdem.org/schedule/xml";
private static final String EVENT_URL_FORMAT = "https://fosdem.org/%1$d/schedule/event/%2$s/";
private static final String PERSON_URL_FORMAT = "https://fosdem.org/%1$d/schedule/speaker/%2$s/";
public static String getSchedule() {
return SCHEDULE_URL;
}
public static String getEvent(String slug, int year) {
return String.format(Locale.US, EVENT_URL_FORMAT, year, slug);
}
public static String getPerson(String slug, int year) {
return String.format(Locale.US, PERSON_URL_FORMAT, year, slug);
}
}
|
package be.digitalia.fosdem.api;
import java.util.Locale;
/**
* This class contains all FOSDEM Urls
*
* @author Christophe Beyls
*
*/
public class FosdemUrls {
// private static final String SCHEDULE_URL = "https://fosdem.org/schedule/xml";
private static final String SCHEDULE_URL = "https://archive.fosdem.org/2013/schedule/xml";
private static final String EVENT_URL_FORMAT = "https://fosdem.org/%1$d/schedule/event/%2$s/";
private static final String PERSON_URL_FORMAT = "https://fosdem.org/%1$d/schedule/speaker/%2$s/";
public static String getSchedule() {
return SCHEDULE_URL;
}
public static String getEvent(String slug, int year) {
return String.format(Locale.US, EVENT_URL_FORMAT, year, slug);
}
public static String getPerson(String slug, int year) {
return String.format(Locale.US, PERSON_URL_FORMAT, year, slug);
}
}
|
Remove unused name in Statistics constructor.
|
'use strict';
const Stats = require('fast-stats').Stats;
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else if (percentile === 50) {
return 'median';
}
return `p${String(percentile).replace('.', '_')}`;
}
class Statistics {
constructor() {
this.stats = new Stats();
}
add(value) {
this.stats.push(value);
}
summarize(options) {
options = options || {};
const percentiles = options.percentiles || [0, 10, 50, 90, 99, 100];
const decimals = options.decimals || 0;
const data = {};
const self = this;
percentiles.forEach(p => {
const name = percentileName(p);
data[name] = self.stats.percentile(p).toFixed(decimals);
});
return data;
}
}
module.exports = {
Statistics,
};
|
'use strict';
const Stats = require('fast-stats').Stats;
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else if (percentile === 50) {
return 'median';
}
return `p${String(percentile).replace('.', '_')}`;
}
class Statistics {
constructor(name) {
this.name = name;
this.stats = new Stats();
}
add(value) {
this.stats.push(value);
}
summarize(options) {
options = options || {};
const percentiles = options.percentiles || [0, 10, 50, 90, 99, 100];
const decimals = options.decimals || 0;
const data = {};
const self = this;
percentiles.forEach(p => {
const name = percentileName(p);
data[name] = self.stats.percentile(p).toFixed(decimals);
});
return data;
}
}
module.exports = {
Statistics,
};
|
Update dependency to Markdown 2.6+ & bleach 2.0.0+
|
import os.path as path
from setuptools import setup
def get_readme(filename):
if not path.exists(filename):
return ""
with open(path.join(path.dirname(__file__), filename)) as readme:
content = readme.read()
return content
setup(name="mdx_linkify",
version="0.6",
author="Raitis (daGrevis) Stengrevics",
author_email="dagrevis@gmail.com",
description="Link recognition for Python Markdown",
license="MIT",
keywords="markdown links",
url="https://github.com/daGrevis/mdx_linkify",
packages=["mdx_linkify"],
long_description=get_readme("README.md"),
classifiers=[
"Topic :: Text Processing :: Markup",
"Topic :: Utilities",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: Implementation :: PyPy",
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
],
install_requires=["Markdown>=2.6", "bleach>=2.0.0"],
test_suite="mdx_linkify.tests")
|
import os.path as path
from setuptools import setup
def get_readme(filename):
if not path.exists(filename):
return ""
with open(path.join(path.dirname(__file__), filename)) as readme:
content = readme.read()
return content
setup(name="mdx_linkify",
version="0.6",
author="Raitis (daGrevis) Stengrevics",
author_email="dagrevis@gmail.com",
description="Link recognition for Python Markdown",
license="MIT",
keywords="markdown links",
url="https://github.com/daGrevis/mdx_linkify",
packages=["mdx_linkify"],
long_description=get_readme("README.md"),
classifiers=[
"Topic :: Text Processing :: Markup",
"Topic :: Utilities",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: Implementation :: PyPy",
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
],
install_requires=["Markdown>=2.5", "bleach>=1.4"],
test_suite="mdx_linkify.tests")
|
[TASK] Add TYPO3 CMS 8 as compatible version
|
<?php
/************************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
************************************************************************/
$EM_CONF[$_EXTKEY] = array(
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'constraints' => array(
'depends' => array(
'typo3' => '7.6.2-8.99.99'
),
'conflicts' => array(
'css_styled_content' => '*',
'fluid_styled_content' => '*',
'themes' => '*',
'fluidpages' => '*',
'dyncss' => '*',
),
),
'autoload' => array(
'psr-4' => array(
'BK2K\\BootstrapPackage\\' => 'Classes'
),
),
'state' => 'stable',
'uploadfolder' => 0,
'createDirs' => '',
'clearCacheOnLoad' => 1,
'author' => 'Benjamin Kott',
'author_email' => 'info@bk2k.info',
'author_company' => 'private',
'version' => '7.0.0-dev',
);
|
<?php
/************************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
************************************************************************/
$EM_CONF[$_EXTKEY] = array(
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'constraints' => array(
'depends' => array(
'typo3' => '7.6.0-7.99.99'
),
'conflicts' => array(
'css_styled_content' => '*',
'fluid_styled_content' => '*',
'themes' => '*',
'fluidpages' => '*',
'dyncss' => '*',
),
),
'autoload' => array(
'psr-4' => array(
'BK2K\\BootstrapPackage\\' => 'Classes'
),
),
'state' => 'stable',
'uploadfolder' => 0,
'createDirs' => '',
'clearCacheOnLoad' => 1,
'author' => 'Benjamin Kott',
'author_email' => 'info@bk2k.info',
'author_company' => 'private',
'version' => '7.0.0-dev',
);
|
Revert "Req-52 Alignment of file names in traceability matrix is "right-aligned""
This reverts commit 9bada791cfc5b699feaf0132ea1f302a9e006314.
|
package de.fau.osr.gui;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.table.JTableHeader;
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
RowHeaderRenderer(JTable table) {
JTableHeader header = table.getTableHeader();
setOpaque(true);
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
setHorizontalAlignment(RIGHT);
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
header.setResizingAllowed(true);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setText((value == null) ? "" : value.toString());
return this;
}
}
|
package de.fau.osr.gui;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.table.JTableHeader;
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
RowHeaderRenderer(JTable table) {
JTableHeader header = table.getTableHeader();
setOpaque(true);
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
setHorizontalAlignment(LEFT);
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
header.setResizingAllowed(true);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setText((value == null) ? "" : value.toString());
return this;
}
}
|
Use config to build paths
|
/**
* Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
* Sources at https://github.com/Memba
*/
/* jshint node: true, expr: true */
/* globals describe: false, before: false, it: false */
'use strict';
var request = require('supertest'),
//We cannot define app like this because the server is already running
//app = request('../../../webapp/server');
config = require('../../../webapp/config'),
app = config.get('uris:webapp:root');
describe('routes/homeRoute', function() {
it('it should return the home page', function(done) {
request(app)
.get(config.get('uris:webapp:home'))
.expect(200)
.expect('Content-Type', /html/)
.end(done);
});
});
|
/**
* Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
* Sources at https://github.com/Memba
*/
/* jshint node: true, expr: true */
/* globals describe: false, before: false, it: false */
'use strict';
var request = require('supertest'),
//We cannot define app like this because the server is already running
//app = request('../../../webapp/server');
config = require('../../../webapp/config'),
app = config.get('uris:webapp:root');
describe('routes/homeRoute', function() {
it('it should return the home page', function(done) {
request(app)
.get('/')
.expect(200)
.expect('Content-Type', /html/)
.end(done);
});
});
|
Fix build with new sass-loader
|
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
test: /\.s?css$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
},
},
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: ['app/javascript'],
},
implementation: require('sass'),
sourceMap: true,
},
},
],
};
|
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
test: /\.s?css$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
},
},
{
loader: 'sass-loader',
options: {
includePaths: ['app/javascript'],
implementation: require('sass'),
sourceMap: true,
},
},
],
};
|
Rename variable name from "val" to "node".
|
# coding: utf-8
"""
Exposes a class that represents a parsed (or compiled) template.
"""
class ParsedTemplate(object):
"""
Represents a parsed or compiled template.
An instance wraps a list of unicode strings and node objects. A node
object must have a `render(engine, stack)` method that accepts a
RenderEngine instance and a ContextStack instance and returns a unicode
string.
"""
def __init__(self):
self._parse_tree = []
def __repr__(self):
return repr(self._parse_tree)
def add(self, node):
"""
Arguments:
node: a unicode string or node object instance. See the class
docstring for information.
"""
self._parse_tree.append(node)
def render(self, engine, context):
"""
Returns: a string of type unicode.
"""
# We avoid use of the ternary operator for Python 2.4 support.
def get_unicode(node):
if type(node) is unicode:
return node
return node.render(engine, context)
parts = map(get_unicode, self._parse_tree)
s = ''.join(parts)
return unicode(s)
|
# coding: utf-8
"""
Exposes a class that represents a parsed (or compiled) template.
"""
class ParsedTemplate(object):
"""
Represents a parsed or compiled template.
An instance wraps a list of unicode strings and node objects. A node
object must have a `render(engine, stack)` method that accepts a
RenderEngine instance and a ContextStack instance and returns a unicode
string.
"""
def __init__(self):
self._parse_tree = []
def __repr__(self):
return repr(self._parse_tree)
def add(self, node):
"""
Arguments:
node: a unicode string or node object instance. See the class
docstring for information.
"""
self._parse_tree.append(node)
def render(self, engine, context):
"""
Returns: a string of type unicode.
"""
# We avoid use of the ternary operator for Python 2.4 support.
def get_unicode(val):
if type(val) is unicode:
return val
return val.render(engine, context)
parts = map(get_unicode, self._parse_tree)
s = ''.join(parts)
return unicode(s)
|
Use version of slots admin already in production
While building the schedule for the conference, the admin view for
`schedule.models.Slot` was changed in production* to figure out what
implementation made the most sense. This formalizes it as the preferred
version.
Closes #111
*Don't do this at home.
|
"""Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
column_default_sort='start',
column_filters=('day',),
column_list=(
'day', 'rooms', 'kind', 'start', 'end', 'presentation',
'content_override',
),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
|
"""Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
column_default_sort='start',
column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
|
Fix cache tests to account for callback style.
Were built with a return value in mind
|
var Memory = require('../lib/cache').Memory
, assert = require('assert')
;
describe('cache', function(){
var cache = new Memory();
before(function(){
})
describe('#get/#set', function(){
it('should set a value', function(){
cache.set('foo', 'bar', function(){
cache.get('foo', function(err, value ){
assert.equal(value, 'bar' )
})
});
})
it('should expire keys', function( done ){
cache.setMeta({timeout:0.5});
cache.set('bar','baz')
cache.get('bar', function( err, value){
assert.equal( value, 'baz')
})
setTimeout( function(){
cache.get('bar', function(err, value){
assert.notEqual(value, 'baz')
done();
})
},1000)
})
it('should defaine control property function', function(){
assert.equal( cache.control.no_cache, true )
cache.setMeta({control:{no_cache:false}});
assert.equal( cache.control.no_cache, false)
})
})
})
|
var Memory = require('../lib/cache').Memory
, assert = require('assert')
;
describe('cache', function(){
var cache = new Memory();
before(function(){
})
describe('#get/#set', function(){
it('should set a value', function(){
cache.set('foo', 'bar' );
assert.equal( cache.get('foo'), 'bar')
})
it('should expire keys', function( done ){
cache.setMeta({timeout:0.5});
cache.set('bar','baz')
assert.equal( cache.get('bar'), 'baz')
setTimeout( function(){
assert.notEqual( cache.get('bar'), 'baz')
done();
},1000)
})
it('should defaine control property function', function(){
assert.equal( cache.control.no_cache, true )
cache.setMeta({control:{no_cache:false}});
assert.equal( cache.control.no_cache, false)
})
})
})
|
Check if function exists before adding
|
package main
import (
"archive/zip"
"bytes"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
)
var runtimeFunction = `
exports.handler = function(event, context) {
eval(event.source);
};
`
func install(role string, region string) {
svc := lambda.New(&aws.Config{Region: region})
if functionExists(svc) {
println("Function already exits")
} else {
createFunction(svc, role)
}
}
func functionExists(svc *lambda.Lambda) bool {
params := &lambda.GetFunctionInput{
FunctionName: aws.String(FunctionName),
}
_, err := svc.GetFunction(params)
return err == nil
}
func createFunction(svc *lambda.Lambda, role string) {
params := &lambda.CreateFunctionInput{
Code: &lambda.FunctionCode{
ZipFile: zipRuntime(),
},
FunctionName: aws.String(FunctionName),
Handler: aws.String("index.handler"),
Runtime: aws.String("nodejs"),
Role: aws.String(role),
}
_, err := svc.CreateFunction(params)
if err != nil {
panic(err)
}
}
func zipRuntime() []byte {
buf := bytes.NewBuffer(nil)
arch := zip.NewWriter(buf)
fwriter, _ := arch.Create("index.js")
fwriter.Write([]byte(runtimeFunction))
arch.Close()
return buf.Bytes()
}
|
package main
import (
"archive/zip"
"bytes"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
)
var runtimeFunction = `
exports.handler = function(event, context) {
eval(event.source);
};
`
func install(role string, region string) {
svc := lambda.New(&aws.Config{Region: region})
params := &lambda.CreateFunctionInput{
Code: &lambda.FunctionCode{
ZipFile: zipRuntime(),
},
FunctionName: aws.String(FunctionName),
Handler: aws.String("index.handler"),
Runtime: aws.String("nodejs"),
Role: aws.String(role),
}
_, err := svc.CreateFunction(params)
if err != nil {
panic(err)
}
}
func zipRuntime() []byte {
buf := bytes.NewBuffer(nil)
arch := zip.NewWriter(buf)
fwriter, _ := arch.Create("index.js")
fwriter.Write([]byte(runtimeFunction))
arch.Close()
return buf.Bytes()
}
|
Add subprocess32 as package dependency
|
from setuptools import setup, find_packages
setup(
name='pycalico',
# Don't need a version until we publish to PIP or other forum.
# version='0.0.0',
description='A Python API to Calico',
# The project's main homepage.
url='https://github.com/projectcalico/libcalico/',
# Author details
author='Project Calico',
author_email='calico-tech@lists.projectcalico.org',
# Choose your license
license='Apache 2.0',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Networking',
],
# What does your project relate to?
keywords='calico docker etcd mesos kubernetes rkt openstack',
package_dir={"": "calico_containers"},
packages=["pycalico"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['netaddr', 'python-etcd', 'subprocess32'],
)
|
from setuptools import setup, find_packages
setup(
name='pycalico',
# Don't need a version until we publish to PIP or other forum.
# version='0.0.0',
description='A Python API to Calico',
# The project's main homepage.
url='https://github.com/projectcalico/libcalico/',
# Author details
author='Project Calico',
author_email='calico-tech@lists.projectcalico.org',
# Choose your license
license='Apache 2.0',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Networking',
],
# What does your project relate to?
keywords='calico docker etcd mesos kubernetes rkt openstack',
package_dir={"": "calico_containers"},
packages=["pycalico"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['netaddr', 'python-etcd'],
)
|
Fix null error when there's no data
|
<?php
namespace App\Http\Controllers;
use App\Services\Ranking;
use App\Services\Slack;
use App\SlackProp;
use App\SlackUser;
class DashboardController extends Controller
{
public function index()
{
$ranking = Ranking::getRanking();
$props = SlackProp::query()->orderBy('created_at', 'DESC')->take(5)->get();
return view('welcome', compact('ranking', 'props'));
}
public function userDetail($username)
{
$user = SlackUser::find($username);
return view('users.view', compact('user'));
}
public function slack()
{
$newestBeforeUpdate = $this->getDateOfLatestProp();
Slack::importProps();
$newestAfterUpdate = $this->getDateOfLatestProp();
if ($newestBeforeUpdate != null && $newestAfterUpdate->gt($newestBeforeUpdate)) {
Slack::sendRanking();
}
return redirect()->back();
}
public function getDateOfLatestProp()
{
return SlackProp::query()->orderBy('created_at', 'DESC')->value('created_at');
}
}
|
<?php
namespace App\Http\Controllers;
use App\Services\Ranking;
use App\Services\Slack;
use App\SlackProp;
use App\SlackUser;
class DashboardController extends Controller
{
public function index()
{
$ranking = Ranking::getRanking();
$props = SlackProp::query()->orderBy('created_at', 'DESC')->take(5)->get();
return view('welcome', compact('ranking', 'props'));
}
public function userDetail($username)
{
$user = SlackUser::find($username);
return view('users.view', compact('user'));
}
public function slack()
{
$newestBeforeUpdate = $this->getDateOfLatestProp();
Slack::importProps();
$newestAfterUpdate = $this->getDateOfLatestProp();
if ($newestAfterUpdate->gt($newestBeforeUpdate)) {
Slack::sendRanking();
}
return redirect()->back();
}
public function getDateOfLatestProp()
{
return SlackProp::query()->orderBy('created_at', 'DESC')->value('created_at');
}
}
|
Use root element instead of global in CSS
|
// ==UserScript==
// @name Firefox GTK+ dark themes fix
// @version 0.4
// @description Resets colors in all pages to match those of a bright theme and, hopefully, fix annoying inconsistencies caused by using darker GTK+ themes with Firefox.
// @namespace https://github.com/darkalemanbr/userscripts
// @include *
// @downloadURL https://raw.githubusercontent.com/darkalemanbr/userscripts/master/firefox-gtk-dark-themes-fix/script.user.js
// @updateURL https://raw.githubusercontent.com/darkalemanbr/userscripts/master/firefox-gtk-dark-themes-fix/script.user.js
// @require https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js
// ==/UserScript==
var css = '' +
':root { color: #000; background: #FFF; }'
;
$('link[rel=stylesheet]:first-of-type, style:first-of-type').before('<style type="text/css">' + css + '"</style>');
|
// ==UserScript==
// @name Firefox GTK+ dark themes fix
// @version 0.3
// @description Resets colors in all pages to match those of a bright theme and, hopefully, fix annoying inconsistencies caused by using darker GTK+ themes with Firefox.
// @namespace https://github.com/darkalemanbr/userscripts
// @include *
// @downloadURL https://raw.githubusercontent.com/darkalemanbr/userscripts/master/firefox-gtk-dark-themes-fix/script.user.js
// @updateURL https://raw.githubusercontent.com/darkalemanbr/userscripts/master/firefox-gtk-dark-themes-fix/script.user.js
// @require https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js
// ==/UserScript==
var css = '' +
'* { color: #000; background: #FFF; }'
;
$('link[rel=stylesheet]:first-of-type, style:first-of-type').before('<style type="text/css">' + css + '"</style>');
|
Add fix for embroider tests
|
/* eslint-disable prettier/prettier */
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
let app = new EmberAddon(defaults, {
minifyCSS: {
enabled: false
},
'ember-prism': {
'components': ['bash', 'javascript', 'handlebars', 'markup-templating'],
'plugins': ['line-highlight']
}
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
const { maybeEmbroider } = require('@embroider/test-setup');
return maybeEmbroider(app, {
// Needed for IE11 https://github.com/embroider-build/embroider/issues/731
skipBabel: [
{
package: 'qunit'
}
]
});
};
|
/* eslint-disable prettier/prettier */
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
let app = new EmberAddon(defaults, {
minifyCSS: {
enabled: false
},
'ember-prism': {
'components': ['bash', 'javascript', 'handlebars', 'markup-templating'],
'plugins': ['line-highlight']
}
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
const { maybeEmbroider } = require('@embroider/test-setup');
return maybeEmbroider(app);
};
|
Enable minification for esbuild in production.
|
const watch = process.argv.includes("--watch") && {
/**
* Log when a build is finished or failed.
*
* @param {Error|null} error The possible error.
* @returns {void}
*/
onRebuild(error) {
if (error) {
// eslint-disable-next-line no-console
console.error("[watch] build failed", error);
} else {
console.log("[watch] build finished"); // eslint-disable-line no-console
}
}
};
require("esbuild").
build({
"bundle": true,
"entryPoints": ["app/javascript/application.js"],
"minify": process.env.NODE_ENV === "production",
"outfile": "app/assets/builds/application.js",
watch
}).
catch(() => {
process.exit(1); // eslint-disable-line no-magic-numbers
});
|
const watch = process.argv.includes("--watch") && {
/**
* Log when a build is finished or failed.
*
* @param {Error|null} error The possible error.
* @returns {void}
*/
onRebuild(error) {
if (error) {
// eslint-disable-next-line no-console
console.error("[watch] build failed", error);
} else {
console.log("[watch] build finished"); // eslint-disable-line no-console
}
}
};
require("esbuild").
build({
"bundle": true,
"entryPoints": ["app/javascript/application.js"],
"outfile": "app/assets/builds/application.js",
watch
}).
catch(() => {
process.exit(1); // eslint-disable-line no-magic-numbers
});
|
Add python package install dependency
Add babel as python package install dependency. Babel is used in
phonenumber_field.widget.
|
from setuptools import setup, find_packages
from phonenumber_field import __version__
setup(
name="django-phonenumber-field",
version=__version__,
url='http://github.com/stefanfoulis/django-phonenumber-field',
license='BSD',
platforms=['OS Independent'],
description="An international phone number field for django models.",
install_requires=[
'phonenumbers>=7.0.2',
'babel',
],
long_description=open('README.rst').read(),
author='Stefan Foulis',
author_email='stefan.foulis@gmail.com',
maintainer='Stefan Foulis',
maintainer_email='stefan.foulis@gmail.com',
packages=find_packages(),
package_data = {
'phonenumber_field': [
'locale/*/LC_MESSAGES/*',
],
},
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
|
from setuptools import setup, find_packages
from phonenumber_field import __version__
setup(
name="django-phonenumber-field",
version=__version__,
url='http://github.com/stefanfoulis/django-phonenumber-field',
license='BSD',
platforms=['OS Independent'],
description="An international phone number field for django models.",
install_requires=[
'phonenumbers>=7.0.2',
],
long_description=open('README.rst').read(),
author='Stefan Foulis',
author_email='stefan.foulis@gmail.com',
maintainer='Stefan Foulis',
maintainer_email='stefan.foulis@gmail.com',
packages=find_packages(),
package_data = {
'phonenumber_field': [
'locale/*/LC_MESSAGES/*',
],
},
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
|
Add comment about more efficient than bubble sort
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Selection sort is more efficient than bubble sort
since the former does not swap for all successive pairs,
and just do one swapping for each iteration.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
Delete Report models before reloading them
|
# -*- encoding: UTF-8 -*-
#
# Copyright 2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of CVN.
#
# CVN is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CVN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with CVN. If not, see
# <http://www.gnu.org/licenses/>.
#
from django.core.management.base import BaseCommand
from core.ws_utils import CachedWS as ws
from cvn.models import ReportArea, ReportDept
from django.utils.translation import ugettext as _
class Command(BaseCommand):
help = _(u'Import department and area info from WebServices')
def handle(self, *args, **options):
ReportArea.objects.all().delete()
ReportDept.objects.all().delete()
ReportArea.reload()
ReportDept.reload()
|
# -*- encoding: UTF-8 -*-
#
# Copyright 2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of CVN.
#
# CVN is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CVN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with CVN. If not, see
# <http://www.gnu.org/licenses/>.
#
from django.core.management.base import BaseCommand
from core.ws_utils import CachedWS as ws
from cvn.models import ReportArea, ReportDept
from django.utils.translation import ugettext as _
class Command(BaseCommand):
help = _(u'Import department and area info from WebServices')
def handle(self, *args, **options):
ReportArea.reload()
ReportDept.reload()
|
Remove forgotten bits of buildbot 0.7.12 compatibility code.
A second take of https://chromiumcodereview.appspot.com/13560017 but should work now.
R=iannucci@chromium.org
BUG=
Review URL: https://chromiumcodereview.appspot.com/20481003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@217592 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script to setup the environment to run unit tests.
Modifies PYTHONPATH to automatically include parent, common and pylibs
directories.
"""
import os
import sys
RUNTESTS_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_PATH = os.path.join(RUNTESTS_DIR, 'data')
BASE_DIR = os.path.abspath(os.path.join(RUNTESTS_DIR, '..', '..', '..'))
sys.path.insert(0, os.path.join(BASE_DIR, 'scripts'))
sys.path.insert(0, os.path.join(BASE_DIR, 'site_config'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'buildbot_slave_8_4'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'twisted_10_2'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'mock-1.0.1'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'coverage-3.6'))
from common import find_depot_tools # pylint: disable=W0611
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script to setup the environment to run unit tests.
Modifies PYTHONPATH to automatically include parent, common and pylibs
directories.
"""
import os
import sys
RUNTESTS_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_PATH = os.path.join(RUNTESTS_DIR, 'data')
BASE_DIR = os.path.abspath(os.path.join(RUNTESTS_DIR, '..', '..', '..'))
sys.path.insert(0, os.path.join(BASE_DIR, 'scripts'))
sys.path.insert(0, os.path.join(BASE_DIR, 'site_config'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'buildbot_8_4p1'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'twisted_10_2'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'mock-1.0.1'))
sys.path.insert(0, os.path.join(BASE_DIR, 'third_party', 'coverage-3.6'))
from common import find_depot_tools # pylint: disable=W0611
|
fix: Use README as the long description on PyPI
|
#!/usr/bin/env python
import sys
from setuptools import setup
from shortuuid import __version__
assert sys.version >= "3.5", "Requires Python v3.5 or above."
classifiers = [
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Software Development :: Libraries :: Python Modules",
]
setup(
name="shortuuid",
version=__version__,
author="Stochastic Technologies",
author_email="info@stochastictechnologies.com",
url="https://github.com/stochastic-technologies/shortuuid/",
long_description=open("README.rst").read(),
description="A generator library for concise, " "unambiguous and URL-safe UUIDs.",
license="BSD",
python_requires=">=3.5",
classifiers=classifiers,
packages=["shortuuid"],
test_suite="shortuuid.tests",
tests_require=[],
)
|
#!/usr/bin/env python
import sys
from setuptools import setup
from shortuuid import __version__
assert sys.version >= "3.5", "Requires Python v3.5 or above."
classifiers = [
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Software Development :: Libraries :: Python Modules",
]
setup(
name="shortuuid",
version=__version__,
author="Stochastic Technologies",
author_email="info@stochastictechnologies.com",
url="https://github.com/stochastic-technologies/shortuuid/",
description="A generator library for concise, " "unambiguous and URL-safe UUIDs.",
long_description=open("README.rst").read(),
license="BSD",
python_requires=">=3.5",
classifiers=classifiers,
packages=["shortuuid"],
test_suite="shortuuid.tests",
tests_require=[],
)
|
Destroy stream early on error
|
let Stream = require('stream');
const {SaxesParser, EVENTS} = require('saxes');
// Backwards compatibility for earlier node versions and browsers
if (!Stream.Readable || typeof Symbol === 'undefined' || !Stream.Readable.prototype[Symbol.asyncIterator]) {
Stream = require('readable-stream');
}
module.exports = class SAXStream extends Stream.Transform {
constructor() {
super({readableObjectMode: true});
this._error = null;
this.saxesParser = new SaxesParser();
this.saxesParser.on('error', error => {
this.destroy(error);
});
for (const event of EVENTS) {
if (event !== 'ready' && event !== 'error' && event !== 'end') {
this.saxesParser.on(event, value => {
this.push({event, value});
});
}
}
}
_transform(chunk, _encoding, callback) {
this.saxesParser.write(chunk.toString());
// saxesParser.write and saxesParser.on() are synchronous,
// so we can only reach the below line once all event handlers
// have been called
callback();
}
_final(callback) {
this.saxesParser.close();
callback();
}
};
|
let Stream = require('stream');
const {SaxesParser, EVENTS} = require('saxes');
// Backwards compatibility for earlier node versions and browsers
if (!Stream.Readable || typeof Symbol === 'undefined' || !Stream.Readable.prototype[Symbol.asyncIterator]) {
Stream = require('readable-stream');
}
module.exports = class SAXStream extends Stream.Transform {
constructor() {
super({readableObjectMode: true});
this._error = null;
this.saxesParser = new SaxesParser();
this.saxesParser.on('error', error => {
this._error = error;
});
for (const event of EVENTS) {
if (event !== 'ready' && event !== 'error' && event !== 'end') {
this.saxesParser.on(event, value => {
this.push({event, value});
});
}
}
}
_transform(chunk, _encoding, callback) {
this.saxesParser.write(chunk.toString());
// saxesParser.write and saxesParser.on() are synchronous,
// so we can only reach the below line once all event handlers
// have been called
callback(this._error);
}
_final(callback) {
this.saxesParser.close();
callback();
}
};
|
Add return type to `conduit.query`
Summary: Fixes T6950. Adds the return type of Conduit API methods to the `conduit.query` call.
Test Plan: Called `echo '{}' | arc call-conduit conduit.query` and verified that the return types were present in the response.
Reviewers: epriestley, #blessed_reviewers
Reviewed By: epriestley, #blessed_reviewers
Subscribers: Korvin, epriestley
Maniphest Tasks: T6950
Differential Revision: https://secure.phabricator.com/D11466
|
<?php
final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {
public function getAPIMethodName() {
return 'conduit.query';
}
public function getMethodDescription() {
return 'Returns the parameters of the Conduit methods.';
}
public function defineParamTypes() {
return array();
}
public function defineReturnType() {
return 'dict<dict>';
}
public function defineErrorTypes() {
return array();
}
protected function execute(ConduitAPIRequest $request) {
$classes = id(new PhutilSymbolLoader())
->setAncestorClass('ConduitAPIMethod')
->setType('class')
->loadObjects();
$names_to_params = array();
foreach ($classes as $class) {
$names_to_params[$class->getAPIMethodName()] = array(
'params' => $class->defineParamTypes(),
'return' => $class->defineReturnType(),
);
}
return $names_to_params;
}
}
|
<?php
final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {
public function getAPIMethodName() {
return 'conduit.query';
}
public function getMethodDescription() {
return 'Returns the parameters of the Conduit methods.';
}
public function defineParamTypes() {
return array();
}
public function defineReturnType() {
return 'dict<dict>';
}
public function defineErrorTypes() {
return array();
}
protected function execute(ConduitAPIRequest $request) {
$classes = id(new PhutilSymbolLoader())
->setAncestorClass('ConduitAPIMethod')
->setType('class')
->loadObjects();
$names_to_params = array();
foreach ($classes as $class) {
$names_to_params[$class->getAPIMethodName()] = array(
'params' => $class->defineParamTypes(),
);
}
return $names_to_params;
}
}
|
Make sure handle all the exceptions
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import requests
def check(url):
try:
response = requests.get(
"https://isitup.org/{0}.json".format(url),
headers={'User-Agent': 'https://github.com/lord63/isitup'})
except requests.exceptions.ConnectionError:
return ("A network problem(e.g. you're offline; refused connection),"
"can't check the site right now.")
except requests.exceptions.Timeout:
return "The request timed out."
except requests.exceptions.RequestException as error:
return "Something bad happened:\n{0}".format(error)
status_code = response.json()["status_code"]
if status_code == 1:
return ("Yay, {0} is up.\nIt took {1[response_time]} ms "
"for a {1[response_code]} response code with "
"an ip of {1[response_ip]}".format(url, response.json()))
if status_code == 2:
return "{0} seems to be down!".format(url)
if status_code == 3:
return "We need a valid domain to check! Try again."
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import requests
def check(url):
try:
response = requests.get(
"https://isitup.org/{0}.json".format(url),
headers={'User-Agent': 'https://github.com/lord63/isitup'})
except requests.exceptions.ConnectionError:
return ("A network problem(e.g. you're offline; refused connection),"
"can't check the site right now.")
except requests.exceptions.Timeout:
return "The request timed out."
status_code = response.json()["status_code"]
if status_code == 1:
return ("Yay, {0} is up.\nIt took {1[response_time]} ms "
"for a {1[response_code]} response code with "
"an ip of {1[response_ip]}".format(url, response.json()))
if status_code == 2:
return "{0} seems to be down!".format(url)
if status_code == 3:
return "We need a valid domain to check! Try again."
|
Fix a bug that failed to show Rekit Studio.
|
const setItem = type => (key, item) => {
const obj = window[`${type}Storage`];
return obj.setItem(key, JSON.stringify(item));
};
const getItem = type => (key, defaultValue, saveIfNotExist) => {
const obj = window[`${type}Storage`];
const savedItem = obj.getItem(key);
if (!savedItem && saveIfNotExist) {
setItem(type)(key, defaultValue);
}
try {
if (savedItem) return JSON.parse(savedItem);
} catch (e) {
obj.removeItem(key);
return defaultValue;
}
return defaultValue;
};
const removeItem = type => (key) => {
const obj = window[`${type}Storage`];
obj.removeItem(key);
};
export const storage = {
local: {
setItem: setItem('local'),
getItem: getItem('local'),
removeItem: removeItem('local'),
},
session: {
setItem: setItem('session'),
getItem: getItem('session'),
removeItem: removeItem('session'),
},
};
export const getTreeNodeData = (treeData, key) => {
const arr = [treeData];
while (arr.length) {
const node = arr.pop();
if (node.key === key) return node;
if (node.children) arr.push.apply(arr, node.children);
}
return null;
};
|
const setItem = type => (key, item) => {
const obj = window[`${type}Storage`];
return obj.setItem(key, JSON.stringify(item));
};
const getItem = type => (key, defaultValue, saveIfNotExist) => {
const obj = window[`${type}Storage`];
const savedItem = obj.getItem(key);
if (!savedItem && saveIfNotExist) {
setItem(type)(key, defaultValue);
}
return savedItem ? JSON.parse(savedItem) : defaultValue;
};
export const storage = {
local: {
setItem: setItem('local'),
getItem: getItem('local'),
},
session: {
setItem: setItem('session'),
getItem: getItem('session'),
},
};
export const getTreeNodeData = (treeData, key) => {
const arr = [treeData];
while (arr.length) {
const node = arr.pop();
if (node.key === key) return node;
if (node.children) arr.push.apply(arr, node.children);
}
return null;
};
|
Add in election title to content pane
|
<?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
$stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?");
$stmt->bindParam(1, $row["election"]);
$stmt->execute();
$election_name = $stmt->fetch(PDO::FETCH_NUM)[0];
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Edit Election
<small><?php echo $election_name; ?></small>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-th-list"></i> Elections</li>
<li class="active"><?php echo $election_name; ?></li>
</ol>
</section>
<section class="content">
<!-- Your Page Content Here -->
</section>
</div>
<?php
require_once('page_template_dash_foot.php');
?>
|
<?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Edit Election
<small>Optional description</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li>
<li class="active">Here</li>
</ol>
</section>
<section class="content">
<!-- Your Page Content Here -->
</section>
</div>
<?php
require_once('page_template_dash_foot.php');
?>
|
Add @glimmer/env to vendor.js in local builds.
|
"use strict";
const build = require('@glimmer/build');
const packageDist = require('@glimmer/build/lib/package-dist');
const buildVendorPackage = require('@glimmer/build/lib/build-vendor-package');
const funnel = require('broccoli-funnel');
const path = require('path');
module.exports = function() {
let vendorTrees = [
'@glimmer/application',
'@glimmer/resolver',
'@glimmer/compiler',
'@glimmer/di',
'@glimmer/object-reference',
'@glimmer/reference',
'@glimmer/runtime',
'@glimmer/syntax',
'@glimmer/util',
'@glimmer/wire-format',
'@glimmer/env'
].map(packageDist);
vendorTrees.push(buildVendorPackage('simple-html-tokenizer'));
vendorTrees.push(funnel(path.dirname(require.resolve('handlebars/package')), {
include: ['dist/handlebars.amd.js'] }));
return build({
vendorTrees,
external: [
'@glimmer/application',
'@glimmer/resolver',
'@glimmer/compiler',
'@glimmer/reference',
'@glimmer/util',
'@glimmer/runtime',
'@glimmer/di',
'@glimmer/env'
]
});
}
|
"use strict";
const build = require('@glimmer/build');
const packageDist = require('@glimmer/build/lib/package-dist');
const buildVendorPackage = require('@glimmer/build/lib/build-vendor-package');
const funnel = require('broccoli-funnel');
const path = require('path');
module.exports = function() {
let vendorTrees = [
'@glimmer/application',
'@glimmer/resolver',
'@glimmer/compiler',
'@glimmer/di',
'@glimmer/object-reference',
'@glimmer/reference',
'@glimmer/runtime',
'@glimmer/syntax',
'@glimmer/util',
'@glimmer/wire-format'
].map(packageDist);
vendorTrees.push(buildVendorPackage('simple-html-tokenizer'));
vendorTrees.push(funnel(path.dirname(require.resolve('handlebars/package')), {
include: ['dist/handlebars.amd.js'] }));
return build({
vendorTrees,
external: [
'@glimmer/application',
'@glimmer/resolver',
'@glimmer/compiler',
'@glimmer/reference',
'@glimmer/util',
'@glimmer/runtime',
'@glimmer/di'
]
});
}
|
Return 404 instead of 400 if the translation is not found.
|
/*
* Copyright (c) 2014 ZionSoft. All rights reserved.
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file.
*/
package translation
import (
"net/http"
"net/url"
"appengine"
"appengine/blobstore"
"src/core"
)
func DownloadTranslationHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
panic(&core.Error{http.StatusMethodNotAllowed, ""})
}
// parses query parameters
params, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
panic(&core.Error{http.StatusBadRequest, ""})
}
// TODO supports other query params
blobKey := params.Get("blobKey")
translations := loadTranslations(appengine.NewContext(r))
for _, t := range translations {
if (string)(t.BlobKey) == blobKey {
blobstore.Send(w, appengine.BlobKey(blobKey))
return
}
}
panic(&core.Error{http.StatusNotFound, ""})
}
|
/*
* Copyright (c) 2014 ZionSoft. All rights reserved.
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file.
*/
package translation
import (
"net/http"
"net/url"
"appengine"
"appengine/blobstore"
"src/core"
)
func DownloadTranslationHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
panic(&core.Error{http.StatusMethodNotAllowed, ""})
}
// parses query parameters
params, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
panic(&core.Error{http.StatusBadRequest, ""})
}
// TODO supports other query params
blobKey := params.Get("blobKey")
translations := loadTranslations(appengine.NewContext(r))
for _, t := range translations {
if (string)(t.BlobKey) == blobKey {
blobstore.Send(w, appengine.BlobKey(blobKey))
return
}
}
panic(&core.Error{http.StatusBadRequest, ""})
}
|
Add HTML IDs to CloseDialogConfirmation
|
import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Button } from 'react-bootstrap'
import style from './style.css'
const CloseDialogConfirmation = ({ onYes, onNo }) => {
const idPrefix = 'closedialogconfim'
return (
<Modal show dialogClassName={style['cust-modal-content']}>
<Modal.Header bsClass={`modal-header ${style['cust-modal-header']}`}>
<Modal.Title id={`${idPrefix}-title`}>Dialog contains unsaved changes</Modal.Title>
</Modal.Header>
<Modal.Body bsClass={`modal-body ${style['cust-modal-body']}`}>
<h4 id={`${idPrefix}-body-text`}>Are you sure you want to drop your changes?</h4>
</Modal.Body>
<Modal.Footer>
<Button id={`${idPrefix}-button-no`} onClick={onNo} bsClass='btn btn-default'>No</Button>
<Button id={`${idPrefix}-button-yes`} onClick={onYes} bsClass='btn btn-info'>Yes</Button>
</Modal.Footer>
</Modal>
)
}
CloseDialogConfirmation.propTypes = {
onYes: PropTypes.func.isRequired,
onNo: PropTypes.func.isRequired,
}
export default CloseDialogConfirmation
|
import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Button } from 'react-bootstrap'
import style from './style.css'
const CloseDialogConfirmation = ({ onYes, onNo }) => {
return (
<Modal show dialogClassName={style['cust-modal-content']}>
<Modal.Header bsClass={`modal-header ${style['cust-modal-header']}`}>
<Modal.Title>Dialog contains unsaved changes</Modal.Title>
</Modal.Header>
<Modal.Body bsClass={`modal-body ${style['cust-modal-body']}`}>
<h4>Are you sure you want to drop your changes?</h4>
</Modal.Body>
<Modal.Footer>
<Button onClick={onNo} bsClass='btn btn-default'>No</Button>
<Button onClick={onYes} bsClass='btn btn-info'>Yes</Button>
</Modal.Footer>
</Modal>
)
}
CloseDialogConfirmation.propTypes = {
onYes: PropTypes.func.isRequired,
onNo: PropTypes.func.isRequired,
}
export default CloseDialogConfirmation
|
Remove setting user id and access token from response method in auth response handler
|
package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener) {
mUser = user;
mListener = listener;
}
public void onResponse(JSONObject response){
if (!response.optString(AuthUtil.USERID_KEY).isEmpty() && !response.optString(AuthUtil.ACCESS_TOKEN_KEY).isEmpty()) {
mListener.onSuccess(mUser, response.optString(AuthUtil.USERID_KEY), response.optString(AuthUtil.ACCESS_TOKEN_KEY));
} else {
mListener.onFailure(mUser, AuthException.defaultException());
}
}
public void onError(AuthException error) {
mListener.onFailure(mUser, error);
}
}
|
package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONException;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener){
mUser = user;
mListener = listener;
}
public void onResponse(JSONObject response){
try {
mUser.setUserId(response.getString(AuthUtil.USERID_KEY));
mUser.setAccessToken(response.getString(AuthUtil.ACCESS_TOKEN_KEY));
} catch(JSONException error){
mListener.onFailure(mUser, AuthException.defaultException());
return;
}
mUser.setStatus(User.Status.AUTHORIZED);
mListener.onSuccess(mUser, mUser.getUserId(), mUser.getAccessToken());
}
public void onError(AuthException error){
mListener.onFailure(mUser, error);
}
}
|
Add some missing disabled features for Cassandra
|
import mysql from './mysql';
import postgresql from './postgresql';
import sqlserver from './sqlserver';
import cassandra from './cassandra';
/**
* List of supported database clients
*/
export const CLIENTS = [
{
key: 'mysql',
name: 'MySQL',
defaultPort: 3306,
},
{
key: 'postgresql',
name: 'PostgreSQL',
defaultDatabase: 'postgres',
defaultPort: 5432,
},
{
key: 'sqlserver',
name: 'Microsoft SQL Server',
defaultPort: 1433,
},
{
key: 'cassandra',
name: 'Cassandra',
defaultPort: 9042,
disabledFeatures: [
'server:ssl',
'server:socketPath',
'server:user',
'server:password',
'scriptCreateTable',
],
},
];
export default {
mysql,
postgresql,
sqlserver,
cassandra,
};
|
import mysql from './mysql';
import postgresql from './postgresql';
import sqlserver from './sqlserver';
import cassandra from './cassandra';
/**
* List of supported database clients
*/
export const CLIENTS = [
{
key: 'mysql',
name: 'MySQL',
defaultPort: 3306,
},
{
key: 'postgresql',
name: 'PostgreSQL',
defaultDatabase: 'postgres',
defaultPort: 5432,
},
{
key: 'sqlserver',
name: 'Microsoft SQL Server',
defaultPort: 1433,
},
{
key: 'cassandra',
name: 'Cassandra',
defaultPort: 9042,
disabledFeatures: [
'scriptCreateTable',
],
},
];
export default {
mysql,
postgresql,
sqlserver,
cassandra,
};
|
Introduce global template function `url_for_snippet`
Use it to ease the transition to a multisite-capable snippet URL rule system.
|
"""
byceps.blueprints.snippet.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import abort, g, url_for
from ...services.snippet import mountpoint_service
from ...util.framework.blueprint import create_blueprint
from .templating import render_snippet_as_page, render_snippet_as_partial
blueprint = create_blueprint('snippet', __name__)
blueprint.add_app_template_global(render_snippet_as_partial, 'render_snippet')
@blueprint.app_template_global()
def url_for_snippet(name):
return url_for(f'snippet.{name}')
def view_current_version_by_name(name):
"""Show the current version of the snippet that is mounted with that
name.
"""
# Note: endpoint suffix != snippet name
version = mountpoint_service.find_current_snippet_version_for_mountpoint(
g.site_id, name
)
if version is None:
abort(404)
return render_snippet_as_page(version)
|
"""
byceps.blueprints.snippet.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import abort, g
from ...services.snippet import mountpoint_service
from ...util.framework.blueprint import create_blueprint
from .templating import render_snippet_as_page, render_snippet_as_partial
blueprint = create_blueprint('snippet', __name__)
blueprint.add_app_template_global(render_snippet_as_partial, 'render_snippet')
def view_current_version_by_name(name):
"""Show the current version of the snippet that is mounted with that
name.
"""
# Note: endpoint suffix != snippet name
version = mountpoint_service.find_current_snippet_version_for_mountpoint(
g.site_id, name
)
if version is None:
abort(404)
return render_snippet_as_page(version)
|
ETM: Add doc note that stages shouldn't change column headers
The reason for the stage system is because of ERED. I'm planning on two
stages. The first allows the user to input event results. In preparing
for the second stage, the application generates sweepstakes points using
the event's specification. Then, in the second stage, these are exposed
to the user for editing.
|
/**
*
*/
package mathsquared.resultswizard2;
import javax.swing.table.TableModel;
/**
* Represents data that can be edited in one or more stages and then transformed into another object.
*
* <p>Note that these stages should not change the column headers or layout in this table. They should only change which columns are editable and which are not. This will help generate a consistent user experience.</p>
*
* @author MathSquared
* @param <T> the type of data that can be obtained from this model using {@link #getResult()}
*
*/
public interface EditorTableModel<T> extends TableModel {
/**
* Returns the number of stages used by this editor.
*
* @return a number indicating the number of stages; this number must always be greater than or equal to 1
*/
public int numStages ();
/**
* Returns the current stage.
*
* @return a zero-based index for the current stage; this is guaranteed to be <code>>= 0</code> and <code>< {@link #numStages()}</code>
*/
public int currentStage ();
/**
* Moves to the next stage.
*
* @throws IllegalStateException if we are at the last stage
*/
public void nextStage ();
/**
* Moves to the previous stage.
*
* @throws IllegalStateException if we are at the first stage
*/
public void previousStage ();
/**
* Obtains the current result of this model. This only works if we are at the last stage.
*
* @return an object representing the data stored in this model
* @throws IllegalStateException if we are not at the last stage
*/
public T getResult ();
}
|
/**
*
*/
package mathsquared.resultswizard2;
import javax.swing.table.TableModel;
/**
* Represents data that can be edited in one or more stages and then transformed into another object.
*
* @author MathSquared
* @param <T> the type of data that can be obtained from this model using {@link #getResult()}
*
*/
public interface EditorTableModel<T> extends TableModel {
/**
* Returns the number of stages used by this editor.
*
* @return a number indicating the number of stages; this number must always be greater than or equal to 1
*/
public int numStages ();
/**
* Returns the current stage.
*
* @return a zero-based index for the current stage; this is guaranteed to be <code>>= 0</code> and <code>< {@link #numStages()}</code>
*/
public int currentStage ();
/**
* Moves to the next stage.
*
* @throws IllegalStateException if we are at the last stage
*/
public void nextStage ();
/**
* Moves to the previous stage.
*
* @throws IllegalStateException if we are at the first stage
*/
public void previousStage ();
/**
* Obtains the current result of this model. This only works if we are at the last stage.
*
* @return an object representing the data stored in this model
* @throws IllegalStateException if we are not at the last stage
*/
public T getResult ();
}
|
Fix bad indexing in array
|
if (!localStorage['saved']){
localStorage['letA'] = '#800000'; //maroon
localStorage['letE'] = '#008000'; //green
localStorage['letI'] = '#0000ff'; //blue
localStorage['letO'] = '#008080'; //teal
localStorage['letU'] = '#800080'; //purple
localStorage['saved'] = 'Y';
}
// Converts an integer (unicode value) to a char
function itoa(i)
{
return String.fromCharCode(i);
}
// Converts a char into to an integer (unicode value)
function atoi(a)
{
return a.charCodeAt();
}
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getColors"){
var colorList = new Array();
//first the letters
for( x=0; x<26; x++){
colorList[x] = localStorage['let' + itoa( atoi('A') + x) ];
}
//now the numbers...
for( x=26; x<36; x++){
colorList[x] = localStorage['let' + itoa( atoi('0') + x - 26) ];
}
sendResponse({colors: colorList});
}
else{
sendResponse({}); // snub them.
}
});
|
if (!localStorage['saved']){
localStorage['letA'] = '#800000'; //maroon
localStorage['letE'] = '#008000'; //green
localStorage['letI'] = '#0000ff'; //blue
localStorage['letO'] = '#008080'; //teal
localStorage['letU'] = '#800080'; //purple
localStorage['saved'] = 'Y';
}
// Converts an integer (unicode value) to a char
function itoa(i)
{
return String.fromCharCode(i);
}
// Converts a char into to an integer (unicode value)
function atoi(a)
{
return a.charCodeAt();
}
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getColors"){
var colorList = new Array();
//first the letters
for( x=0; x<26; x++){
colorList[x] = localStorage['let' + itoa( atoi('A') + x) ];
}
//now the numbers...
for( x=0; x<10; x++){
colorList[x] = localStorage['let' + itoa( atoi('0') + x) ];
}
sendResponse({colors: colorList});
}
else{
sendResponse({}); // snub them.
}
});
|
Add one more line of comment in printList function.
|
"""
This file includes several data structures used in LeetCode question.
"""
# Definition for a list node.
class ListNode(object):
def __init__(self, n):
self.val = n
self.next = None
def createLinkedList(nodelist):
#type nodelist: list[int/float]
#rtype: head of linked list
linkedList = ListNode(0)
head = linkedList
for val in nodelist:
linkedList.next = ListNode(val)
linkedList = linkedList.next
return head.next
def printList(head):
if not head:
print "head is None!\n"
return
else:
while head:
print head.val
head = head.next
print "END OF LIST"
return
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#TODO finish createBinaryTree
def createBinaryTree(nodelist):
root = TreeNode(0)
l = len(nodelist)
if l == 0:
return None
if __name__ == '__main__':
# main()
n = [1,2,3]
bst = createBinaryTree(n)
|
"""
This file includes several data structures used in LeetCode question.
"""
# Definition for a list node.
class ListNode(object):
def __init__(self, n):
self.val = n
self.next = None
def createLinkedList(nodelist):
#type nodelist: list[int/float]
#rtype: head of linked list
linkedList = ListNode(0)
head = linkedList
for val in nodelist:
linkedList.next = ListNode(val)
linkedList = linkedList.next
return head.next
def printList(head):
if not head:
print "head is None!\n"
return
else:
while head:
print head.val
head = head.next
return
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#TODO finish createBinaryTree
def createBinaryTree(nodelist):
root = TreeNode(0)
l = len(nodelist)
if l == 0:
return None
if __name__ == '__main__':
# main()
n = [1,2,3]
bst = createBinaryTree(n)
|
Add a method to print a message on the sense hat
|
class HatManager(object):
def __init__(self, sense):
self.sense = sense
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
def refresh_state(self):
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
@property
def get_humidity(self):
return self._humidity
@property
def get_temperature(self):
return self._temperature
@property
def get_pressure(self):
return self._pressure
def set_message(self, msg):
self.sense.show_message(msg, scroll_speed=0.05)
|
class HatManager(object):
def __init__(self, sense):
self.sense = sense
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
def refresh_state(self):
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
@property
def get_humidity(self):
return self._humidity
@property
def get_temperature(self):
return self._temperature
@property
def get_pressure(self):
return self._pressure
|
Save value in storage on init
|
(function (angular) {
'use strict';
var StoredItem = function (storage, itemName, defaultValueFactory, log) {
var value = defaultValueFactory();
this.get = function () {
return value;
};
this.save = function (newValue) {
value = newValue;
storage.setItem(itemName, angular.toJson(value));
};
this.reset = function () {
value = defaultValueFactory();
storage.removeItem(itemName);
};
var storedValue = storage.getItem(itemName);
if (_.isString(storedValue)) {
try {
_.merge(value, angular.fromJson(storedValue));
} catch (e) {
log.warn('Caught exception when loading filters from local storage item', itemName, ':', e);
}
}
this.save(value);
};
var BrowserObjectStorage = function (storage, log) {
this.getItem = function (itemName, defaultValueFactory) {
return new StoredItem(storage, itemName, defaultValueFactory, log);
};
};
angular.module('zucchini-ui-frontend')
.factory('BrowserSessionStorage', function ($window, $log) {
return new BrowserObjectStorage($window.sessionStorage, $log);
})
.factory('BrowserLocalStorage', function ($window, $log) {
return new BrowserObjectStorage($window.localStorage, $log);
});
})(angular);
|
(function (angular) {
'use strict';
var StoredItem = function (storage, itemName, defaultValueFactory, log) {
var value = defaultValueFactory();
var storedValue = storage.getItem(itemName);
if (_.isString(storedValue)) {
try {
_.merge(value, angular.fromJson(storedValue));
} catch (e) {
log.warn('Caught exception when loading filters from local storage item', itemName, ':', e);
}
}
this.get = function () {
return value;
};
this.save = function (newValue) {
value = newValue;
storage.setItem(itemName, angular.toJson(value));
};
this.reset = function () {
value = defaultValueFactory();
storage.removeItem(itemName);
};
};
var BrowserObjectStorage = function (storage, log) {
this.getItem = function (itemName, defaultValueFactory) {
return new StoredItem(storage, itemName, defaultValueFactory, log);
};
};
angular.module('zucchini-ui-frontend')
.factory('BrowserSessionStorage', function ($window, $log) {
return new BrowserObjectStorage($window.sessionStorage, $log);
})
.factory('BrowserLocalStorage', function ($window, $log) {
return new BrowserObjectStorage($window.localStorage, $log);
});
})(angular);
|
Fix error in History table if stack does not exist
Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba
|
# -*- coding: utf8 -*-
#
# 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.
from horizon import tables as horizon_tables
from tuskar_ui import api
from tuskar_ui.infrastructure.history import tables
class IndexView(horizon_tables.DataTableView):
table_class = tables.HistoryTable
template_name = "infrastructure/history/index.html"
def get_data(self):
plan = api.tuskar.OvercloudPlan.get_the_plan(self.request)
if plan:
stack = api.heat.Stack.get_by_plan(self.request, plan)
if stack:
return stack.events
return []
|
# -*- coding: utf8 -*-
#
# 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.
from horizon import tables as horizon_tables
from tuskar_ui import api
from tuskar_ui.infrastructure.history import tables
class IndexView(horizon_tables.DataTableView):
table_class = tables.HistoryTable
template_name = "infrastructure/history/index.html"
def get_data(self):
plan = api.tuskar.OvercloudPlan.get_the_plan(self.request)
if plan:
stack = api.heat.Stack.get_by_plan(self.request, plan)
if stack:
return stack.events
|
Add a shebang for a python interpreter.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 5000,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
@manager.command
def db_recreate_tables():
"""Drop and create all the db tables."""
if prompt_bool('Are you sure you want to recreate all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
db.create_tables()
if __name__ == '__main__':
manager.run()
|
# -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 5000,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
@manager.command
def db_recreate_tables():
"""Drop and create all the db tables."""
if prompt_bool('Are you sure you want to recreate all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
db.create_tables()
if __name__ == '__main__':
manager.run()
|
Remove tree layout, use default layout instead.
|
package nl.tudelft.dnainator.ui;
import nl.tudelft.dnainator.graph.DNAGraph;
import org.graphstream.graph.Graph;
import org.graphstream.ui.view.Viewer;
/**
* The viewer is responsible for managing the interactable views of the the strain graph.
* Use the addDefaultView() method to obtain a view.
*/
public class DNAViewer extends Viewer {
/**
* Creates a new GraphViewer, with a default graph
* and ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
*/
public DNAViewer() {
this(new DNAGraph(), ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
}
/**
* Creates a new GraphViewer, with ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
* @param graph The graph of strains.
*/
public DNAViewer(Graph graph) {
this(graph, ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
}
/**
* Creates a new GraphViewer.
* @param graph The graph of strains.
* @param model The ThreadingModel to use.
*/
public DNAViewer(Graph graph, ThreadingModel model) {
super(graph, model);
this.enableAutoLayout();
this.setCloseFramePolicy(Viewer.CloseFramePolicy.EXIT);
}
}
|
package nl.tudelft.dnainator.ui;
import nl.tudelft.dnainator.graph.DNAGraph;
import nl.tudelft.dnainator.graph.DNALayout;
import org.graphstream.graph.Graph;
import org.graphstream.ui.layout.Layout;
import org.graphstream.ui.view.Viewer;
/**
* The viewer is responsible for managing the interactable views of the the strain graph.
* Use the addDefaultView() method to obtain a view.
*/
public class DNAViewer extends Viewer {
/**
* Creates a new GraphViewer, with a default graph
* and ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
*/
public DNAViewer() {
this(new DNAGraph(), ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
}
/**
* Creates a new GraphViewer, with ThreadingModel.GRAPH_IN_ANOTHER_THREAD.
* @param graph The graph of strains.
*/
public DNAViewer(Graph graph) {
this(graph, ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
}
/**
* Creates a new GraphViewer.
* @param graph The graph of strains.
* @param model The ThreadingModel to use.
*/
public DNAViewer(Graph graph, ThreadingModel model) {
super(graph, model);
Layout layout = new DNALayout(graph);
this.enableAutoLayout(layout);
this.setCloseFramePolicy(Viewer.CloseFramePolicy.EXIT);
}
}
|
Fix comma and newline text.Word matching
|
package text
import (
"unicode"
)
type Query interface {
Match(string) int
}
// Word matches complete words only.
// The "complete words" of a string s is defined as the result of
// splitting the string on every single Unicode whitespace character.
type Word struct {
W string
}
func (q Word) Match(s string) int {
if s == q.W {
return 0
}
sr := []rune(s)
qr := []rune(q.W)
if len(sr) < len(qr) {
return -1
}
var nMatch int
for i := 0; i < len(sr); i++ {
if nMatch < len(qr) && sr[i] != qr[nMatch] {
nMatch = 0
continue
}
nMatch++
if nMatch == len(qr) {
// Check that any immediately preceding or following
// characters are spaces.
next := i + 1
prev := i - nMatch
hasNext := len(sr) > next
hasPrev := i-nMatch >= 0
if hasNext && !(unicode.IsSpace(sr[next]) || sr[next] == ',') {
nMatch = 0
continue
}
if hasPrev && !(unicode.IsSpace(sr[prev]) || sr[prev] == '\n') {
nMatch = 0
continue
}
return i - nMatch + 1
}
}
return -1
}
|
package text
import "unicode"
type Query interface {
Match(string) int
}
// Word matches complete words only.
// The "complete words" of a string s is defined as the result of
// splitting the string on every single Unicode whitespace character.
type Word struct {
W string
}
func (q Word) Match(s string) int {
if s == q.W {
return 0
}
sr := []rune(s)
qr := []rune(q.W)
if len(sr) < len(qr) {
return -1
}
var nMatch int
for i := 0; i < len(sr); i++ {
if nMatch < len(qr) && sr[i] != qr[nMatch] {
nMatch = 0
continue
}
nMatch++
if nMatch == len(qr) {
// Check that any immediately preceding or following
// characters are spaces.
next := i + 1
prev := i - nMatch
hasNext := len(sr) > next
hasPrev := i-nMatch >= 0
if (hasNext && (!unicode.IsSpace(sr[next]) || sr[next] != ',')) || (hasPrev && !unicode.IsSpace(sr[prev])) {
nMatch = 0
continue
}
return i - nMatch + 1
}
}
return -1
}
|
Add X- headers for security
X-XSS, X-Content-Type-Options, X-Download-Options have sane defaults,
but X-Frame-Options would break existing functionality of including
concourse on iframes if we added this header by default.
Instead, we expose what to put in this header in the ATC flags,
defaulting it to no header.
[#141162059]
Signed-off-by: Anisha Hirji <234e666d587164a63e127013ae06c9fdf954d431@pivotal.io>
|
package web
import (
"html/template"
"net/http"
"code.cloudfoundry.org/lager"
)
type templateData struct{}
type handler struct {
logger lager.Logger
template *template.Template
}
func NewHandler(logger lager.Logger) (http.Handler, error) {
tfuncs := &templateFuncs{
assetIDs: map[string]string{},
}
funcs := template.FuncMap{
"asset": tfuncs.asset,
}
src, err := Asset("index.html")
if err != nil {
return nil, err
}
t, err := template.New("index").Funcs(funcs).Parse(string(src))
if err != nil {
return nil, err
}
return &handler{
logger: logger,
template: t,
}, nil
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log := h.logger.Session("index")
err := h.template.Execute(w, templateData{})
if err != nil {
log.Fatal("failed-to-build-template", err, lager.Data{})
w.WriteHeader(http.StatusInternalServerError)
}
}
|
package web
import (
"html/template"
"net/http"
"code.cloudfoundry.org/lager"
)
type templateData struct{}
type handler struct {
logger lager.Logger
template *template.Template
}
func NewHandler(logger lager.Logger) (http.Handler, error) {
tfuncs := &templateFuncs{
assetIDs: map[string]string{},
}
funcs := template.FuncMap{
"asset": tfuncs.asset,
}
src, err := Asset("index.html")
if err != nil {
return nil, err
}
t, err := template.New("index").Funcs(funcs).Parse(string(src))
if err != nil {
return nil, err
}
return &handler{
logger: logger,
template: t,
}, nil
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log := h.logger.Session("index")
err := h.template.Execute(w, templateData{})
if err != nil {
log.Fatal("failed-to-build-template", err, lager.Data{})
w.WriteHeader(http.StatusInternalServerError)
}
}
|
Update to display notes count bubble only when new notes are available
|
from django.template import Library, Node, TemplateSyntaxError
from django.utils.html import escape
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from notes.models import Note
from castle.models import Profile
register = Library()
#-----------------------------------------------------------------------------
@register.filter
def note_link(note):
if note is None:
return u'<NULL NOTE>'
if note.read_date is None:
return mark_safe(u'<b><a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a></b>')
else:
return mark_safe(u'<a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a>')
#-----------------------------------------------------------------------------
@register.filter
def inbox_count(profile):
count = Note.objects.filter(recipient=profile, read_date__isnull=True, recipient_deleted_date__isnull=True).count()
if count > 0:
return mark_safe(u'<span class="inbox-count">' + escape(count) + u'</span>')
else:
return mark_safe(u'<span>' + escape(count) + u'</span>')
#-----------------------------------------------------------------------------
@register.filter
def author_msg(profile):
return mark_safe(u'<a class="btn btn-success author-msg-btn" href="/notes/compose?recipient=' + escape(profile.pen_name) + u'" type="button"><span class="glyphicon glyphicon-pencil"></span> Message ' + escape(profile.pen_name) + u'</a>')
|
from django.template import Library, Node, TemplateSyntaxError
from django.utils.html import escape
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from notes.models import Note
from castle.models import Profile
register = Library()
#-----------------------------------------------------------------------------
@register.filter
def note_link(note):
if note is None:
return u'<NULL NOTE>'
if note.read_date is None:
return mark_safe(u'<b><a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a></b>')
else:
return mark_safe(u'<a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a>')
#-----------------------------------------------------------------------------
@register.filter
def inbox_count(profile):
count = Note.objects.filter(recipient=profile, read_date__isnull=True, recipient_deleted_date__isnull=True).count()
return mark_safe(u'<span class="inbox-count">' + escape(count) + u'</span>')
#-----------------------------------------------------------------------------
@register.filter
def author_msg(profile):
return mark_safe(u'<a class="btn btn-success author-msg-btn" href="/notes/compose?recipient=' + escape(profile.pen_name) + u'" type="button"><span class="glyphicon glyphicon-pencil"></span> Message ' + escape(profile.pen_name) + u'</a>')
|
Change thumbnail to display self
|
import React from 'react'
import styled from 'styled-components'
const isActualThumbnail = thumbnail => thumbnail.startsWith('http')
const getPlaceholder = str => {
if (['nsfw'].includes(str)) {
return str
} else {
return 'self'
}
}
const BaseThumbnail = styled.div`
width: 70px;
height: 70px;
border-radius: 4px;
overflow: hidden;
`
const Image = BaseThumbnail.extend`
background: url(${props => props.thumbnail});
background-size: cover;
`
const Letter = BaseThumbnail.extend`
display: flex;
align-items: center;
justify-content: center;
background: #323a45;
color: #fff;
text-transform: uppercase;
font-size: 20px;
`
const Thumbnail = props => {
if (isActualThumbnail(props.thumbnail)) {
return <Image {...props} />
}
return <Letter>{getPlaceholder(props.thumbnail)}</Letter>
}
export default Thumbnail
|
import React from 'react'
import styled from 'styled-components'
const isActualThumbnail = thumbnail => thumbnail.startsWith('http')
const getPlaceholder = str => {
if (['nsfw'].includes(str)) {
return str
} else {
return 's'
}
}
const BaseThumbnail = styled.div`
width: 70px;
height: 70px;
border-radius: 4px;
overflow: hidden;
`
const Image = BaseThumbnail.extend`
background: url(${props => props.thumbnail});
background-size: cover;
`
const Letter = BaseThumbnail.extend`
display: flex;
align-items: center;
justify-content: center;
background: #323a45;
color: #fff;
text-transform: uppercase;
font-size: 24px;
`
const Thumbnail = props => {
if (isActualThumbnail(props.thumbnail)) {
return <Image {...props} />
}
return <Letter>{getPlaceholder(props.thumbnail)}</Letter>
}
export default Thumbnail
|
Fix test for python 2
|
from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((MAX_WIDTH, MAX_HEIGHT, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(test_image, INPUT_WIDTH, INPUT_HEIGHT)
# Check normalization
assertEq(len(np.where(np.abs(image) > 1)[0]), 0)
# Check resize
assertEq(image.size, 3 * INPUT_WIDTH * INPUT_HEIGHT)
# Check normalization on one element
assertEq(image[0, 0, 0], ((234 / 255.) - 0.5) * 2)
def testPredict():
model = loadNetwork(WEIGHTS_PTH, NUM_OUTPUT, MODEL_TYPE)
x, y = predict(model, test_image)
|
from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((*CAMERA_RESOLUTION, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(test_image, INPUT_WIDTH, INPUT_HEIGHT)
# Check normalization
assertEq(len(np.where(np.abs(image) > 1)[0]), 0)
# Check resize
assertEq(image.size, 3 * INPUT_WIDTH * INPUT_HEIGHT)
# Check normalization on one element
assertEq(image[0, 0, 0], ((234 / 255.) - 0.5) * 2)
def testPredict():
model = loadNetwork(WEIGHTS_PTH, NUM_OUTPUT, MODEL_TYPE)
x, y = predict(model, test_image)
|
Load asset at the footer.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Diskus;
use \Asset,
\Event,
Orchestra\Acl,
Orchestra\Core as O;
class Core {
/**
* Start your engine
*
* @static
* @access public
* @return void
*/
public static function start()
{
Acl::make('diskus')->attach(O::memory());
// Append all Diskus required assets for Orchestra Administrator
// Interface usage mainly on Resources page.
Event::listen('orchestra.started: backend', function()
{
$asset = Asset::container('orchestra.backend: footer');
$asset->script('redactor', 'bundles/orchestra/vendor/redactor/redactor.js', array('jquery', 'bootstrap'));
$asset->script('diskus', 'bundles/diskus/js/diskus.min.js', array('redactor'));
$asset->style('redactor', 'bundles/orchestra/vendor/redactor/css/redactor.css', array('bootstrap'));
});
}
}
|
<?php namespace Diskus;
use \Asset,
\Event,
Orchestra\Acl,
Orchestra\Core as O;
class Core {
/**
* Start your engine
*
* @static
* @access public
* @return void
*/
public static function start()
{
Acl::make('diskus')->attach(O::memory());
// Append all Diskus required assets for Orchestra Administrator
// Interface usage mainly on Resources page.
Event::listen('orchestra.started: backend', function()
{
$asset = Asset::container('orchestra.backend');
$asset->script('redactor', 'bundles/orchestra/vendor/redactor/redactor.js', array('jquery', 'bootstrap'));
$asset->script('diskus', 'bundles/diskus/js/diskus.min.js', array('redactor'));
$asset->style('redactor', 'bundles/orchestra/vendor/redactor/css/redactor.css', array('bootstrap'));
});
}
}
|
Move stuff so it looks prettier..
|
<?php
// Imports
use Slim\Slim;
use Slim\Views\Twig;
use ProjectRena\Lib\SessionHandler;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;
// Error display
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Load the autoloader
if(file_exists(__DIR__."/vendor/autoload.php"))
require_once(__DIR__."/vendor/autoload.php");
else
throw new Exception("vendor/autoload.php not found, make sure you run composer install");
// Require the config
if(file_exists(__DIR__."/config.php"))
require_once(__DIR__."/config.php");
else
throw new Exception("config.php not found (you might wanna start by copying config_new.php)");
// Prepare app
$app = new Slim($config["slim"]);
// Session
$session = new SessionHandler();
session_set_save_handler($session, true);
session_cache_limiter(false);
session_start();
// Launch Whoops
$app->add(new WhoopsMiddleware);
// Prepare view
$app->view(new Twig());
$app->view->parserOptions = $config["twig"];
// load the additional configs
$configFiles = glob(__DIR__ . "/config/*.php");
foreach($configFiles as $configFile)
require_once($configFile);
// Run app
$app->run();
|
<?php
// Imports
use ProjectRena\Lib\SessionHandler;
use Slim\Slim;
use Slim\Views\Twig;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;
// Error display
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Load the autoloader
if(file_exists(__DIR__."/vendor/autoload.php"))
require_once(__DIR__."/vendor/autoload.php");
else
throw new Exception("vendor/autoload.php not found, make sure you run composer install");
// Require the config
if(file_exists(__DIR__."/config.php"))
require_once(__DIR__."/config.php");
else
throw new Exception("config.php not found (you might wanna start by copying config_new.php)");
// Prepare app
$app = new Slim($config["slim"]);
// Session
$session = new SessionHandler();
session_set_save_handler($session, true);
session_cache_limiter(false);
session_start();
// Launch Whoops
$app->add(new WhoopsMiddleware);
// Prepare view
$app->view(new Twig());
$app->view->parserOptions = $config["twig"];
// load the additional configs
$configFiles = glob(__DIR__ . "/config/*.php");
foreach($configFiles as $configFile)
require_once($configFile);
// Run app
$app->run();
|
Update the service provider to publish the migrations
|
<?php
namespace Michaeljennings\Feed;
use Illuminate\Support\ServiceProvider;
class FeedServiceProvider extends ServiceProvider
{
/**
* @inheritdoc
*/
public function boot()
{
$this->publishes([
__DIR__.'/../migrations/' => database_path('migrations')
], 'migrations');
}
/**
* @inheritdoc
*/
public function register()
{
$this->app->bind('michaeljennings.feed.repository', 'Michaeljennings\Feed\Notifications\Repository');
$this->app->bind('michaeljennings.feed', function($app) {
return new Feed($app['michaeljennings.feed.repository']);
});
$this->app->alias('michaeljennings.feed.repository', 'Michaeljennings\Feed\Contracts\Repository');
$this->app->alias('michaeljennings.feed', 'Michaeljennings\Feed\Contracts\PullFeed');
$this->app->alias('michaeljennings.feed', 'Michaeljennings\Feed\Contracts\PushFeed');
}
}
|
<?php
namespace Michaeljennings\Feed;
use Illuminate\Support\ServiceProvider;
class FeedServiceProvider extends ServiceProvider
{
/**
* @inheritdoc
*/
public function register()
{
$this->app->bind('michaeljennings.feed.repository', 'Michaeljennings\Feed\Notifications\Repository');
$this->app->bind('michaeljennings.feed', function($app) {
return new Feed($app['michaeljennings.feed.repository']);
});
$this->app->alias('michaeljennings.feed.repository', 'Michaeljennings\Feed\Contracts\Repository');
$this->app->alias('michaeljennings.feed', 'Michaeljennings\Feed\Contracts\PullFeed');
$this->app->alias('michaeljennings.feed', 'Michaeljennings\Feed\Contracts\PushFeed');
}
}
|
Change message that detects instance type
|
#!/usr/bin/env python
import sys
import click
from aws_util import Ec2Util
@click.command()
@click.option('-p', '--profile', default='default', help='Profile name to use.')
@click.argument('id_or_tag', required=True)
@click.argument('new_instance_type', required=True)
def cli(profile, id_or_tag, new_instance_type):
ec2 = Ec2Util(profile)
instance = ec2.get_instance(id_or_tag)
if instance:
old_instance_state = instance.state['Name']
old_instance_type = instance.instance_type
print('Current instance type is %s' % old_instance_type)
if new_instance_type != instance.instance_type:
ec2.change_instance_type(id_or_tag, new_instance_type)
instance.reload()
print('Instance type changed to %s successfully' % instance.instance_type)
else:
print('Current instance type is the same as new type. No need to do anything.')
else:
print('Error. Cannot find instance')
if __name__ == '__main__':
cli()
|
#!/usr/bin/env python
import sys
import click
from aws_util import Ec2Util
@click.command()
@click.option('-p', '--profile', default='default', help='Profile name to use.')
@click.argument('id_or_tag', required=True)
@click.argument('new_instance_type', required=True)
def cli(profile, id_or_tag, new_instance_type):
ec2 = Ec2Util(profile)
instance = ec2.get_instance(id_or_tag)
if instance:
old_instance_state = instance.state['Name']
old_instance_type = instance.instance_type
print('Current instance type is %s' % old_instance_type)
if new_instance_type != instance.instance_type:
ec2.change_instance_type(id_or_tag, new_instance_type)
instance.reload()
print('Instance type changed to %s successfully' % instance.instance_type)
else:
print('Error. Cannot find instance')
if __name__ == '__main__':
cli()
|
Add userid to geotagging callback
|
'use strict';
var request = require('request');
var Q = require('q');
var config = require('../config');
const plugins = require('../../plugins');
const geoTagController = plugins.getFirst('geo-tag-controller');
if(!geoTagController) {
throw new Error('Missing a geo-tag-controller plugin!');
}
function deg(w) {
w = w % 360;
return w < 0 ? w + 360 : w;
}
exports.save = function(req, res, next) {
// Check with the CIP to ensure that the asset has not already been geotagged.
var collection = req.params.collection;
var id = req.params.id;
var latitude = parseFloat(req.body.latitude);
var longitude = parseFloat(req.body.longitude);
const userId = req.user.id;
// Checking if heading is a key in the body, as a valid heading can be 0.
// Heading is also converted to a degree between 0 and 360
var heading = 'heading' in req.body ?
deg(parseFloat(req.body.heading)) :
null;
if (!config.features.geoTagging) {
throw new Error('Geotagging is disabled.');
}
// Save the new coordinates to the CIP.
geoTagController.save({
collection,
id,
latitude,
longitude,
heading,
userId,
})
.then(geoTagController.updateIndex)
.then(function(result) {
res.json(result);
}, next);
};
|
'use strict';
var request = require('request');
var Q = require('q');
var config = require('../config');
const plugins = require('../../plugins');
const geoTagController = plugins.getFirst('geo-tag-controller');
if(!geoTagController) {
throw new Error('Missing a geo-tag-controller plugin!');
}
function deg(w) {
w = w % 360;
return w < 0 ? w + 360 : w;
}
exports.save = function(req, res, next) {
// Check with the CIP to ensure that the asset has not already been geotagged.
var collection = req.params.collection;
var id = req.params.id;
var latitude = parseFloat(req.body.latitude);
var longitude = parseFloat(req.body.longitude);
// Checking if heading is a key in the body, as a valid heading can be 0.
// Heading is also converted to a degree between 0 and 360
var heading = 'heading' in req.body ?
deg(parseFloat(req.body.heading)) :
null;
if (!config.features.geoTagging) {
throw new Error('Geotagging is disabled.');
}
// Save the new coordinates to the CIP.
geoTagController.save({
collection,
id,
latitude,
longitude,
heading
})
.then(geoTagController.updateIndex)
.then(function(result) {
res.json(result);
}, next);
};
|
Set meta descripting for the main page.
closes #77
|
import Vue from 'vue'
import Router from 'vue-router'
import index from '@/components/index'
import four from '@/components/four'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'github',
component: index,
meta: {
title: 'Linux Kernel CVE Tracker',
metaTags: [
{
name: 'description',
content: 'Security Tracker for the Linux Kernel. Provides details, fixed versions, and CVSS scores for CVEs affecting the Linux Kernel.'
}
]
}
},
{
path: '/streams/:stream_id',
name: 'stream',
component: () => import('@/components/stream')
},
{
path: '/cves',
name: 'cves',
component: () => import('@/components/cves')
},
{
path: '/cves/:cve_id',
name: 'cve',
component: () => import('@/components/cve')
},
{
path: '/404',
name: 'four',
component: four
},
{
path: '*',
redirect: '/404'
}
]
})
|
import Vue from 'vue'
import Router from 'vue-router'
import index from '@/components/index'
import four from '@/components/four'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'github',
component: index
},
{
path: '/streams/:stream_id',
name: 'stream',
component: () => import('@/components/stream')
},
{
path: '/cves',
name: 'cves',
component: () => import('@/components/cves')
},
{
path: '/cves/:cve_id',
name: 'cve',
component: () => import('@/components/cve')
},
{
path: '/404',
name: 'four',
component: four
},
{
path: '*',
redirect: '/404'
}
]
})
|
Add command line arguments for program
|
import argparse
import logging
import Portal
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="Dynatrace Synthetic Automation")
parser.add_argument(
"-t", "--type", help="The account type: [gpn|dynatrace]", required=True)
parser.add_argument(
"-u", "--username", help="The username for the account", type=str, required=True)
parser.add_argument(
"-p", "--password", help="The password for the account", type=str, required=True)
parser.add_argument(
"-d", "--directory", help="The directory to save the chart screenshots", type=str, default=".")
parser.add_argument(
"-v", "--verbose", help="Display debug message", action="store_true")
parser.add_argument(
"-c", "--chartNames", nargs="+", help="The name of the chart to capture")
args = parser.parse_args()
print(args)
# portal = Portal.DynatracePortal(args.username, args.password)
# portal.login()
# portal.saveChartToScreenshot()
|
import argparse
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="BTScreenshotAutomation")
parser.add_argument(
"-a", "--account", help="The name of the account", type=str, required=True)
parser.add_argument(
"-c", "--additionalCharts", nargs="+", help="The name of the additional charts")
parser.add_argument(
"-d", "--directory", help="The directory to save the chart screenshots", type=str, default=".")
parser.add_argument(
"-v", "--verbose", help="Display debug message", action="store_true")
args = parser.parse_args()
additionalCharts = set()
if args.additionalCharts is not None:
additionalCharts = set(args.additionalCharts)
btSeedingAccount = BTSeeding.BTSeedingAccount(
args.account, additionalCharts)
btSeedingAccount.run(saveDir=args.directory)
|
Add unique constraint to user email
|
module.exports = {
up: function (migration, DataTypes) {
return migration.createTable('Users', {
id: {
primaryKey: true,
allowNull: false,
type: DataTypes.UUID
},
name: {
allowNull: false,
type: DataTypes.STRING
},
email: {
unique: true,
allowNull: false,
type: DataTypes.STRING
},
hashedPassword: {
allowNull: false,
type: DataTypes.STRING
},
createdAt: {
allowNull: false,
type: DataTypes.DATE
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE
}
})
},
down: function (migration) {
return migration.dropTable('Users')
}
}
|
module.exports = {
up: function (migration, DataTypes) {
return migration.createTable('Users', {
id: {
primaryKey: true,
allowNull: false,
type: DataTypes.UUID
},
name: {
allowNull: false,
type: DataTypes.STRING
},
email: {
allowNull: false,
type: DataTypes.STRING
},
hashedPassword: {
allowNull: false,
type: DataTypes.STRING
},
createdAt: {
allowNull: false,
type: DataTypes.DATE
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE
}
})
},
down: function (migration) {
return migration.dropTable('Users')
}
}
|
Print selection in selectionChanged handler.
|
from PySide import QtGui, QtCore
class Tree(QtGui.QTreeView):
def __init__(self, parent=None):
super(Tree, self).__init__(parent)
def load_from_path(self, path):
""" Load directory containing file into the tree. """
# Link the tree to a model
model = QtGui.QFileSystemModel()
model.setRootPath(path)
self.setModel(model)
# Set the tree's index to the root of the model
indexRoot = model.index(model.rootPath())
self.setRootIndex(indexRoot)
# Display tree cleanly
self.hide_unwanted_info()
# Connect the selection changed signal
# selmodel = self.listing.selectionModel()
# self.selectionChanged.connect(self.handleSelectionChanged)
def hide_unwanted_info(self):
""" Hides unneeded columns and header. """
# Hide tree size and date columns
self.hideColumn(1)
self.hideColumn(2)
self.hideColumn(3)
# Hide tree header
self.setHeaderHidden(True)
def selectionChanged(self, selected, deselected):
"""
Event handler for selection changes.
"""
print "In selectionChanged"
indexes = selected.indexes()
if indexes:
print('row: %d' % indexes[0].row())
# print selected.value(indexes[0].row())
print self.model().data(indexes[0])
|
from PySide import QtGui, QtCore
class Tree(QtGui.QTreeView):
def __init__(self, parent=None):
super(Tree, self).__init__(parent)
def load_from_path(self, path):
""" Load directory containing file into the tree. """
# Link the tree to a model
model = QtGui.QFileSystemModel()
model.setRootPath(path)
self.setModel(model)
# Set the tree's index to the root of the model
indexRoot = model.index(model.rootPath())
self.setRootIndex(indexRoot)
# Display tree cleanly
self.hide_unwanted_info()
def hide_unwanted_info(self):
""" Hides unneeded columns and header. """
# Hide tree size and date columns
self.hideColumn(1)
self.hideColumn(2)
self.hideColumn(3)
# Hide tree header
self.setHeaderHidden(True)
|
Remove duplicate test, fix duplicate test
|
import transformCss from '../..'
it('textShadow with all values', () => {
expect(transformCss([['text-shadow', '10px 20px 30px red']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 30,
textShadowColor: 'red',
})
})
it('textShadow omitting blur', () => {
expect(transformCss([['text-shadow', '10px 20px red']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 0,
textShadowColor: 'red',
})
})
it('textShadow omitting color', () => {
expect(transformCss([['text-shadow', '10px 20px']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 0,
textShadowColor: 'black',
})
})
it('textShadow enforces offset-x and offset-y', () => {
expect(() => transformCss([['text-shadow', 'red']])).toThrow()
expect(() => transformCss([['text-shadow', '10px red']])).toThrow()
})
|
import transformCss from '../..'
it('textShadow with all values', () => {
expect(transformCss([['text-shadow', '10px 20px 30px red']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 30,
textShadowColor: 'red',
})
})
it('textShadow omitting blur', () => {
expect(transformCss([['text-shadow', '10px 20px red']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 0,
textShadowColor: 'red',
})
})
it('textShadow omitting color', () => {
expect(transformCss([['text-shadow', '10px 20px black']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 0,
textShadowColor: 'black',
})
})
it('textShadow omitting blur, offset-y', () => {
expect(transformCss([['text-shadow', '10px 20px red']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 0,
textShadowColor: 'red',
})
})
it('textShadow enforces offset-x and offset-y', () => {
expect(() => transformCss([['text-shadow', 'red']])).toThrow()
expect(() => transformCss([['text-shadow', '10px red']])).toThrow()
})
|
Clean local db and webapp references
|
package org.openmrs.reference.page;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class TestProperties {
private Properties properties;
public TestProperties() {
properties = new Properties();
try {
InputStream input = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("org/openmrs/reference/test.properties");
properties.load(new InputStreamReader(input, "UTF-8"));
}
catch (IOException ioException) {
throw new RuntimeException("test.properties not found. Error: ", ioException);
}
}
public String getWebAppUrl() {
return properties.getProperty("webapp.url");
}
}
|
package org.openmrs.reference.page;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class TestProperties {
private Properties properties;
public TestProperties() {
properties = new Properties();
try {
InputStream input = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("org/openmrs/reference/test.properties");
properties.load(new InputStreamReader(input, "UTF-8"));
}
catch (IOException ioException) {
throw new RuntimeException("test.properties not found. Error: ", ioException);
}
}
public String getWebAppUrl() {
return properties.getProperty("webapp.url", "http://localhost:8080/openmrs");
}
public String getDatabaseUrl() {
return properties.getProperty("database.url", "jdbc:mysql://localhost:3306/openmrs");
}
public String getDatabaseUsername() {
return properties.getProperty("database.username", "");
}
public String getDatabasePassword() {
return properties.getProperty("database.password", "");
}
}
|
Update the active class for the current step
|
var GtfsEditor = GtfsEditor || {};
(function(G, $, ich) {
G.Router = Backbone.Router.extend({
routes: {
'': 'showStep',
':step': 'showStep'
},
initialize: function () {
var router = this;
$('#route-nav').on('click', 'a', function (evt) {
evt.preventDefault();
router.navigate($(this).attr('href'), {trigger: true});
});
},
showStep: function (step) {
if (!step) {
step = '1';
this.navigate(step);
}
$('#route-nav li').removeClass('active').find('a[href="'+step+'"]').parent().addClass('active');
$('#route-step-content').html('This is step ' + step);
}
});
})(GtfsEditor, jQuery, ich);
var router;
$(function(){
router = new GtfsEditor.Router();
Backbone.history.start({pushState: true, root: '/route/'});
});
|
var GtfsEditor = GtfsEditor || {};
(function(G, $, ich) {
G.Router = Backbone.Router.extend({
routes: {
'': 'showStep',
':step': 'showStep'
},
initialize: function () {
var router = this;
$('#route-nav').on('click', 'a', function (evt) {
evt.preventDefault();
router.navigate($(this).attr('href'), {trigger: true});
});
},
showStep: function (step) {
if (!step) {
step = '1';
this.navigate(step);
}
$('#route-step-content').html('This is step ' + step);
}
});
})(GtfsEditor, jQuery, ich);
var router;
$(function(){
router = new GtfsEditor.Router();
Backbone.history.start({pushState: true, root: '/route/'});
});
|
Fix outdated command line help
|
import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import DataUse, def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn():
adder = FlagAdder()
for use in DataUse:
use = use.value
adder.add_flag("{}_steps".format(use), type=int,
help="Maximum number of {} steps".format(use))
adder.add_flag("min_eval_frequency", type=int, default=1,
help="Minimum evaluation frequency in number of model "
"savings")
estimator = def_estimator()
def_train_input_fn = def_def_train_input_fn()
def_eval_input_fn = def_def_eval_input_fn()
def def_experiment_fn(model_fn, input_fn):
def experiment_fn(output_dir):
return tf.contrib.learn.Experiment(
estimator(model_fn, output_dir),
def_train_input_fn(input_fn),
def_eval_input_fn(input_fn),
**{arg: getattr(FLAGS, arg) for arg in adder.flags})
return experiment_fn
return def_experiment_fn
|
import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn
from .inputs import def_def_eval_input_fn
def def_def_experiment_fn():
adder = FlagAdder()
works_with = lambda name: "Works only with {}".format(name)
train_help = works_with("qnd.train_and_evaluate()")
adder.add_flag("train_steps", type=int, help=train_help)
adder.add_flag("eval_steps", type=int, help=works_with("qnd.evaluate()"))
adder.add_flag("min_eval_frequency", type=int, default=1, help=train_help)
estimator = def_estimator()
def_train_input_fn = def_def_train_input_fn()
def_eval_input_fn = def_def_eval_input_fn()
def def_experiment_fn(model_fn, input_fn):
def experiment_fn(output_dir):
return tf.contrib.learn.Experiment(
estimator(model_fn, output_dir),
def_train_input_fn(input_fn),
def_eval_input_fn(input_fn),
**{arg: getattr(FLAGS, arg) for arg in adder.flags})
return experiment_fn
return def_experiment_fn
|
Add string as a possible prop type
|
import React, { Fragment, PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';
class Link extends PureComponent {
render() {
const { children, className, icon, iconPlacement, element, inherit, ...others } = this.props;
const classNames = cx(
theme['link'],
{
[theme['inherit']]: inherit,
},
className,
);
const ChildrenWrapper = icon ? 'span' : Fragment;
const Element = element;
return (
<Element className={classNames} data-teamleader-ui="link" {...others}>
{icon && iconPlacement === 'left' && icon}
<ChildrenWrapper>{children}</ChildrenWrapper>
{icon && iconPlacement === 'right' && icon}
</Element>
);
}
}
Link.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string,
/** The icon displayed inside the button. */
icon: PropTypes.element,
/** The position of the icon inside the button. */
iconPlacement: PropTypes.oneOf(['left', 'right']),
inherit: PropTypes.bool,
element: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
};
Link.defaultProps = {
className: '',
element: 'a',
inherit: true,
};
export default Link;
|
import React, { Fragment, PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';
class Link extends PureComponent {
render() {
const { children, className, icon, iconPlacement, element, inherit, ...others } = this.props;
const classNames = cx(
theme['link'],
{
[theme['inherit']]: inherit,
},
className,
);
const ChildrenWrapper = icon ? 'span' : Fragment;
const Element = element;
return (
<Element className={classNames} data-teamleader-ui="link" {...others}>
{icon && iconPlacement === 'left' && icon}
<ChildrenWrapper>{children}</ChildrenWrapper>
{icon && iconPlacement === 'right' && icon}
</Element>
);
}
}
Link.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string,
/** The icon displayed inside the button. */
icon: PropTypes.element,
/** The position of the icon inside the button. */
iconPlacement: PropTypes.oneOf(['left', 'right']),
inherit: PropTypes.bool,
element: PropTypes.element,
};
Link.defaultProps = {
className: '',
element: 'a',
inherit: true,
};
export default Link;
|
Order filter for report page
|
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(request, days):
print(request.user.is_staff)
if not request.user.is_staff:
return ""
d = datetime.datetime.now() - datetime.timedelta(days=int(days))
organisations = Organisation.objects.filter(
active=True).filter(created_at__gte=d)
workshops = Workshop.objects.filter(
is_active=True).filter(
expected_date__gte=d).filter(
expected_date__lt=datetime.datetime.now()).filter(
status__in=[WorkshopStatus.COMPLETED,
WorkshopStatus.FEEDBACK_PENDING]).order_by('expected_date')
profiles = Profile.objects.filter(user__date_joined__gte=d)
no_of_participants = sum([w.no_of_participants for w in workshops])
template_name = 'reports/index.html'
context_dict = {}
context_dict['organisations'] = organisations
context_dict['workshops'] = workshops
context_dict['profiles'] = profiles
context_dict['no_of_participants'] = no_of_participants
context_dict['date'] = d
workshops = Workshop.objects.filter(
is_active=True)
return render(request, template_name, context_dict)
|
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(request, days):
print(request.user.is_staff)
if not request.user.is_staff:
return ""
d = datetime.datetime.now() - datetime.timedelta(days=int(days))
organisations = Organisation.objects.filter(
active=True).filter(created_at__gte=d)
workshops = Workshop.objects.filter(
is_active=True).filter(
expected_date__gte=d).filter(
expected_date__lt=datetime.datetime.now()).filter(
status__in=[WorkshopStatus.COMPLETED,
WorkshopStatus.FEEDBACK_PENDING])
profiles = Profile.objects.filter(user__date_joined__gte=d)
no_of_participants = sum([w.no_of_participants for w in workshops])
template_name = 'reports/index.html'
context_dict = {}
context_dict['organisations'] = organisations
context_dict['workshops'] = workshops
context_dict['profiles'] = profiles
context_dict['no_of_participants'] = no_of_participants
context_dict['date'] = d
workshops = Workshop.objects.filter(
is_active=True)
return render(request, template_name, context_dict)
|
Add missing dependency for tastypie
|
from setuptools import setup, find_packages
from gcm import VERSION
setup(
name='django-gcm',
version=VERSION,
description='Google Cloud Messaging Server',
author='Adam Bogdal',
author_email='adam@bogdal.pl',
url='https://github.com/bogdal/django-gcm',
download_url='https://github.com/bogdal/django-gcm/zipball/master',
packages=find_packages(),
package_data={
'gcm': ['locale/*/LC_MESSAGES/*']
},
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities'],
zip_safe=False,
install_requires=[
'django>=1.5',
'django-tastypie>=0.9.13',
'python-mimeparse>=0.1.4',
'pytz==2013.8',
'requests>=1.2.0',
],
)
|
from setuptools import setup, find_packages
from gcm import VERSION
setup(
name='django-gcm',
version=VERSION,
description='Google Cloud Messaging Server',
author='Adam Bogdal',
author_email='adam@bogdal.pl',
url='https://github.com/bogdal/django-gcm',
download_url='https://github.com/bogdal/django-gcm/zipball/master',
packages=find_packages(),
package_data={
'gcm': ['locale/*/LC_MESSAGES/*']
},
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities'],
zip_safe=False,
install_requires=[
'django>=1.5',
'django-tastypie>=0.9.13',
'pytz==2013.8',
'requests>=1.2.0',
],
)
|
Remove stupid South thing that is messing up Heroku
remove, I say!!
|
#!/usr/bin/env python
# This manage.py exists for the purpose of creating migrations
import sys
import django
from django.conf import settings
settings.configure(
ROOT_URLCONF='',
DATABASES={'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}},
PAYPAL_RECEIVER_EMAIL='',
PAYPAL_IDENTITY_TOKEN='',
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'paypal.pro',
'paypal.standard',
'paypal.standard.ipn',
'paypal.standard.pdt',
],
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
'TIMEOUT': 0,
'KEY_PREFIX': 'paypal_tests_',
}
},
MIDDLEWARE_CLASSES=[],
)
from django.core.management import execute_from_command_line
if __name__ == '__main__':
execute_from_command_line(sys.argv)
|
#!/usr/bin/env python
# This manage.py exists for the purpose of creating migrations
import sys
import django
from django.conf import settings
settings.configure(
ROOT_URLCONF='',
DATABASES={'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}},
PAYPAL_RECEIVER_EMAIL='',
PAYPAL_IDENTITY_TOKEN='',
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'paypal.pro',
'paypal.standard',
'paypal.standard.ipn',
'paypal.standard.pdt',
] + (['south'] if django.VERSION < (1,7) else []),
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
'TIMEOUT': 0,
'KEY_PREFIX': 'paypal_tests_',
}
},
MIDDLEWARE_CLASSES=[],
)
from django.core.management import execute_from_command_line
if __name__ == '__main__':
execute_from_command_line(sys.argv)
|
Change the default logging level to error
|
import logging
import click
from detectem.response import get_har
from detectem.plugin import load_plugins
from detectem.core import Detector
# Set up logging
logger = logging.getLogger('detectem')
ch = logging.StreamHandler()
logger.setLevel(logging.ERROR)
logger.addHandler(ch)
@click.command()
@click.option(
'--debug',
default=False,
is_flag=True,
help='Include this flag to enable debug messages.'
)
@click.option(
'--format',
default=None,
type=click.Choice(['json']),
help='Set the format of the results.'
)
@click.option(
'--metadata',
default=False,
is_flag=True,
help='Include this flag to return plugin metadata.'
)
@click.argument('url')
def main(debug, format, metadata, url):
if debug:
click.echo("[+] Enabling debug mode.")
ch.setLevel(logging.DEBUG)
else:
ch.setLevel(logging.ERROR)
print(get_detection_results(url, format, metadata))
def get_detection_results(url, format, metadata):
har_data = get_har(url)
plugins = load_plugins()
det = Detector(har_data, plugins, url)
det.start_detection()
return det.get_results(format=format, metadata=metadata)
if __name__ == "__main__":
main()
|
import logging
import click
from detectem.response import get_har
from detectem.plugin import load_plugins
from detectem.core import Detector
# Set up logging
logger = logging.getLogger('detectem')
ch = logging.StreamHandler()
logger.setLevel(logging.DEBUG)
logger.addHandler(ch)
@click.command()
@click.option(
'--debug',
default=False,
is_flag=True,
help='Include this flag to enable debug messages.'
)
@click.option(
'--format',
default=None,
type=click.Choice(['json']),
help='Set the format of the results.'
)
@click.option(
'--metadata',
default=False,
is_flag=True,
help='Include this flag to return plugin metadata.'
)
@click.argument('url')
def main(debug, format, metadata, url):
if debug:
click.echo("[+] Enabling debug mode.")
ch.setLevel(logging.DEBUG)
else:
ch.setLevel(logging.ERROR)
print(get_detection_results(url, format, metadata))
def get_detection_results(url, format, metadata):
har_data = get_har(url)
plugins = load_plugins()
det = Detector(har_data, plugins, url)
det.start_detection()
return det.get_results(format=format, metadata=metadata)
if __name__ == "__main__":
main()
|
Store new user instead of just id
|
<?php
namespace BasicUser\Model\Form;
use Solleer\User\{User, SigninStatus};
class Signup implements \MVC\Model\Form {
private $model;
private $status;
public $successful = false;
public $submitted = false;
public $newUser;
public function __construct(User $model, SigninStatus $status) {
$this->model = $model;
$this->status = $status;
}
public function main($data) {
$this->submitted = false;
return true;
}
public function submit($data) {
$this->submitted = true;
if ($data['password'] !== $data['password_confirm']) return false;
$this->newUser = $this->model->save($data);
return $this->newUser !== false;
}
public function success() {
$this->status->setSigninID($this->newUser->id);
$this->successful = true;
}
}
|
<?php
namespace BasicUser\Model\Form;
use Solleer\User\{User, SigninStatus};
class Signup implements \MVC\Model\Form {
private $model;
private $status;
public $successful = false;
public $submitted = false;
public $newId;
public function __construct(User $model, SigninStatus $status) {
$this->model = $model;
$this->status = $status;
$this->code = $code;
}
public function main($data) {
$this->submitted = false;
return true;
}
public function submit($data) {
$this->submitted = true;
if ($data['password'] !== $data['password_confirm']) return false;
$this->newId = $this->model->save($data)->id;
return $this->newId !== false;
}
public function success() {
$this->status->setSigninID($this->newId);
$this->successful = true;
}
}
|
Fix instagram script on feed
|
(function () {
'use strict';
window.scrollTo(0, document.body.scrollHeight);
var likeElements = document.querySelectorAll(".coreSpriteLikeHeartOpen");
var likeCount = 0;
var nextTime = 1000;
function doLike(photo) {
photo.click();
}
likeElements.forEach(photo => {
nextTime = Math.random() * (14000 - 4000) + 4000;
console.log(nextTime);
console.log("Like: " + likeCount);
likeCount++;
if (likeCount > 5) {
console.log("too much liking !");
return
} else {
setTimeout(doLike(photo), nextTime);
}
});
})();
|
(function () {
'use strict';
window.scrollTo(0, document.body.scrollHeight);
var likeElements = document.querySelectorAll(".coreSpriteHeartOpen");
var likeCount = 0;
var nextTime = 1000;
function doLike(i) {
likeElements[i].click();
}
for (var i = 0; i < likeElements.length; i++) {
nextTime = Math.random() * (14000 - 4000) + 4000;
console.log(nextTime);
console.log("Like: " + likeCount);
likeCount++;
if (likeCount > 10) {
console.log("too much liking !");
break;
} else {
setTimeout(doLike(i), nextTime);
}
}
})();
|
Fix distinct asset in the basket.
|
"use strict";
(function () {
angular
.module("conpa")
.factory("basketService", basketService);
function basketService() {
var assets = [],
service = {
getAssets: getAssets,
addAsset: addAsset
};
return service;
function getAssets() {
return assets;
}
function addAsset(item) {
var isNew;
if (!item) {
return;
}
isNew = assets.filter(function (asset) {
if (item.symbol === asset.symbol) {
return asset;
}
}).length === 0;
if (isNew) {
assets.push(item);
}
}
}
}());
|
"use strict";
(function () {
angular
.module("conpa")
.factory("basketService", basketService);
function basketService() {
var assets = [],
service = {
getAssets: getAssets,
addAsset: addAsset
};
return service;
function getAssets() {
return assets;
}
function addAsset(item) {
var isNew;
if (!item) {
return;
}
isNew = assets.filter(function (asset) {
if (item.name === asset.name) {
return asset;
}
}).length === 0;
if (isNew) {
assets.push(item);
}
}
}
}());
|
Change server port to 4000
|
'use strict';
module.exports = {
'serverport': 4000,
'styles': {
'src' : 'app/styles/**/*.scss',
'dest': 'build/css'
},
'scripts': {
'src' : 'app/js/**/*.js',
'dest': 'build/js'
},
'images': {
'src' : 'app/images/**/*',
'dest': 'build/images'
},
'views': {
'watch': [
'app/index.html',
'app/views/**/*.html'
],
'src': 'app/views/**/*.html',
'dest': 'app/js'
},
'dist': {
'root' : 'build'
},
'browserify': {
'entries' : ['./app/js/main.js'],
'bundleName': 'main.js',
'sourcemap' : true
},
'test': {
'karma': 'test/karma.conf.js',
'protractor': 'test/protractor.conf.js'
}
};
|
'use strict';
module.exports = {
'serverport': 3000,
'styles': {
'src' : 'app/styles/**/*.scss',
'dest': 'build/css'
},
'scripts': {
'src' : 'app/js/**/*.js',
'dest': 'build/js'
},
'images': {
'src' : 'app/images/**/*',
'dest': 'build/images'
},
'views': {
'watch': [
'app/index.html',
'app/views/**/*.html'
],
'src': 'app/views/**/*.html',
'dest': 'app/js'
},
'dist': {
'root' : 'build'
},
'browserify': {
'entries' : ['./app/js/main.js'],
'bundleName': 'main.js',
'sourcemap' : true
},
'test': {
'karma': 'test/karma.conf.js',
'protractor': 'test/protractor.conf.js'
}
};
|
Check AuthToken header if empty before query database
|
package middlewares
import (
"net/http"
"time"
"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gin-gonic/gin"
"github.com/freeusd/solebtc/errors"
"github.com/freeusd/solebtc/models"
)
type authRequiredDependencyGetAuthToken func(authTokenString string) (models.AuthToken, *errors.Error)
// AuthRequired checks if user is authorized
func AuthRequired(
getAuthToken authRequiredDependencyGetAuthToken,
authTokenLifetime time.Duration,
) gin.HandlerFunc {
return func(c *gin.Context) {
authTokenHeader := c.Request.Header.Get("Auth-Token")
if authTokenHeader == "" {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
authToken, err := getAuthToken(authTokenHeader)
if err != nil && err.ErrCode != errors.ErrCodeNotFound {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if authToken.CreatedAt.Add(authTokenLifetime).Before(time.Now()) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Set("auth_token", authToken)
c.Next()
}
}
|
package middlewares
import (
"net/http"
"time"
"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gin-gonic/gin"
"github.com/freeusd/solebtc/errors"
"github.com/freeusd/solebtc/models"
)
type authRequiredDependencyGetAuthToken func(authTokenString string) (models.AuthToken, *errors.Error)
// AuthRequired checks if user is authorized
func AuthRequired(
getAuthToken authRequiredDependencyGetAuthToken,
authTokenLifetime time.Duration,
) gin.HandlerFunc {
return func(c *gin.Context) {
authToken, err := getAuthToken(c.Request.Header.Get("Auth-Token"))
if err != nil && err.ErrCode != errors.ErrCodeNotFound {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if authToken.CreatedAt.Add(authTokenLifetime).Before(time.Now()) {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Set("auth_token", authToken)
c.Next()
}
}
|
Fix new form confirm code
@atfornes please note that this code is common for the + buttons
of project and community
Fixes #249
|
'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window', '$rootScope',
function($location, $window, $rootScope) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
scope[objectName].delete();
$location.search('form', undefined);
$window.history.back();
},
confirmNew () {
$location.search('form', undefined);
// TODO fix with community invite
if (objectName === 'project') {
scope.invite.selected.forEach(function(i){
scope.project.addContributor(i);
});
}
$rootScope.$broadcast('teem.' + objectName + '.join');
}
};
function initialize(s, o) {
scope = s;
objectName = o;
Object.assign(scope, scopeFn);
}
return {
initialize
};
}]);
|
'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window', '$rootScope',
function($location, $window, $rootScope) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
scope[objectName].delete();
$location.search('form', undefined);
$window.history.back();
},
confirmNew () {
$location.search('form', undefined);
scope.invite.selected.forEach(function(i){
scope.project.addContributor(i);
});
$rootScope.$broadcast('teem.project.join');
}
};
function initialize(s, o) {
scope = s;
objectName = o;
Object.assign(scope, scopeFn);
}
return {
initialize
};
}]);
|
Add some prints to improve verbosity
|
"""
Main script to execute the gesture recognition software.
"""
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
print('Is face detected? ', face.face_detected)
if face.face_detected:
print("Enabled Gesture Recognition")
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
print('Disabled Gesture Recognition')
return
if __name__ == "__main__":
while True:
run_step()
|
"""
Main script to execute the gesture recognition software.
"""
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
print face.face_detected
if face.face_detected:
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
return
if __name__ == "__main__":
while True:
run_step()
|
Update upstream version of vo
|
from distutils.core import Extension
from os.path import join
from astropy import setup_helpers
def get_extensions(build_type='release'):
VO_DIR = 'astropy/io/vo/src'
return [Extension(
"astropy.io.vo.tablewriter",
[join(VO_DIR, "tablewriter.c")],
include_dirs=[VO_DIR])]
def get_package_data():
return {
'astropy.io.vo': [
'data/ucd1p-words.txt', 'data/*.xsd', 'data/*.dtd'],
'astropy.io.vo.tests': [
'data/*.xml', 'data/*.gz', 'data/*.json', 'data/*.fits',
'data/*.txt'],
'astropy.io.vo.validator': [
'urls/*.dat.gz']}
def get_legacy_alias():
return setup_helpers.add_legacy_alias(
'vo', 'astropy.io.vo', '0.8')
|
from distutils.core import Extension
from os.path import join
from astropy import setup_helpers
def get_extensions(build_type='release'):
VO_DIR = 'astropy/io/vo/src'
return [Extension(
"astropy.io.vo.tablewriter",
[join(VO_DIR, "tablewriter.c")],
include_dirs=[VO_DIR])]
def get_package_data():
return {
'astropy.io.vo': [
'data/ucd1p-words.txt', 'data/*.xsd', 'data/*.dtd'],
'astropy.io.vo.tests': [
'data/*.xml', 'data/*.gz', 'data/*.json', 'data/*.fits',
'data/*.txt'],
'astropy.io.vo.validator': [
'urls/*.dat.gz']}
def get_legacy_alias():
return setup_helpers.add_legacy_alias(
'vo', 'astropy.io.vo', '0.7.2')
|
New: Return child from execute method
|
const spawn = require('child_process').spawn;
const reorder = require('./lib/reorder');
exports.needed = function needed (flags, argv) {
var shouldRespawn = false;
if (!argv) {
argv = process.argv;
}
return (JSON.stringify(argv) !== JSON.stringify(reorder(flags, argv)));
};
exports.execute = function execute (flags, argv) {
if (!flags) {
throw new Error('You must specify flags to respawn with.');
}
if (!argv) {
argv = process.argv;
}
var args = reorder(flags, argv);
var child = spawn(args[0], args.slice(1));
child.on('exit', function (code, signal) {
process.on('exit', function () {
if (signal) {
process.kill(process.pid, signal);
} else {
process.exit(code);
}
});
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
return child;
};
|
const spawn = require('child_process').spawn;
const reorder = require('./lib/reorder');
exports.needed = function needed (flags, argv) {
var shouldRespawn = false;
if (!argv) {
argv = process.argv;
}
return (JSON.stringify(argv) !== JSON.stringify(reorder(flags, argv)));
};
exports.execute = function execute (flags, argv) {
if (!flags) {
throw new Error('You must specify flags to respawn with.');
}
if (!argv) {
argv = process.argv;
}
var args = reorder(flags, argv);
child = spawn(args[0], args.slice(1));
child.on('exit', function (code, signal) {
process.on('exit', function () {
if (signal) {
process.kill(process.pid, signal);
} else {
process.exit(code);
}
});
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
};
|
Add a broader set of events for inline event handler rewrite function
|
opera.isReady(function() {
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'beforeunload', 'unload', 'click', 'dblclick', 'mouseover', 'mousemove',
'mousedown', 'mouseup', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i < l; i++) {
var els = document.querySelectorAll('[on' + selectors[i] + ']');
for(var j = 0, k = els.length; j < k; j++) {
var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
var target = els[j];
if(selectors[i].indexOf('load') > -1 && els[j] === document.body) {
target = window;
}
els[j].removeAttribute('on' + selectors[i]);
target.addEventListener(selectors[i], fn, true);
}
}
}, false);
});
|
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'click', 'mouseover', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i < l; i++) {
var els = document.querySelectorAll('[on' + selectors[i] + ']');
for(var j = 0, k = els.length; j < k; j++) {
var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
var target = els[j];
if(selectors[i] === 'load' && els[j] === document.body) {
target = window;
}
els[j].removeAttribute('on' + selectors[i]);
target.addEventListener(selectors[i], fn, true);
}
}
}, false);
|
Configure anti-spam form type constraints.
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;
/**
* Anti-spam form type
*/
class AntiSpamType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'attr' => array(
'class' => 'title_field',
),
'constraints' => new Blank(),
'mapped' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'text';
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'darvin_utils_anti_spam';
}
}
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Anti-spam form type
*/
class AntiSpamType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'attr' => array(
'class' => 'title_field',
),
'mapped' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'text';
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'darvin_utils_anti_spam';
}
}
|
Move structure to a separate directory
|
import countershape
from countershape import Page, Directory, PythonModule
import countershape.grok
this.layout = countershape.Layout("_layout.html")
this.markdown = "rst"
ns.docTitle = "Countershape Manual"
ns.docMaintainer = "Aldo Cortesi"
ns.docMaintainerEmail = "dev@nullcube.com"
ns.copyright = "Copyright Nullcube 2007"
ns.head = countershape.template.File(None, "_banner.html")
ns.sidebar = countershape.widgets.SiblingPageIndex(
'/index.html',
exclude=['countershape']
)
ns.parse = countershape.grok.parse("../countershape")
pages = [
Page("index.html", "Introduction"),
Page("structure/structure.html", "Document Structure"),
Directory("structure"),
Page("doc.html", "Documenting Code"),
Page("api/apiref.html", "API Reference"),
Directory("api"),
PythonModule("../countershape", "Source"),
Page("admin.html", "Administrivia")
]
ns.imgBanner = countershape.html.IMG(
src=countershape.model.UrlTo("countershape.png"),
width="280",
height="77",
align="right"
)
|
import countershape
from countershape import Page, Directory, PythonModule
import countershape.grok
this.layout = countershape.Layout("_layout.html")
this.markdown = "rst"
ns.docTitle = "Countershape Manual"
ns.docMaintainer = "Aldo Cortesi"
ns.docMaintainerEmail = "dev@nullcube.com"
ns.copyright = "Copyright Nullcube 2007"
ns.head = countershape.template.File(None, "_banner.html")
ns.sidebar = countershape.widgets.SiblingPageIndex(
'/index.html',
exclude=['countershape']
)
ns.parse = countershape.grok.parse("../countershape")
pages = [
Page("index.html", "Introduction"),
Page("structure.html", "Document Structure"),
Page("doc.html", "Documenting Code"),
Page("api/apiref.html", "API Reference"),
Directory("api"),
PythonModule("../countershape", "Source"),
Page("admin.html", "Administrivia")
]
ns.imgBanner = countershape.html.IMG(
src=countershape.model.UrlTo("countershape.png"),
width="280",
height="77",
align="right"
)
|
Update @ Sat Mar 11 2017 17:01:59 GMT+0800 (CST)
|
const { exec } = require('child_process')
const ora = require('ora')
const config = require('../config')
const spinner = ora('Deploy to gh-pages...')
spinner.start()
function execute (cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err) return reject(err)
if (stderr) return reject(stderr)
resolve(stdout)
})
})
}
console.log(config.paths.output)
execute(`cd ${config.paths.output}`)
.then(stdout => {
execute('pwd').then(s => console.log(s.toString()))
return execute('git add --all')
})
.then(stdout => {
return execute(`git commit -m 'Update @ ${new Date}'`)
})
.then(stdout => {
return execute('git push -u origin gh-pages')
})
.then(stdout => {
spinner.stop()
})
.catch(err => {
throw err
spinner.stop()
})
|
const { exec } = require('child_process')
const ora = require('ora')
const config = require('../config')
const spinner = ora('Deploy to gh-pages...')
spinner.start()
function execute (cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err) return reject(err)
if (stderr) return reject(stderr)
resolve(stdout)
})
})
}
execute(`cd ${config.paths.output}`)
.then(stdout => {
execute('pwd').then(s => console.log(s.toString()))
return execute('git add --all')
})
.then(stdout => {
return execute(`git commit -m 'Update @ ${new Date}'`)
})
.then(stdout => {
return execute('git push -u origin gh-pages')
})
.then(stdout => {
spinner.stop()
})
.catch(err => {
throw err
spinner.stop()
})
|
Replace duplicate test with valid address kwarg
|
import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
((), {'address': ADDRESS}, None),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
)
def test_contract_address_validation(web3, args, kwargs, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
web3.eth.contract(*args, **kwargs)
return
# run without errors
web3.eth.contract(*args, **kwargs)
@pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3")
def test_set_contract_factory(web3):
factoryClass = Mock()
web3.eth.setContractFactory(factoryClass)
web3.eth.contract(contract_name='myname')
factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
|
import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
)
def test_contract_address_validation(web3, args, kwargs, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
web3.eth.contract(*args, **kwargs)
return
# run without errors
web3.eth.contract(*args, **kwargs)
@pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3")
def test_set_contract_factory(web3):
factoryClass = Mock()
web3.eth.setContractFactory(factoryClass)
web3.eth.contract(contract_name='myname')
factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
|
Fix style of unoriginal names plugin
|
<?php
$query = Query("SELECT name FROM {$dbpref}users");
$names = array();
while ($name = FetchRow($query))
{
$name = strtolower(preg_replace('/[^a-zA-Z]/', '', $name[0]));
// Name might not use any letters. Skip those.
if ($name)
$names[] = $name;
}
?>
<script>
$(function () {
var names = <?php echo json_encode($names) ?>;
$('#un').change(function () {
var i, length, name = this.value.toLowerCase().replace(/[^a-zA-Z]/g, '');
for (i = 0, length = names.length; i < length; i++) {
if (names[i] === name) {
$('#original').show('fast');
return;
}
}
$('#original').hide('fast');
});
});
</script>
<table class="message margin" id="original" style="display:none">
<tr class="header0"><th>Warning</th></tr>
<tr class="cell0"><td>You should be more original with your user names.</td></tr>
</table>
<?php
require 'pages/register.php';
?>
|
<?php
$query = Query("SELECT name FROM {$dbpref}users");
$names = array();
while ($name = FetchRow($query))
{
$name = strtolower(preg_replace('/[^a-zA-Z]/', '', $name[0]));
// Name might not use any letters. Skip those.
if ($name) {
$names[] = $name;
}
}
?>
<script>
$(function () {
var names = <?php echo json_encode($names) ?>;
$('#un').change(function () {
var i, length, name = this.value.toLowerCase().replace(/[^a-zA-Z]/g, '');
for (i = 0, length = names.length; i < length; i++) {
if (names[i] === name) {
$('#original').show('fast');
return;
}
}
$('#original').hide('fast');
});
});
</script>
<table class="message margin" id="original" style="display:none">
<tr class="header0"><th>Warning</th></tr>
<tr class="cell0"><td>You should be more original with your user names.</td></tr>
</table>
<?php
require 'pages/register.php';
?>
|
Use medium text to store posts summary.
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->mediumText('summary')->nullable();
$table->integer('minutes_read')->nullable();
$table->longText('content');
$table->timestamps();
$table->integer('author_id')->unsigned()->index();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('posts');
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->string('summary')->nullable();
$table->integer('minutes_read')->nullable();
$table->longText('content');
$table->timestamps();
$table->integer('author_id')->unsigned()->index();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('posts');
}
}
|
Add new calculations; still needs work
|
public class ArrayAnalyzerLarge {
public static void main(String[] args) {
ArrayUtil au = new ArrayUtil();
//StopWatch sw = new StopWatch();
int size = 10000000;
int valueSize = 250000001;
for (int i=0; i<11; i++) {
int[] array = au.randomIntArray(size, valueSize);
size += 10000000;
evalArray(array, i);
}
}
private static void evalArray(int[] array, int count) {
StopWatch sw = new StopWatch();
int min = array[0];
int max = array[0];
int average = 0;
sw.reset();
sw.start();
for (int i=0; i<array.length; i++) {
if (array[i] < min) {
min = array[i];
}
if (array[i] > max) {
max = array[i];
}
average += array[i];
}
average = average / array.length;
sw.stop();
System.out.println("[ARRAY #" + count + "] " + "Min: " + min + "; Max: " + max + "; Average: " + average +
"; Elapsed Time: " + sw.getElapsedTime() + " milliseconds");
}
}
|
public class ArrayAnalyzerLarge {
public static void main(String[] args) {
ArrayUtil au = new ArrayUtil();
StopWatch sw = new StopWatch();
int min = 999999999;
int max = 0;
int average = 0;
int[] mainArray = createArray(10, 10000000);
au.print(mainArray);
sw.reset();
sw.start();
for (int i=0; i<mainArray.length; i++) {
if (mainArray[i] < min) {
min = mainArray[i];
}
if (mainArray[i] > max) {
max = mainArray[i];
}
average += mainArray[i];
}
average = average / mainArray.length;
sw.stop();
System.out.println("The minimum value is " + min + ".");
System.out.println("The maximum value is " + max + ".");
System.out.println("The average is " + average + ".");
System.out.println("Elapsed Time: " + sw.getElapsedTime() + " milliseconds");
}
private static int[] createArray(int size, int increment) {
int[] returnArray = new int[size];
for (int i=0; i < size; i++) {
returnArray[i] = (int)((Math.random() * increment));
increment += increment;
}
return returnArray;
}
}
|
Add tests for setting prefix
|
import { expect } from 'chai';
import { Tags, addOrRemoveTag, pre, mac } from '../extra-keys';
// see: https://github.com/mochajs/mocha/issues/1847
const { describe, it } = global;
describe('Markdown/extra-keys', () => {
it('should add tags to a selection', () => {
const result = addOrRemoveTag(Tags.STRONG, 'foo');
expect(result).to.equal('**foo**');
});
it('should remove tags when a selection already has the tags', () => {
const result = addOrRemoveTag(Tags.STRONG, '**foo**');
expect(result).to.equal('foo');
});
it('should not remove tags that are not the same', () => {
const result = addOrRemoveTag(Tags.ITALIC, '**foo**');
expect(result).to.equal('_**foo**_');
});
it('should not remove tags that are not the same (2)', () => {
const result = addOrRemoveTag(Tags.STRONG, '*foo*');
expect(result).to.equal('***foo***');
});
it('should handle multiline strings', () => {
const content = `**Hello
This should not be strong**`;
const result = addOrRemoveTag(Tags.STRONG, content);
expect(result).to.equal('Hello\nThis should not be strong');
});
it('should properly set shortcut prefix', () => {
if (!mac) {
expect(pre).to.equal('Ctrl-');
} else {
expect(pre).to.equal('Cmd-');
}
});
});
|
import { expect } from 'chai';
import { Tags, addOrRemoveTag } from '../extra-keys';
// see: https://github.com/mochajs/mocha/issues/1847
const { describe, it } = global;
describe('Markdown/extra-keys', () => {
it('should add tags to a selection', () => {
const result = addOrRemoveTag(Tags.STRONG, 'foo');
expect(result).to.equal('**foo**');
});
it('should remove tags when a selection already has the tags', () => {
const result = addOrRemoveTag(Tags.STRONG, '**foo**');
expect(result).to.equal('foo');
});
it('should not remove tags that are not the same', () => {
const result = addOrRemoveTag(Tags.ITALIC, '**foo**');
expect(result).to.equal('_**foo**_');
});
it('should not remove tags that are not the same (2)', () => {
const result = addOrRemoveTag(Tags.STRONG, '*foo*');
expect(result).to.equal('***foo***');
});
it('should handle multiline strings', () => {
const content = `**Hello
This should not be strong**`;
const result = addOrRemoveTag(Tags.STRONG, content);
expect(result).to.equal('Hello\nThis should not be strong');
});
});
|
Make file uploading return more descriptive error messages.
|
<?php
/**
* @author marcus@silverstripe.com.au
* @license BSD License http://silverstripe.org/bsd-license/
*/
class FileUploadTask extends ScavengerTask {
public function updateTaskFields(FieldList $fields) {
$fields->push(new FileField('File', 'Upload file'));
}
public function processSubmission($data) {
if(!isset($data['File']['tmp_name'])) {
return 'Please select a file to upload';
}
$upload = new Upload();
$upload->load($data['File']);
if($upload->isError()) {
return sprintf(
'Upload could not be saved: %s.',
implode(', ', $upload->getErrors())
);
}
if(!$file = $upload->getFile()) {
return 'Upload could not be saved, please try again.';
}
$response = $this->newResponse('TaskResponseFileUpload');
$response->Response = $file->getAbsoluteURL();
$response->UploadedFileID = $file->ID;
$response->Status = 'Pending';
$response->write();
return $response;
}
}
|
<?php
/**
* @author marcus@silverstripe.com.au
* @license BSD License http://silverstripe.org/bsd-license/
*/
class FileUploadTask extends ScavengerTask {
public function updateTaskFields(FieldList $fields) {
$fields->push(new FileField('File', 'Upload file'));
}
public function processSubmission($data) {
if (isset($data['File']) && isset($data['File']['tmp_name'])) {
$upload = new Upload();
if ($upload->load($data['File'])) {
$file = $upload->getFile();
if ($file->ID) {
$response = $this->newResponse('TaskResponseFileUpload');
$response->Response = $file->getAbsoluteURL();
$response->UploadedFileID = $file->ID;
$response->Status = 'Pending';
$response->write();
return $response;
}
}
}
return 'Upload could not be saved, please try again';
}
}
|
Install console script only in Py2.x.
|
from distutils.util import convert_path
import re
from setuptools import setup
import sys
def get_version():
with open(convert_path('cinspect/__init__.py')) as f:
metadata = dict(re.findall("__([a-z]+)__\s*=\s*'([^']+)'", f.read()))
return metadata.get('version', '0.1')
def get_long_description():
with open('README.md') as f:
return f.read()
packages = [
'cinspect',
'cinspect.index',
'cinspect.tests',
]
package_data = {'cinspect.tests': ['data/*.py']}
entry_points = {}
if sys.version_info.major == 2:
packages.extend([
'cinspect.vendor.clang',
])
package_data['cinspect.tests'] += ['data/*.md', 'data/*.c']
entry_points = {
"console_scripts": [
"cinspect-index = cinspect.index.writer:main",
],
}
setup(
name="cinspect",
author="Puneeth Chaganti",
author_email="punchagan@muse-amuse.in",
version=get_version(),
long_description=get_long_description(),
url = "https://github.com/punchagan/cinspect",
license="BSD",
description = "C-source introspection for packages.",
packages = packages,
package_data=package_data,
entry_points=entry_points,
)
|
from distutils.util import convert_path
import re
from setuptools import setup
import sys
def get_version():
with open(convert_path('cinspect/__init__.py')) as f:
metadata = dict(re.findall("__([a-z]+)__\s*=\s*'([^']+)'", f.read()))
return metadata.get('version', '0.1')
def get_long_description():
with open('README.md') as f:
return f.read()
packages = [
'cinspect',
'cinspect.index',
'cinspect.tests',
]
package_data = {'cinspect.tests': ['data/*.py']}
if sys.version_info.major == 2:
packages.extend([
'cinspect.vendor.clang',
])
package_data['cinspect.tests'] += ['data/*.md', 'data/*.c']
setup(
name="cinspect",
author="Puneeth Chaganti",
author_email="punchagan@muse-amuse.in",
version=get_version(),
long_description=get_long_description(),
url = "https://github.com/punchagan/cinspect",
license="BSD",
description = "C-source introspection for packages.",
packages = packages,
package_data=package_data,
entry_points = {
"console_scripts": [
"cinspect-index = cinspect.index.writer:main",
],
},
)
|
Fix revision numbers in migration 0177
|
"""
Revision ID: 0177_add_virus_scan_statuses
Revises: 0176_alter_billing_columns
Create Date: 2018-02-21 14:05:04.448977
"""
from alembic import op
revision = '0177_add_virus_scan_statuses'
down_revision = '0176_alter_billing_columns'
def upgrade():
op.execute("INSERT INTO notification_status_types (name) VALUES ('pending-virus-check')")
op.execute("INSERT INTO notification_status_types (name) VALUES ('virus-scan-failed')")
def downgrade():
op.execute("UPDATE notifications SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'")
op.execute("UPDATE notification_history SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'")
op.execute("UPDATE notifications SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'")
op.execute("UPDATE notification_history SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'")
op.execute("DELETE FROM notification_status_types WHERE name in ('pending-virus-check', 'virus-scan-failed')")
|
"""
Revision ID: 0177_add_virus_scan_statuses
Revises: 0176_alter_billing_columns
Create Date: 2018-02-21 14:05:04.448977
"""
from alembic import op
revision = '0176_alter_billing_columns'
down_revision = '0175_drop_job_statistics_table'
def upgrade():
op.execute("INSERT INTO notification_status_types (name) VALUES ('pending-virus-check')")
op.execute("INSERT INTO notification_status_types (name) VALUES ('virus-scan-failed')")
def downgrade():
op.execute("UPDATE notifications SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'")
op.execute("UPDATE notification_history SET notification_status = 'created' WHERE notification_status = 'pending-virus-check'")
op.execute("UPDATE notifications SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'")
op.execute("UPDATE notification_history SET notification_status = 'permanent-failure' WHERE notification_status = 'virus-scan-failed'")
op.execute("DELETE FROM notification_status_types WHERE name in ('pending-virus-check', 'virus-scan-failed')")
|
Fix path for test logs
|
<?php
namespace ApiTest;
use Zend\Json\Json;
class JsonFileIterator extends \GlobIterator
{
/**
* Override parent to force pattern for JSON file
* @param string $path
*/
public function __construct($path)
{
$path = $path . '/*.json';
parent::__construct($path, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO);
}
/**
* Override pattern to return an array instead of FileInfo.
* @return array [url parameters, expected json, optional message]
*/
public function current()
{
$file = parent::current();
@list($params, $message) = explode('#', str_replace('.json', '', $file->getFilename()));
$fullpath = getcwd() . '/data/logs/' . $file->getPath() . '/';
`rm -rf $fullpath`;
@mkdir($fullpath, 0777, true);
$json = file_get_contents($file->getPathname());
$result = [
$params,
$json,
$message,
$fullpath . $file->getFilename(),
];
return $result;
}
}
|
<?php
namespace ApiTest;
use Zend\Json\Json;
class JsonFileIterator extends \GlobIterator
{
/**
* Override parent to force pattern for JSON file
* @param string $path
*/
public function __construct($path)
{
$path = $path . '/*.json';
parent::__construct($path, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO);
}
/**
* Override pattern to return an array instead of FileInfo.
* @return array [url parameters, expected json, optional message]
*/
public function current()
{
$file = parent::current();
@list($params, $message) = explode('#', str_replace('.json', '', $file->getFilename()));
$fullpath = getcwd() . '/../data/logs/tests/' . $file->getPath() . '/';
`rm -rf $fullpath`;
@mkdir($fullpath, 0777, true);
$json = file_get_contents($file->getPathname());
$result = [
$params,
$json,
$message,
$fullpath . $file->getFilename(),
];
return $result;
}
}
|
:muscle: Structure of data generator iimproved
Structure of dataset generator improved
|
import numpy as np
import os
import sys
import time
from unrealcv import client
class Dataset(object):
def __init__(self,folder,nberOfImages):
self.folder=folder
self.nberOfImages=nberOfImages
self.client.connect()
def scan():
try:
p=self.client.request('vget /camera/0/lit')
a=p.split('/').pop()
p=self.client.request('vget /camera/0/object_mask '+a)
print p
except Exception,e:
print 'Image could not be saved not saved: error occured, '+str(e)
|
import numpy as np
import os
import sys
import time
from unrealcv import client
class Dataset(object):
def __init__(self,folder,nberOfImages):
self.folder=folder
self.nberOfImages=nberOfImages
self.client.connect()
def scan():
try:
p=self.client.request('vget /camera/0/lit')
a=p.split('/').pop()
p=self.client.request('vget /camera/0/object_mask '+a)
print p
except Exception,e:
print 'Image not saved: error occured, '+str(e)
|
Send original Stream in Sync with GetStream
|
package cdp
import (
"fmt"
"github.com/mafredri/cdp/rpcc"
)
type eventClient interface {
rpcc.Stream
}
type getStreamer interface {
GetStream() rpcc.Stream
}
// Sync takes two or more event clients and sets them into synchronous operation,
// relative to each other. This operation cannot be undone. If an error is
// returned this function is no-op and the event clients will continue in
// asynchronous operation.
//
// All event clients must belong to the same connection and they must not be
// closed. Passing multiple clients of the same event type to Sync is not
// supported and will return an error.
//
// An event client that is closed is removed and has no further affect on the
// clients that were synchronized.
//
// When two event clients, A and B, are in sync they will receive events in the
// order of arrival. If an event for both A and B is triggered, in that order,
// it will not be possible to receive the event from B before the event from A
// has been received.
func Sync(c ...eventClient) error {
var s []rpcc.Stream
for _, cc := range c {
cs, ok := cc.(getStreamer)
if !ok {
return fmt.Errorf("cdp: Sync: bad eventClient type: %T", cc)
}
s = append(s, cs.GetStream())
}
return rpcc.Sync(s...)
}
|
package cdp
import (
"github.com/mafredri/cdp/rpcc"
)
type eventClient interface {
rpcc.Stream
}
// Sync takes two or more event clients and sets them into synchronous operation,
// relative to each other. This operation cannot be undone. If an error is
// returned this function is no-op and the event clients will continue in
// asynchronous operation.
//
// All event clients must belong to the same connection and they must not be
// closed. Passing multiple clients of the same event type to Sync is not
// supported and will return an error.
//
// An event client that is closed is removed and has no further affect on the
// clients that were synchronized.
//
// When two event clients, A and B, are in sync they will receive events in the
// order of arrival. If an event for both A and B is triggered, in that order,
// it will not be possible to receive the event from B before the event from A
// has been received.
func Sync(c ...eventClient) error {
var s []rpcc.Stream
for _, cc := range c {
s = append(s, cc)
}
return rpcc.Sync(s...)
}
|
Remove a Rails accent of use subject in favor of Zen of Python: explicit is better than implicit and readbility counts
|
from unittest import TestCase
import numpy as np
import pandas as pd
from rosie.chamber_of_deputies.classifiers import ElectionExpensesClassifier
class TestElectionExpensesClassifier(TestCase):
def setUp(self):
self.dataset = pd.read_csv('rosie/chamber_of_deputies/tests/fixtures/election_expenses_classifier.csv',
dtype={'name': np.str, 'legal_entity': np.str})
self.election_expenser_classifier = ElectionExpensesClassifier()
def test_is_election_company(self):
self.assertEqual(self.election_expenser_classifier.predict(self.dataset)[0], True)
def test_is_not_election_company(self):
self.assertEqual(self.election_expenser_classifier.predict(self.dataset)[1], False)
def test_fit(self):
self.assertEqual(self.election_expenser_classifier.fit(self.dataset), self.election_expenser_classifier)
def test_tranform(self):
self.assertEqual(self.election_expenser_classifier.transform(), self.election_expenser_classifier)
|
from unittest import TestCase
import numpy as np
import pandas as pd
from rosie.chamber_of_deputies.classifiers import ElectionExpensesClassifier
class TestElectionExpensesClassifier(TestCase):
def setUp(self):
self.dataset = pd.read_csv('rosie/chamber_of_deputies/tests/fixtures/election_expenses_classifier.csv',
dtype={'name': np.str, 'legal_entity': np.str})
self.subject = ElectionExpensesClassifier()
def test_is_election_company(self):
self.assertEqual(self.subject.predict(self.dataset)[0], True)
def test_is_not_election_company(self):
self.assertEqual(self.subject.predict(self.dataset)[1], False)
def test_fit(self):
self.assertEqual(self.subject.fit(self.dataset), self.subject)
def test_tranform(self):
self.assertEqual(self.subject.transform(), self.subject)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.