text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add unit test for checking the default behavior.
- IE does not follow specs when clicking a checkbox that is in an indeterminate state
|
$(function () {
'use strict';
QUnit.module('indeterminable.js', {
beforeEach: function () {
this.checkbox = $('<input type="checkbox">');
$('#qunit-fixture').append(this.checkbox);
}
});
QUnit.test('Regular checkbox cannot be set to "indeterminate"', function(assert) {
S(this.checkbox).click(function () {
assert.equal(this.prop('indeterminate'), false, 'Radio button should be checked');
});
});
QUnit.test('Left click sets indeterminate checkbox to "checked"', function(assert) {
this.checkbox.prop('indeterminate', true);
S(this.checkbox).click(function () {
assert.equal(this.prop('checked'), true, 'Checkbox should be checked, according to W3C spec');
});
});
QUnit.test('Left click sets unckecked checkbox to "indeterminate"', function(assert) {
this.checkbox.prop('indeterminable', true);
S(this.checkbox).click(function () {
assert.equal(this.prop('indeterminate'), true, 'Radio button should be checked');
});
});
});
|
$(function () {
'use strict';
QUnit.module('indeterminable.js', {
beforeEach: function () {
this.checkbox = $('<input type="checkbox">');
$('#qunit-fixture').append(this.checkbox);
}
});
QUnit.test('Regular checkbox cannot be set to "indeterminate"', function(assert) {
S(this.checkbox).click(function () {
assert.equal(this.prop('indeterminate'), false, 'Radio button should be checked');
});
});
QUnit.test('Left click sets unckecked checkbox to "indeterminate"', function(assert) {
this.checkbox.prop('indeterminable', true);
S(this.checkbox).click(function () {
assert.equal(this.prop('indeterminate'), true, 'Radio button should be checked');
});
});
});
|
Fix tests with updated generation
|
<?php
namespace Joli\Jane\Swagger\Tests\Expected\Resource;
use Joli\Jane\Swagger\Client\QueryParam;
use Joli\Jane\Swagger\Client\Resource;
class TestResource extends Resource
{
/**
* @param array $parameters List of parameters
* @param string $fetch Fetch mode (object or response)
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function getTest($parameters = array(), $fetch = self::FETCH_OBJECT)
{
$queryParam = new QueryParam();
$url = sprintf('/test?%s', $queryParam->buildQueryString($parameters));
$request = $this->messageFactory->createRequest('GET', $url, $queryParam->buildHeaders($parameters), null);
$response = $this->httpClient->sendRequest($request);
if (self::FETCH_RESPONSE == $fetch) {
return $response;
}
return $response;
}
}
|
<?php
namespace Joli\Jane\Swagger\Tests\Expected\Resource;
use Joli\Jane\Swagger\Client\QueryParam;
use Joli\Jane\Swagger\Client\Resource;
class TestResource extends Resource
{
/**
* @param array $parameters
* @param string $fetch
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function getTest($parameters = array(), $fetch = self::FETCH_OBJECT)
{
$queryParam = new QueryParam();
$url = sprintf('/test?%s', $queryParam->buildQueryString($parameters));
$request = $this->messageFactory->createRequest('GET', $url, $queryParam->buildHeaders($parameters), null);
$response = $this->httpClient->sendRequest($request);
return $response;
}
}
|
[COLAB-2861] Fix staff members widget error
|
package org.xcolab.service.members.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.xcolab.model.tables.pojos.StaffMember;
import org.xcolab.service.members.domain.staffmember.StaffMemberDao;
import org.xcolab.service.utils.PaginationHelper;
import java.util.List;
@RestController
public class StaffMemberController {
private final StaffMemberDao staffMemberDao;
@Autowired
public StaffMemberController(StaffMemberDao staffMemberDao) {
this.staffMemberDao = staffMemberDao;
}
@GetMapping("staffMembers")
public List<StaffMember> listStaffMembers(
@RequestParam(required = false) Integer startRecord,
@RequestParam(required = false) Integer limitRecord,
@RequestParam(required = false) String sort,
@RequestParam(required = false) Long categoryId) {
PaginationHelper paginationHelper = new PaginationHelper(startRecord, limitRecord, sort);
return staffMemberDao.findByGiven(paginationHelper, categoryId);
}
}
|
package org.xcolab.service.members.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.xcolab.model.tables.pojos.StaffMember;
import org.xcolab.service.members.domain.staffmember.StaffMemberDao;
import org.xcolab.service.utils.PaginationHelper;
import java.util.List;
@RestController
public class StaffMemberController {
private final StaffMemberDao staffUserDao;
@Autowired
public StaffMemberController(StaffMemberDao staffUserDao) {
this.staffUserDao = staffUserDao;
}
@RequestMapping(value = "staffUsers", method = RequestMethod.GET)
public List<StaffMember> listStaffMembers(
@RequestParam(required = false) Integer startRecord,
@RequestParam(required = false) Integer limitRecord,
@RequestParam(required = false) String sort,
@RequestParam(required = false) Long categoryId) {
PaginationHelper paginationHelper = new PaginationHelper(startRecord, limitRecord, sort);
return staffUserDao.findByGiven(paginationHelper, categoryId);
}
}
|
Add HTML5 doctype to all rendered pages.
|
var path = require('path');
var url = require('url');
var compression = require('compression');
var express = require('express');
var ssr = require('../index');
var xhr = require('./xhr');
var proxy = require('./proxy');
var doctype = '<!DOCTYPE html>';
module.exports = function (config) {
var app = express()
.use(compression())
.use(xhr());
var pkgPath = path.join(config.path, 'package.json');
var pkg = require(pkgPath);
var render = ssr({
config: pkgPath + '!npm',
main: pkg.main
});
if (config.configure) {
config.configure(app);
}
if (config.proxy) {
var apiPath = config.proxyTo || '/api';
app.use(apiPath, proxy(config.proxy));
}
app.use(express.static(path.join(config.path)));
app.use("/", function (req, res) {
var pathname = url.parse(req.url).pathname;
render(pathname).then(function(html) {
var dt = config.doctype || doctype;
res.send(dt + '\n' + html);
});
});
return app;
};
|
var path = require('path');
var url = require('url');
var compression = require('compression');
var express = require('express');
var ssr = require('../index');
var xhr = require('./xhr');
var proxy = require('./proxy');
module.exports = function (config) {
var app = express()
.use(compression())
.use(xhr());
var pkgPath = path.join(config.path, 'package.json');
var pkg = require(pkgPath);
var render = ssr({
config: pkgPath + '!npm',
main: pkg.main
});
if (config.configure) {
config.configure(app);
}
if (config.proxy) {
var apiPath = config.proxyTo || '/api';
app.use(apiPath, proxy(config.proxy));
}
app.use(express.static(path.join(config.path)));
app.use("/", function (req, res) {
const pathname = url.parse(req.url).pathname;
render(pathname).then(res.send.bind(res));
});
return app;
};
|
Fix wiblog's use of the anti-spam validator
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from django.forms import ModelForm
from django import forms
from fragdev.util.validate_ham import ANTI_SPAM, validate_ham
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\
.format(ANTI_SPAM),
validators=[validate_ham],
max_length=len(ANTI_SPAM))
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from fragdev.contact import validate_ham
from django.forms import ModelForm
from django import forms
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5)
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
Admin: Add template helper for datetime fields
Refs SHOOP-1612
|
# -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
def datetime_field(self, field, **kwargs):
kwargs.setdefault("widget_class", "datetime")
kwargs.setdefault("addon_after", "<span class='fa fa-calendar'></span>")
return self.field(field, **kwargs)
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
|
# -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
|
Make java file compile under 1.6.
I still have 1.6 installed. So the two simple fixes are necessary to make my build pass for now.
|
package test;
import dotty.tools.dotc.core.Contexts;
import org.junit.*;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
public abstract class ContextEscapeDetection {
public static class TestContext{
public TestContext(WeakReference<Contexts.Context> context, String testName) {
this.context = context;
this.testName = testName;
}
public final WeakReference<Contexts.Context> context;
public final String testName;
}
public static final List<TestContext> contexts = new LinkedList<TestContext>();
public abstract Contexts.Context getCtx();
public abstract void clearCtx();
@Before
public synchronized void stealContext() {
contexts.add(new TestContext(new WeakReference<Contexts.Context>(this.getCtx()), this.getClass().getName()));
}
@After
public synchronized void clearContext() {
this.clearCtx();
}
}
|
package test;
import dotty.tools.dotc.core.Contexts;
import org.junit.*;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
public abstract class ContextEscapeDetection {
public static class TestContext{
public TestContext(WeakReference<Contexts.Context> context, String testName) {
this.context = context;
this.testName = testName;
}
public final WeakReference<Contexts.Context> context;
public final String testName;
}
public static final List<TestContext> contexts = new LinkedList<>();
public abstract Contexts.Context getCtx();
public abstract void clearCtx();
@Before
public synchronized void stealContext() {
contexts.add(new TestContext(new WeakReference<>(this.getCtx()), this.getClass().getName()));
}
@After
public synchronized void clearContext() {
this.clearCtx();
}
}
|
Load Google visualization lbirary here so that we don't have to load it in hte inlcuding html.
|
google.load('visualization', '1', {'packages':['annotatedtimeline']});
function annotatedTimeLineChart(chart_element, url, dataString) {
chart_element.text('Loading...');
$.ajax({
url: url,
//dataType: 'json',
//timeout: 30000,
data: dataString,
success: function (data_perl) {
//var data_json = eval (data_perl);
var data = new google.visualization.DataTable(data_perl, 0.6);
//var chart_placement = document.getElementById('line_chart');
var chart = new google.visualization.AnnotatedTimeLine(chart_element.get(0));
var json = data.toJSON();
//alert(json);
chart.draw(data, {
displayAnnotations: true
});
//alert(data.toJSON() );
},
error: function (jqXHR, textStatus, errorThrownsuccess) {
alert(textStatus);
}
});
}
|
function annotatedTimeLineChart(chart_element, url, dataString) {
var chart_element = $('#line_chart');
chart_element.text('Loading...');
$.ajax({
url: url,
//dataType: 'json',
//timeout: 30000,
data: dataString,
success: function (data_perl) {
//var data_json = eval (data_perl);
var data = new google.visualization.DataTable(data_perl, 0.6);
//var chart_placement = document.getElementById('line_chart');
var chart = new google.visualization.AnnotatedTimeLine(chart_element.get(0));
var json = data.toJSON();
//alert(json);
chart.draw(data, {
displayAnnotations: true
});
//alert(data.toJSON() );
},
error: function (jqXHR, textStatus, errorThrownsuccess) {
alert(textStatus);
}
});
}
|
samples: Add quickstarts to root module.
Fixes checkstyle errors in samples.
|
/*
Copyright 2016, Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.translate;
// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;
public class QuickstartSample {
public static void main(String... args) throws Exception {
// Instantiates a client
Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();
// The text to translate
String text = "Hello, world!";
// Translates some text into Russian
Translation translation =
translate.translate(
text,
TranslateOption.sourceLanguage("en"),
TranslateOption.targetLanguage("ru"));
System.out.printf("Text: %s%n", text);
System.out.printf("Translation: %s%n", translation.translatedText());
}
}
// [END translate_quickstart]
|
/*
Copyright 2016, Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.translate;
// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;
public class QuickstartSample {
public static void main(String... args) throws Exception {
// Instantiates a client
Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();
// The text to translate
String text = "Hello, world!";
// Translates some text into Russian
Translation translation = translate.translate(
text,
TranslateOption.sourceLanguage("en"),
TranslateOption.targetLanguage("ru")
);
System.out.printf("Text: %s%n", text);
System.out.printf("Translation: %s%n", translation.translatedText());
}
}
// [END translate_quickstart]
|
Move check for development environment into the getNewAccessToken method.
Revision created by MOE tool push_codebase.
MOE_MIGRATION=7102
|
package com.google.appengine.tools.cloudstorage.oauth;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityService.GetAccessTokenResult;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.appengine.api.utils.SystemProperty;
import java.util.List;
/**
* Provider that uses the AppIdentityService for generating access tokens.
*/
final class AppIdentityAccessTokenProvider implements AccessTokenProvider {
private final AppIdentityService appIdentityService;
public AppIdentityAccessTokenProvider() {
this.appIdentityService = AppIdentityServiceFactory.getAppIdentityService();
}
@Override
public GetAccessTokenResult getNewAccessToken(List<String> scopes) {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) {
throw new IllegalStateException(
"The access token from AppIdentity won't work in the development environment.");
}
return appIdentityService.getAccessToken(scopes);
}
}
|
package com.google.appengine.tools.cloudstorage.oauth;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityService.GetAccessTokenResult;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.appengine.api.utils.SystemProperty;
import java.util.List;
/**
* Provider that uses the AppIdentityService for generating access tokens.
*/
final class AppIdentityAccessTokenProvider implements AccessTokenProvider {
private final AppIdentityService appIdentityService;
public AppIdentityAccessTokenProvider() {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) {
throw new IllegalStateException(
"The access token from AppIdentity won't work in the development environment.");
}
this.appIdentityService = AppIdentityServiceFactory.getAppIdentityService();
}
@Override
public GetAccessTokenResult getNewAccessToken(List<String> scopes) {
return appIdentityService.getAccessToken(scopes);
}
}
|
Use the tempfile module to create system indipendend temporary file for the output.
closes #1
|
import subprocess
import os
import mail_handler
import tempfile
from datetime import datetime
from settings_handler import settings
def execJobs(jobs):
try:
for job in jobs:
if not execJob(job):
return False
print "Jobs executed"
return True
except:
print "Executed failed"
return False
def execJob(job):
recipe = "\"%s\".recipe" % job.recipeRef
output = tempfile.mkstemp(suffix="." + settings.format)
outputPath = output[1]
try:
returned = subprocess.call("ebook-convert %s %s" %(recipe,outputPath) ,shell=True)
if returned != 0:
print "Returned: " + returned
return False
# send the stuff
subject = "%s %s" % (job.recipeRef, datetime.date(datetime.now()))
mail_handler.sendMail(subject, "", outputPath)
except Exception, e:
pass
# delete the tmp file
os.remove(outputPath)
return True
|
import subprocess
import os
import mail_handler
from datetime import datetime
from settings_handler import settings
def execJobs(jobs):
try:
for job in jobs:
if not execJob(job):
return False
print "Jobs executed"
return True
except:
print "Executed failed"
return False
finally:
output = "tmp/output.mobi"
if os.path.isfile(output):
os.remove(output)
def execJob(job):
recipe = "\"%s\".recipe" % job.recipeRef
output = "tmp/output.%s" % settings.format
returned = subprocess.call("ebook-convert %s %s" %(recipe,output) ,shell=True)
if returned != 0:
print "Returned: " + returned
return False
# send the stuff
subject = "%s %s" % (job.recipeRef, datetime.date(datetime.now()))
mail_handler.sendMail(subject, "", output)
# delete the tmp file
os.remove(output)
return True
|
Update PyPSA version in requirements
|
"""This is the docstring for the example.py module. Modules names should
have short, all-lowercase names. The module name may have underscores if
this improves readability.
Every module should have a docstring at the very top of the file. The
module's docstring may extend over multiple lines. If your docstring does
extend over multiple lines, the closing three quotation marks must be on
a line by itself, preferably preceded by a blank line."""
__copyright__ = "tba"
__license__ = "tba"
__author__ = "gplssm"
from setuptools import find_packages, setup
setup(name='ego.powerflow',
author='openego development group',
description='Powerflow analysis based on PyPSA',
version='0.0.1',
license="GNU GENERAL PUBLIC LICENSE Version 3",
packages=find_packages(),
install_requires=['pandas >= 0.17.0, <=0.19.1',
'pypsa >= 0.8.0, <= 0.8.0',
'sqlalchemy >= 1.0.15, <= 1.1.4',
'oemof.db >=0.0.4, <=0.0.4',
'geoalchemy2 >= 0.3.0, <=0.3.0',
'matplotlib >= 1.5.3, <=1.5.3']
)
|
"""This is the docstring for the example.py module. Modules names should
have short, all-lowercase names. The module name may have underscores if
this improves readability.
Every module should have a docstring at the very top of the file. The
module's docstring may extend over multiple lines. If your docstring does
extend over multiple lines, the closing three quotation marks must be on
a line by itself, preferably preceded by a blank line."""
__copyright__ = "tba"
__license__ = "tba"
__author__ = "gplssm"
from setuptools import find_packages, setup
setup(name='ego.powerflow',
author='openego development group',
description='Powerflow analysis based on PyPSA',
version='0.0.1',
license="GNU GENERAL PUBLIC LICENSE Version 3",
packages=find_packages(),
install_requires=['pandas >= 0.17.0, <=0.19.1',
'pypsa >= 0.6.2, <= 0.6.2',
'sqlalchemy >= 1.0.15, <= 1.1.4',
'oemof.db >=0.0.4, <=0.0.4',
'geoalchemy2 >= 0.3.0, <=0.3.0',
'matplotlib >= 1.5.3, <=1.5.3']
)
|
Add dot command not found exception.
|
package org.enoir.graphvizapi.test;
import org.enoir.graphvizapi.*;
import org.enoir.graphvizapi.exception.AttributeNotFondException;
import org.enoir.graphvizapi.exception.GraphException;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by frank on 2014/11/27.
*/
public class TestException {
@Test
public void TestAttributeNotFond(){
try {
Node node = new Node("testId");
node.addAttribute(new Attribute("color", "#000"));
node.removeAttribute("label");
}catch (AttributeNotFondException e) {
Assert.assertTrue(true);
}catch (Exception ex){
Assert.assertTrue(false);
}
}
@Test
public void TestDotCommandNotFound() {
Graphviz gz = new Graphviz("/usr/bin/dot1","./");
Graph graph = new Graph("g1", GraphType.DIGRAPH);
String type = "png";
try {
byte[] bytearray = gz.getGraphByteArray(graph, type, "100");
Assert.assertTrue(false);
}catch (GraphException ge){
Assert.assertTrue(true);
}
}
}
|
package org.enoir.graphvizapi.test;
import org.enoir.graphvizapi.Attribute;
import org.enoir.graphvizapi.Node;
import org.enoir.graphvizapi.exception.AttributeNotFondException;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by frank on 2014/11/27.
*/
public class TestException {
@Test
public void TestAttributeNotFond(){
try {
Node node = new Node("testId");
node.addAttribute(new Attribute("color", "#000"));
node.removeAttribute("label");
}catch (AttributeNotFondException e) {
Assert.assertTrue(true);
}catch (Exception ex){
Assert.assertTrue(false);
}
}
}
|
Fix fetching content for paths without dashes
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { init } from './redux/page';
import Page from './components/Page';
class FrontendApp extends Component {
componentWillMount() {
const path = window.location.pathname
.replace(/^\//, '')
.replace(/\/$/, '');
const options = { mode: 'no-cors' };
if (typeof fetch === 'undefined' || !fetch) {
return;
}
fetch(`/api/content/${path}/index.json`, options)
.then(res => res.json())
.then(json => this.props.initPage(json))
.catch(err => console.error(`Unable to parse content for "${path}".`, err))
}
render() {
const {
title,
description,
children:blocks = [],
} = this.props.page;
return (
<Page
title={title}
description={description}
blocks={blocks}
/>
)
}
}
FrontendApp.propTypes = {
page: PropTypes.object,
init: PropTypes.func,
};
export default connect(
(state) => ({
page: state.page,
}),
{ initPage: init }
)(FrontendApp);
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { init } from './redux/page';
import Page from './components/Page';
class FrontendApp extends Component {
componentWillMount() {
const path = window.location.pathname;
const options = { mode: 'no-cors' };
if (typeof fetch === 'undefined' || !fetch) {
return;
}
fetch(`/api/content${path}index.json`, options)
.then(res => res.json())
.then(json => this.props.initPage(json))
.catch(err => console.error(`Unable to parse content for "${path}".`, err))
}
render() {
const {
title,
description,
children:blocks = [],
} = this.props.page;
return (
<Page
title={title}
description={description}
blocks={blocks}
/>
)
}
}
FrontendApp.propTypes = {
page: PropTypes.object,
init: PropTypes.func,
};
export default connect(
(state) => ({
page: state.page,
}),
{ initPage: init }
)(FrontendApp);
|
Clear autofill when leaving /new form
|
import React from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { clearPetition } from 'actions/PetitionActions';
import { clearSuggestionInputValue } from 'actions/AutocompleteActions';
import settings from 'settings';
import NewPetition from 'components/NewPetition';
import getPetitionForm from 'selectors/petitionForm';
const NewPetitionContainer = React.createClass({
componentWillMount () {
this.props.clearPetition();
this.props.clearSuggestionInputValue();
},
componentWillUnmount () {
this.props.clearSuggestionInputValue();
},
render () {
return (
<div>
<Helmet title={settings.newPetitionPage.title} />
<NewPetition petition={this.props.petition} />
</div>
);
}
});
export const mapStateToProps = ({ petition }) => ({
petition: getPetitionForm(petition)
});
export const mapDispatchToProps = (dispatch) => ({
clearPetition: () => dispatch(clearPetition()),
clearSuggestionInputValue: () => dispatch(clearSuggestionInputValue())
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(NewPetitionContainer);
|
import React from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { clearPetition } from 'actions/PetitionActions';
import { clearSuggestionInputValue } from 'actions/AutocompleteActions';
import settings from 'settings';
import NewPetition from 'components/NewPetition';
import getPetitionForm from 'selectors/petitionForm';
const NewPetitionContainer = React.createClass({
componentWillMount () {
this.props.clearPetition();
this.props.clearSuggestionInputValue();
},
render () {
return (
<div>
<Helmet title={settings.newPetitionPage.title} />
<NewPetition petition={this.props.petition} />
</div>
);
}
});
export const mapStateToProps = ({ petition }) => ({
petition: getPetitionForm(petition)
});
export const mapDispatchToProps = (dispatch) => ({
clearPetition: () => dispatch(clearPetition()),
clearSuggestionInputValue: () => dispatch(clearSuggestionInputValue())
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(NewPetitionContainer);
|
Add build set status listener
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.
*/
(function () {
'use strict';
angular.module('pnc.common.pnc-client.message-bus').factory('buildStatusListener', [
'$log',
'$rootScope',
'pncEventAdaptor',
function ($log, $rootScope, pncEventAdaptor) {
return function (message) {
if (message.eventType === 'BUILD_STATUS_CHANGED' || message.eventType === 'BUILD_SET_STATUS_CHANGED') {
var event = pncEventAdaptor.convert(message);
$log.debug('Following event is broadcasted: %O', event);
$rootScope.$broadcast(event.eventType, event.payload);
}
};
}
]);
})();
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.
*/
(function () {
'use strict';
angular.module('pnc.common.pnc-client.message-bus').factory('buildStatusListener', [
'$log',
'$rootScope',
'pncEventAdaptor',
function ($log, $rootScope, pncEventAdaptor) {
return function (message) {
if (message.eventType === 'BUILD_STATUS_CHANGED') {
var event = pncEventAdaptor.convert(message);
$log.debug('Following event is broadcasted: %O', event);
$rootScope.$broadcast(event.eventType, event.payload);
}
};
}
]);
})();
|
Replace "," with " " before splitting the input.
|
Template.SearchBoxT.events( {
'submit form' : function( evt, template ) {
evt.preventDefault();
var wordList = Session.get( "WordList" );
var newWords = template.find(".search-query")
.value
.replace(/,/g, " ")
.split(/\s+/);
_.each( newWords, function( newWord ) {
var word = newWord.trim();
if( wordList.length < maxNumberOfContainers ) {
if( _.contains( wordList, word.toLowerCase() ) == false ) {
wordList.push( word.toLowerCase() );
Session.set( "WordList", wordList );
}
}
} );
},
'click #clear' : function() {
location.reload();
}
} );
|
Template.SearchBoxT.events( {
'submit form' : function( evt, template ) {
evt.preventDefault();
var wordList = Session.get( "WordList" );
var newWords = template.find(".search-query").value.split(/\s+/);
_.each( newWords, function( newWord ) {
var word = newWord.replace(",", "").trim();
if( wordList.length < maxNumberOfContainers ) {
if( _.contains( wordList, word.toLowerCase() ) == false ) {
wordList.push( word.toLowerCase() );
Session.set( "WordList", wordList );
}
}
} );
},
'click #clear' : function() {
location.reload();
}
} );
|
Remove transparency param for electron
|
"use strict";
/* eslint no-undef:0 */
const { app, BrowserWindow, nativeImage } = require("electron");
const path = require("path");
const url = require("url");
let win;
let image = nativeImage.createFromPath(path.join(__dirname, "./img/icon.png"));
if (app.dock) {
app.dock.setIcon(image);
}
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
icon: __dirname + "/img/icon.png",
title: "Media Player",
darkTheme: true,
hasShadow: true,
titleBarStyle: "hidden-inset"
});
win.setMenu(null);
win.loadURL(url.format({
pathname: path.join(__dirname, "./index.html"),
protocol: "file:",
slashes: true,
}));
win.on("closed", () => {
win = null;
});
}
app.on("ready", createWindow);
app.on("window-all-closed", () => app.quit());
app.on("activate", () => (win === null) ? createWindow() : 0);
|
"use strict";
/* eslint no-undef:0 */
const { app, BrowserWindow, nativeImage } = require("electron");
const path = require("path");
const url = require("url");
let win;
let image = nativeImage.createFromPath(path.join(__dirname, "./img/icon.png"));
if (app.dock) {
app.dock.setIcon(image);
}
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
icon: __dirname + "/img/icon.png",
title: "Media Player",
darkTheme: true,
transparent: true,
hasShadow: true,
titleBarStyle: "hidden-inset"
});
win.setMenu(null);
win.loadURL(url.format({
pathname: path.join(__dirname, "./index.html"),
protocol: "file:",
slashes: true,
}));
win.on("closed", () => {
win = null;
});
}
app.on("ready", createWindow);
app.on("window-all-closed", () => app.quit());
app.on("activate", () => (win === null) ? createWindow() : 0);
|
Fix history message user issue
|
var RtmClient = require('@slack/client').RtmClient;
var RTM_CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS.RTM;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var Conversation = require('watson-developer-cloud/conversation/v1')
var conversation = new Conversation({
username: process.env.CONVERSATION_USERNAME || '',
password: process.env.CONVERSATION_PASSWORD || '',
version_date: Conversation.VERSION_DATE_2017_02_03
});
var workspace_id = process.env.CONVERSATION_WORKSPACE_ID || ''
var bot_token = process.env.SLACK_BOT_TOKEN || '';
var rtm = new RtmClient(bot_token);
rtm.start();
var responseObj = {
context: {}
}
rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
responseObj.context.user = message.user
conversation.message({
input: {text: message.text},
context: responseObj.context,
workspace_id: workspace_id
}, function(err, response) {
if (err) {
console.log(err)
}
else {
console.log(JSON.stringify(response, null, 2))
responseObj = response
rtm.sendMessage(response.output.text[0], message.channel);
}
})
});
rtm.start();
|
var RtmClient = require('@slack/client').RtmClient;
var RTM_CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS.RTM;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var Conversation = require('watson-developer-cloud/conversation/v1')
var conversation = new Conversation({
username: process.env.CONVERSATION_USERNAME || '',
password: process.env.CONVERSATION_PASSWORD || '',
version_date: Conversation.VERSION_DATE_2017_02_03
});
var workspace_id = process.env.CONVERSATION_WORKSPACE_ID || ''
var bot_token = process.env.SLACK_BOT_TOKEN || '';
var rtm = new RtmClient(bot_token);
rtm.start();
var responseObj = {
context: {}
}
rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
if (!responseObj.context.user) {
responseObj.context.user = message.user
}
conversation.message({
input: {text: message.text},
context: responseObj.context,
workspace_id: workspace_id
}, function(err, response) {
if (err) {
console.log(err)
}
else {
console.log(JSON.stringify(response, null, 2))
responseObj = response
rtm.sendMessage(response.output.text[0], message.channel);
}
})
});
rtm.start();
|
Add fix for reactjs shadowdom
|
chrome.storage.local.get(null, function(items) {
var aliases = items.aliases
var aliasKey = items.aliasKey
$('body').on('keydown', 'input, textarea', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == aliasKey) {
var input = $(this).val().split(" ");
for(var i = 0; i < input.length; i++) {
if(replaceInput(input[i])) {
e.preventDefault();
input[i] = replaceInput(input[i])
};
};
this.value = input.join(" ");
var event = new Event('input', {bubbles: true});
this.dispatchEvent(event);
};
});
function replaceInput(input) {
if(input in aliases) {
return aliases[input]
} else {
return false
};
};
});
|
chrome.storage.local.get(null, function(items) {
var aliases = items.aliases
var aliasKey = items.aliasKey
$('body').on('keydown', 'input, textarea', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == aliasKey) {
var input = $(this).val().split(" ");
for(var i = 0; i < input.length; i++) {
if(replaceInput(input[i])) {
e.preventDefault();
input[i] = replaceInput(input[i])
};
};
$(this).val(input.join(" "))
};
});
function replaceInput(input) {
if(input in aliases) {
return aliases[input]
} else {
return false
};
};
});
|
Tag text is now converted to lowercase before being saved
|
from django.db import models
class Author(models.Model):
author_name = models.CharField(max_length=200, unique=True)
author_link = models.URLField()
def __str__(self):
return str(self.name)
class Reason(models.Model):
reason = models.CharField(max_length=200)
def __str__(self):
return str(self.reason)
class Tag(models.Model):
text = models.CharField(max_length=100, unique=True)
def __str__(self):
return str(self.text)
def save(self, *args, **kwargs):
self.text = self.text.lower()
super(Tag, self).save(*args, **kwargs)
class Language(models.Model):
language_name = models.CharField(max_length=100, unique=True)
def __str__(self):
return str(self.name)
class Project(models.Model):
name = models.CharField(max_length=400)
link = models.URLField(unique=True)
author = models.ForeignKey(Author, related_name='projects')
description = models.TextField()
reason = models.ForeignKey(Reason, related_name='projects')
language = models.ForeignKey(Language, related_name='projects', null=True)
tags = models.ManyToManyField(Tag, related_name='projects')
upvotes = models.IntegerField(default=0)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.name)
|
from django.db import models
class Author(models.Model):
author_name = models.CharField(max_length=200, unique=True)
author_link = models.URLField()
def __str__(self):
return str(self.name)
class Reason(models.Model):
reason = models.CharField(max_length=200)
def __str__(self):
return str(self.reason)
class Tag(models.Model):
text = models.CharField(max_length=100, unique=True)
def __str__(self):
return str(self.text)
class Language(models.Model):
language_name = models.CharField(max_length=100, unique=True)
def __str__(self):
return str(self.name)
class Project(models.Model):
name = models.CharField(max_length=400)
link = models.URLField(unique=True)
author = models.ForeignKey(Author, related_name='projects')
description = models.TextField()
reason = models.ForeignKey(Reason, related_name='projects')
language = models.ForeignKey(Language, related_name='projects', null=True)
tags = models.ManyToManyField(Tag, related_name='projects')
upvotes = models.IntegerField(default=0)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.name)
|
Fix some documentation and ugly constant placement
|
package boil
import (
"database/sql"
"os"
)
var (
// currentDB is a global database handle for the package
currentDB Executor
)
// Executor can perform SQL queries.
type Executor interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
// Transactor can commit and rollback, on top of being able to execute queries.
type Transactor interface {
Commit() error
Rollback() error
Executor
}
// Creator starts transactions.
type Creator interface {
Begin() (*sql.Tx, error)
}
// DebugMode is a flag controlling whether generated sql statements and
// debug information is outputted to the DebugWriter handle
//
// NOTE: This should be disabled in production to avoid leaking sensitive data
var DebugMode = false
// DebugWriter is where the debug output will be sent if DebugMode is true
var DebugWriter = os.Stdout
// Begin a transaction
func Begin() (Transactor, error) {
creator, ok := currentDB.(Creator)
if !ok {
panic("Your database does not support transactions.")
}
return creator.Begin()
}
// SetDB initializes the database handle for all template db interactions
func SetDB(db Executor) {
currentDB = db
}
// GetDB retrieves the global state database handle
func GetDB() Executor {
return currentDB
}
|
package boil
import (
"database/sql"
"os"
)
type Executor interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
type Transactor interface {
Commit() error
Rollback() error
Executor
}
type Creator interface {
Begin() (*sql.Tx, error)
}
var currentDB Executor
// DebugMode is a flag controlling whether generated sql statements and
// debug information is outputted to the DebugWriter handle
//
// NOTE: This should be disabled in production to avoid leaking sensitive data
var DebugMode = false
// DebugWriter is where the debug output will be sent if DebugMode is true
var DebugWriter = os.Stdout
func Begin() (Transactor, error) {
creator, ok := currentDB.(Creator)
if !ok {
panic("Your database does not support transactions.")
}
return creator.Begin()
}
// SetDB initializes the database handle for all template db interactions
func SetDB(db Executor) {
currentDB = db
}
// GetDB retrieves the global state database handle
func GetDB() Executor {
return currentDB
}
|
Handle PhantomJS child process errors
|
'use strict';
var app = require('./server/index');
var conf = require('./server/conf');
var logger = conf.logger;
var phantom = require('./server/phantom');
if (!module.parent) {
logger.info('Running in %s mode', conf.env);
var port = conf.port;
var fork = require('child_process').fork;
var phantomChild = fork(__dirname + '/server/phantom');
phantomChild.on('message', function (message) {
if (message.started) {
phantom.started = true; // TODO promise?
phantom.childProcess = phantomChild;
}
});
phantomChild.on('error', function (err) {
logger.error({err: err}, 'PhantomJS child process error');
});
phantomChild.on('exit', function () {
logger.info('PhantomJS child process exited');
});
app.listen(port, function () {
logger.info('Fracas listening on port %s', port);
// if we have a parent, tell them we started
if (process.send) {
process.send({
started: true,
url: 'http://localhost:' + port
});
}
});
}
|
'use strict';
var app = require('./server/index');
var conf = require('./server/conf');
var logger = conf.logger;
var phantom = require('./server/phantom');
if (!module.parent) {
logger.info('Running in %s mode', conf.env);
var port = conf.port;
var fork = require('child_process').fork;
var phantomChild = fork(__dirname + '/server/phantom');
phantomChild.on('message', function (message) {
if (message.started) {
phantom.started = true; // TODO promise?
phantom.childProcess = phantomChild;
}
});
app.listen(port, function () {
logger.info('Fracas listening on port %s', port);
// if we have a parent, tell them we started
if (process.send) {
process.send({
started: true,
url: 'http://localhost:' + port
});
}
});
}
|
Store is using serfnode service discovery
|
import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
import collections
import pickle
import redis
from .serf import node
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = node(role='redis', port=6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
Improve error reporting from server
|
var request = require('request');
var utils = require('./lib/utils');
function Action(actionPath, payload) {
this.actionPath = 'http://test@liferay.com:test@localhost:8080/api/jsonws' + actionPath;
this.payload = payload;
}
Action.prototype.doAction = function(callback) {
var payload = this.payload;
try {
if (!payload) {
throw new Error('Missing payload object');
}
if (!callback) {
throw new Error('Missing callback function');
}
request.post(
{
url: this.actionPath,
form: payload
},
function(error, response, body) {
if (!error) {
if (response.statusCode === 200) {
callback(null, body);
}
else {
var serverError = JSON.parse(response.body).error;
console.log('');
utils.logJSON(serverError);
console.log('');
}
}
else {
console.error('ERROR: ', error);
callback(error);
}
}
);
}
catch(e) {
console.error(e);
}
}
module.exports = Action;
|
var request = require('request');
function Action(actionPath, payload) {
this.actionPath = 'http://test@liferay.com:test@localhost:8080/api/jsonws' + actionPath;
this.payload = payload;
}
Action.prototype.doAction = function(callback) {
var payload = this.payload;
try {
if (!payload) {
throw new Error('Missing payload object');
}
if (!callback) {
throw new Error('Missing callback function');
}
request.post(
{
url: this.actionPath,
form: payload
},
function(error, response, body) {
if (!error && (response.statusCode == 200)) {
callback(null, body);
}
else {
console.error('STATUS CODE: ', response.statusCode);
console.error('ERROR: ', error);
callback(error);
}
}
);
}
catch(e) {
console.error(e);
}
}
module.exports = Action;
|
Rename UMD build product to `ngx-restangular` (to match `package.json`)
|
'use strict';
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './src/index.ts',
output: {
path: __dirname + '/dist/umd',
filename: './ngx-restangular.js',
libraryTarget: 'umd',
library: 'ngx-restangular'
},
externals: [nodeExternals()],
devtool: 'source-map',
module: {
preLoaders: [{
test: /\.ts$/, loader: 'tslint-loader?emitErrors=true&failOnHint=true', exclude: /node_modules/
}],
loaders: [{
test: /\.ts$/, loader: 'ts-loader', exclude: /node_modules/
}]
},
resolve: {
extensions: ['', '.ts', '.js']
}
};
|
'use strict';
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './src/index.ts',
output: {
path: __dirname + '/dist/umd',
filename: './ng2-restangular.js',
libraryTarget: 'umd',
library: 'ng2-restangular'
},
externals: [nodeExternals()],
devtool: 'source-map',
module: {
preLoaders: [{
test: /\.ts$/, loader: 'tslint-loader?emitErrors=true&failOnHint=true', exclude: /node_modules/
}],
loaders: [{
test: /\.ts$/, loader: 'ts-loader', exclude: /node_modules/
}]
},
resolve: {
extensions: ['', '.ts', '.js']
}
};
|
Add flag to print timestamp with rate
|
// Count lines of input per second on stdin
package main
import (
"bufio"
"flag"
"fmt"
"os"
"time"
)
func readLines(c chan int) {
count := 0
bio := bufio.NewReader(os.Stdin)
for {
_, more, err := bio.ReadLine()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if more {
continue
}
count += 1
c <- count
}
}
func main() {
var d time.Duration
var t bool
flag.DurationVar(&d, "i", time.Second, "Update interval")
flag.BoolVar(&t, "t", false, "Include timestamp")
flag.Parse()
line := 0
count := 0
c := make(chan int)
tick := time.Tick(d)
go readLines(c)
for {
select {
// print counts
case <-tick:
prnt := fmt.Sprintf("%v /sec", float64(line-count)/d.Seconds())
if t {
prnt = fmt.Sprintf("%s\t%s", prnt, time.Now().UTC().Format("Mon Jan 2 15:04:05 UTC 2006"))
}
fmt.Println(prnt)
count = line
// update counts
case line = <-c:
}
}
}
|
// Count lines of input per second on stdin
package main
import (
"bufio"
"fmt"
"os"
"time"
"flag"
)
func readLines(c chan int) {
count := 0
bio := bufio.NewReader(os.Stdin)
for {
_, more, err := bio.ReadLine()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if more {
continue
}
count += 1
c <- count
}
}
func main() {
var d time.Duration
flag.DurationVar(&d, "i", time.Second, "Update interval")
flag.Parse()
line := 0
count := 0
c := make(chan int)
tick := time.Tick(d)
go readLines(c)
for {
select {
// print counts
case <-tick:
fmt.Println(float64(line-count)/d.Seconds(), "/sec")
count = line
// update counts
case line = <-c:
}
}
}
|
Change factory class to abstract
|
<?php
namespace JWX\JWE\CompressionAlgorithm;
use JWX\JWA\JWA;
use JWX\JWE\CompressionAlgorithm;
/**
* Factory class to construct compression algorithm instances.
*/
abstract class CompressionFactory
{
/**
* Mapping from algorithm name to class name.
*
* @internal
*
* @var array
*/
const MAP_ALGO_TO_CLASS = array(
/* @formatter:off */
JWA::ALGO_DEFLATE => DeflateAlgorithm::class
/* @formatter:on */
);
/**
* Get compression algorithm by name.
*
* @param string $name
* @throws \UnexpectedValueException
* @return CompressionAlgorithm
*/
public static function algoByName($name) {
if (!array_key_exists($name, self::MAP_ALGO_TO_CLASS)) {
throw new \UnexpectedValueException(
"No compression algorithm '$name'.");
}
$cls = self::MAP_ALGO_TO_CLASS[$name];
return new $cls();
}
}
|
<?php
namespace JWX\JWE\CompressionAlgorithm;
use JWX\JWA\JWA;
use JWX\JWE\CompressionAlgorithm;
/**
* Factory class to construct compression algorithm instances.
*/
class CompressionFactory
{
/**
* Mapping from algorithm name to class name.
*
* @internal
*
* @var array
*/
const MAP_ALGO_TO_CLASS = array(
/* @formatter:off */
JWA::ALGO_DEFLATE => DeflateAlgorithm::class
/* @formatter:on */
);
/**
* Get compression algorithm by name.
*
* @param string $name
* @throws \UnexpectedValueException
* @return CompressionAlgorithm
*/
public static function algoByName($name) {
if (!array_key_exists($name, self::MAP_ALGO_TO_CLASS)) {
throw new \UnexpectedValueException(
"No compression algorithm '$name'.");
}
$cls = self::MAP_ALGO_TO_CLASS[$name];
return new $cls();
}
}
|
Add quotes to cron information page, for the example crontab file
|
<?php
$this->data['header'] = 'Cron information page';
$this->includeAtTemplateBase('includes/header.php');
?>
<div id="content">
<p>Cron is a way to run things regularly on unix systems.</p>
<p>Here is a suggestion for a crontab file:</p>
<pre style="font-size: x-small; color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code><?php
foreach ($this->data['urls'] AS $url ) {
echo "# " . $url['title'] . "\n";
echo "" . $url['int'] . " curl --silent \"" . $url['href'] . "\" > /dev/null 2>&1\n";
}
?>
</code></pre>
<p>Click here to run the cron jobs:
<ul>
<?php
foreach ($this->data['urls'] AS $url ) {
echo '<li><a href="' . $url['href'] . '">' . $url['title'] . '</a></li>';
}
?>
</ul>
</div>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
<?php
$this->data['header'] = 'Cron information page';
$this->includeAtTemplateBase('includes/header.php');
?>
<div id="content">
<p>Cron is a way to run things regularly on unix systems.</p>
<p>Here is a suggestion for a crontab file:</p>
<pre style="font-size: x-small; color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code><?php
foreach ($this->data['urls'] AS $url ) {
echo "# " . $url['title'] . "\n";
echo "" . $url['int'] . " curl --silent --compressed " . $url['href'] . " > /dev/null 2>&1\n";
}
?>
</code></pre>
<p>Click here to run the cron jobs:
<ul>
<?php
foreach ($this->data['urls'] AS $url ) {
echo '<li><a href="' . $url['href'] . '">' . $url['title'] . '</a></li>';
}
?>
</ul>
</div>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
Add test case for resources docs page
|
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.index))
self.assertEqual(response.status_code, 200)
def test_common_errors(self):
response = self.client.get(reverse(views.common_errors))
self.assertEqual(response.status_code, 200)
def test_one_liners(self):
response = self.client.get(reverse(views.one_liners))
self.assertEqual(response.status_code, 200)
def test_technical(self):
response = self.client.get(reverse(views.technical))
self.assertEqual(response.status_code, 200)
def test_resources(self):
response = self.client.get(reverse(views.resources))
self.assertEqual(response.status_code, 200)
|
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.index))
self.assertEqual(response.status_code, 200)
def test_common_errors(self):
response = self.client.get(reverse(views.common_errors))
self.assertEqual(response.status_code, 200)
def test_one_liners(self):
response = self.client.get(reverse(views.one_liners))
self.assertEqual(response.status_code, 200)
def test_technical(self):
response = self.client.get(reverse(views.technical))
self.assertEqual(response.status_code, 200)
|
Add MotoNyan to mad hax
|
from motobot import command, action
@command('say')
def say_command(bot, message, database):
masters = [
"Moto-chan",
"Motoko11",
"MotoNyan",
"Akahige",
"betholas",
"Baradium",
"Cold_slither",
"Drahken"
]
if message.nick.lower() not in [x.lower() for x in masters]:
return "Check your privilege!"
else:
args = message.message.split(' ')[1:]
if len(args) < 2:
return "You must specify both a channel and a message"
else:
channel = args[0]
message = ' '.join(args[1:])
if message.startswith('/me '):
message = action(message[4:])
bot.send('PRIVMSG {} :{}'.format(channel, message))
|
from motobot import command, action
@command('say')
def say_command(bot, message, database):
masters = [
"Moto-chan",
"Motoko11",
"Akahige",
"betholas",
"Baradium",
"Cold_slither",
"Drahken"
]
if message.nick.lower() not in [x.lower() for x in masters]:
return "Check your privilege!"
else:
args = message.message.split(' ')[1:]
if len(args) < 2:
return "You must specify both a channel and a message"
else:
channel = args[0]
message = ' '.join(args[1:])
if message.startswith('/me '):
message = action(message[4:])
bot.send('PRIVMSG {} :{}'.format(channel, message))
|
Remove include clause from find_packages
It's not supported on older versions of pip
|
from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.10.1.dev0',
author='Abhinav Gupta, Aiden Scandella, Bryce Lampe, Grayson Koonce, Junchao Wu',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(exclude=['tests.*']),
install_requires=[
'contextlib2',
'crcmod',
'tornado>=4.0,<5.0',
'toro>=0.8,<0.9',
'threadloop>=0.3,<0.4',
'futures',
],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:start_ioloop'
]
},
)
|
from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.10.1.dev0',
author='Abhinav Gupta, Aiden Scandella, Bryce Lampe, Grayson Koonce, Junchao Wu',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(include=['tchannel.*']),
install_requires=[
'contextlib2',
'crcmod',
'tornado>=4.0,<5.0',
'toro>=0.8,<0.9',
'threadloop>=0.3,<0.4',
'futures',
],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:start_ioloop'
]
},
)
|
Remove second ? from URL
|
import os
import sys
import json
import urllib
import urllib2
api_key = os.getenv("MAPS_API_KEY")
if api_key == "":
sys.exit("Please obtain an API key from https://developers.google.com/maps/documentation/geocoding/start#get-a-key and set the environment variable MAPS_API_KEY")
#print api_key
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
values = {'address' : 'Campbell Hall',
'key' : api_key }
data = urllib.urlencode(values)
full_url = url + data
print full_url
response = urllib2.urlopen(full_url)
json_response = response.read()
data_dict = json.loads(json_response)
#print data_dict
lat = data_dict['results'][0]['geometry']['location']['lat']
lng = data_dict['results'][0]['geometry']['location']['lng']
print lat, lng
|
import os
import sys
import json
import urllib
import urllib2
api_key = os.getenv("MAPS_API_KEY")
if api_key == "":
sys.exit("Please obtain an API key from https://developers.google.com/maps/documentation/geocoding/start#get-a-key and set the environment variable MAPS_API_KEY")
#print api_key
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
values = {'address' : 'Green Bank Telescope',
'key' : api_key }
data = urllib.urlencode(values)
full_url = url + '?' + data
response = urllib2.urlopen(full_url)
json_response = response.read()
data_dict = json.loads(json_response)
#print data_dict
lat = data_dict['results'][0]['geometry']['location']['lat']
lng = data_dict['results'][0]['geometry']['location']['lng']
print lat, lng
|
Use lodash in all modules.
|
/*! @license ©2014 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */
/** A DistinctIterator emits the unique items from a source. */
var FilterIterator = require('./FilterIterator'),
isEqual = require('lodash').isEqual;
// Creates a new DistinctIterator with the given filter
function DistinctIterator(source, options) {
if (!(this instanceof DistinctIterator))
return new DistinctIterator(source, options);
FilterIterator.call(this, source, options);
// The `window` parameter indicates how much items to keep for uniqueness testing
var window = options && options.window;
this._windowLength = isFinite(window) && window > 0 ? ~~window : Infinity;
this._uniques = [];
}
FilterIterator.inherits(DistinctIterator);
// Filters distinct items from the source
DistinctIterator.prototype._filter = function (item) {
// Reject the item if it is already in the list of uniques
var uniques = this._uniques, length = uniques.length, i = length;
while (i !== 0)
if (isEqual(item, uniques[--i]))
return false;
// Shorten the list of uniques if we reach the window length
(length === this._windowLength) && uniques.shift();
// Add the item to the list of uniques
return uniques.push(item);
};
module.exports = DistinctIterator;
|
/*! @license ©2014 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */
/** A DistinctIterator emits the unique items from a source. */
var FilterIterator = require('./FilterIterator'),
isEqual = require('underscore').isEqual;
// Creates a new DistinctIterator with the given filter
function DistinctIterator(source, options) {
if (!(this instanceof DistinctIterator))
return new DistinctIterator(source, options);
FilterIterator.call(this, source, options);
// The `window` parameter indicates how much items to keep for uniqueness testing
var window = options && options.window;
this._windowLength = isFinite(window) && window > 0 ? ~~window : Infinity;
this._uniques = [];
}
FilterIterator.inherits(DistinctIterator);
// Filters distinct items from the source
DistinctIterator.prototype._filter = function (item) {
// Reject the item if it is already in the list of uniques
var uniques = this._uniques, length = uniques.length, i = length;
while (i !== 0)
if (isEqual(item, uniques[--i]))
return false;
// Shorten the list of uniques if we reach the window length
(length === this._windowLength) && uniques.shift();
// Add the item to the list of uniques
return uniques.push(item);
};
module.exports = DistinctIterator;
|
Add support for Python 3.5
|
import os
import sys
from setuptools import setup
from oauth2 import VERSION
if sys.version_info < (3, 0, 0):
memcache_require = "python-memcached"
else:
memcache_require = "python3-memcached"
setup(name="python-oauth2",
version=VERSION,
description="OAuth 2.0 provider for python",
long_description=open("README.rst").read(),
author="Markus Meyer",
author_email="hydrantanderwand@gmail.com",
url="https://github.com/wndhydrnt/python-oauth2",
packages=[d[0].replace("/", ".") for d in os.walk("oauth2") if not d[0].endswith("__pycache__")],
extras_require={
"memcache": [memcache_require],
"mongodb": ["pymongo"],
"redis": ["redis"]
},
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
]
)
|
import os
import sys
from setuptools import setup
from oauth2 import VERSION
if sys.version_info < (3, 0, 0):
memcache_require = "python-memcached"
else:
memcache_require = "python3-memcached"
setup(name="python-oauth2",
version=VERSION,
description="OAuth 2.0 provider for python",
long_description=open("README.rst").read(),
author="Markus Meyer",
author_email="hydrantanderwand@gmail.com",
url="https://github.com/wndhydrnt/python-oauth2",
packages=[d[0].replace("/", ".") for d in os.walk("oauth2") if not d[0].endswith("__pycache__")],
extras_require={
"memcache": [memcache_require],
"mongodb": ["pymongo"],
"redis": ["redis"]
},
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
]
)
|
Disable the Object Storage tests in Waterford
|
# -*- coding: utf-8 -*-
# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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.
#
# For those usages not covered by the Apache version 2.0 License please
# contact with opensource@tid.es
__author__ = 'jfernandez'
from tests import fiware_region_with_networks_tests
class TestSuite(fiware_region_with_networks_tests.FiwareRegionWithNetworkTest):
region_name = "Waterford"
|
# -*- coding: utf-8 -*-
# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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.
#
# For those usages not covered by the Apache version 2.0 License please
# contact with opensource@tid.es
__author__ = 'jfernandez'
from tests import fiware_region_with_networks_tests, fiware_region_object_storage_tests
class TestSuite(fiware_region_with_networks_tests.FiwareRegionWithNetworkTest,
fiware_region_object_storage_tests.FiwareRegionsObjectStorageTests):
region_name = "Waterford"
|
Replace manual session handling with spring session scoped bean
|
package ee.tuleva.onboarding.auth.session;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GenericSessionStore implements Serializable {
@Serial private static final long serialVersionUID = -648103071415508424L;
private final Map<String, Object> sessionAttributes = new HashMap<>();
public <T extends Serializable> void save(T sessionAttribute) {
sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute);
}
public <T extends Serializable> Optional<T> get(Class clazz) {
@SuppressWarnings("unchecked")
T sessionAttribute = (T) sessionAttributes.get(clazz.getName());
if (sessionAttribute == null) {
return Optional.empty();
}
return Optional.of(sessionAttribute);
}
}
|
package ee.tuleva.onboarding.auth.session;
import java.io.Serializable;
import java.util.Optional;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Component
public class GenericSessionStore {
public <T extends Serializable> void save(T sessionAttribute) {
session().setAttribute(sessionAttribute.getClass().getName(), sessionAttribute);
}
public <T extends Serializable> Optional<T> get(Class clazz) {
@SuppressWarnings("unchecked")
T sessionAttribute = (T) session().getAttribute(clazz.getName());
if (sessionAttribute == null) {
return Optional.empty();
}
return Optional.of(sessionAttribute);
}
private static HttpSession session() {
ServletRequestAttributes attr =
(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
boolean allowCreate = true;
return attr.getRequest().getSession(allowCreate);
}
}
|
Fix totally screwed code >:-)
Better run once before push.
|
<?php
/*
* This file is part of the Assetic package, an OpenSky project.
*
* (c) 2010-2013 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Assetic\Filter;
use Assetic\Factory\AssetFactory;
/**
* Like CallablesFilter, but it is also a DependencyExtractor
*
* @author Matthias Pigulla <mp@webfactory.de>
*/
class CallablesDependencyExtractor extends CallablesFilter implements DependencyExtractorInterface
{
protected $extractor;
public function __construct($loader = null, $dumper = null, $extractor = null)
{
parent::__construct($loader, $dumper);
$this->extractor = $extractor;
}
public function getChildren(AssetFactory $factory, $content, $loadPath = null)
{
if (null !== $callable = $this->extractor) {
return $callable($factory, $content, $loadPath);
}
}
}
|
<?php
/*
* This file is part of the Assetic package, an OpenSky project.
*
* (c) 2010-2013 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Assetic\Filter;
use Assetic\Factory\AssetFactory;
/**
* Like CallablesFilter, but it is also a DependencyExtractor
*
* @author Matthias Pigulla <mp@webfactory.de>
*/
class CallablesDependencyExtractor extends CallablesFilter implements DependencyExtractorInterface
{
protected $extractor;
public function __construct($loader = null, $dumper = null, $extractor = null)
{
parent::__construct($loader, $dumper);
$this->extractor = $extractor;
}
public function getChildren(AssetFactory $factory, $content, $loadPath = null)
{
return $this->extractor($factory, $content, $loadPath);
}
}
|
Change my email. Very important.
Not actually important at all.
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='cb-response-surveyor',
author='Keith McCammon',
author_email='keith@redcanary.com',
url='https://github.com/redcanaryco/cb-response-surveyor',
license='MIT',
packages=find_packages(),
description='Extracts summarized process data from Cb Enterprise Response ',
version='0.1',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: Freely Distributable',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
'cbapi'
]
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='cb-response-surveyor',
author='Keith McCammon',
author_email='keith@redcanary.co',
url='https://github.com/redcanaryco/cb-response-surveyor',
license='MIT',
packages=find_packages(),
description='Extracts summarized process data from Cb Enterprise Response ',
version='0.1',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: Freely Distributable',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
'cbapi'
]
)
|
Fix CodeMirror mode load paths
|
module.exports = [
'browser/vendor/codemirror/lib/codemirror.js',
'browser/vendor/codemirror/mode/xml.js',
'browser/vendor/codemirror/mode/javascript.js',
'browser/vendor/codemirror/mode/css.js',
'browser/vendor/codemirror/mode/vbscript.js',
'browser/vendor/codemirror/mode/coffeescript.js',
'browser/vendor/codemirror/mode/clike.js',
'browser/vendor/codemirror/mode/htmlmixed.js',
'browser/vendor/codemirror/mode/smalltalk.js',
'browser/vendor/codemirror/mode/yaml.js',
'browser/vendor/codemirror/mode/python.js',
'browser/vendor/font-awesome/*.woff',
'browser/vendor/font-awesome/*.ttf',
'browser/vendor/font-awesome/*.svg',
'browser/vendor/hammerjs/hammer.min.js',
'browser/vendor/hammerjs/hammer.min.js.map',
'browser/vendor/klayjs/klay.js',
'browser/vendor/klayjs-noflo/klay-noflo.js',
'browser/vendor/observe-js/observe.js',
'browser/vendor/webcomponentsjs/webcomponents-lite.js',
];
|
module.exports = [
'browser/vendor/codemirror/lib/codemirror.js',
'browser/vendor/codemirror/mode/xml/xml.js',
'browser/vendor/codemirror/mode/javascript/javascript.js',
'browser/vendor/codemirror/mode/css/css.js',
'browser/vendor/codemirror/mode/vbscript/vbscript.js',
'browser/vendor/codemirror/mode/coffeescript/coffeescript.js',
'browser/vendor/codemirror/mode/clike/clike.js',
'browser/vendor/codemirror/mode/htmlmixed/htmlmixed.js',
'browser/vendor/codemirror/mode/smalltalk/smalltalk.js',
'browser/vendor/codemirror/mode/yaml/yaml.js',
'browser/vendor/codemirror/mode/python/python.js',
'browser/vendor/font-awesome/*.woff',
'browser/vendor/font-awesome/*.ttf',
'browser/vendor/font-awesome/*.svg',
'browser/vendor/hammerjs/hammer.min.js',
'browser/vendor/hammerjs/hammer.min.js.map',
'browser/vendor/klayjs/klay.js',
'browser/vendor/klayjs-noflo/klay-noflo.js',
'browser/vendor/observe-js/observe.js',
'browser/vendor/webcomponentsjs/webcomponents-lite.js',
];
|
openings: Fix tests for positioned stages
|
from django.test import TestCase
from ..factories._applications import ApplicationFactory
from ..factories._companysettings import InterviewStageFactory
from ..factories._openings import OpeningFactory
class OpeningsModelsTests(TestCase):
def test_applicants_stats(self):
opening = OpeningFactory()
self.assertEqual(opening.applicants_stats(), [])
s1 = InterviewStageFactory(name="L220",
company=opening.company)
s2 = InterviewStageFactory(name="L33",
company=opening.company)
self.assertEqual(opening.applicants_stats(),
[[s1.name, 0], [s2.name, 0]])
application = ApplicationFactory.create(opening=opening)
application.stage_transitions.create(stage=s1)
self.assertEqual(opening.applicants_stats(),
[[s1.name, 1], [s2.name, 0]])
|
from django.test import TestCase
from ..factories._applications import ApplicationFactory
from ..factories._companysettings import InterviewStageFactory
from ..factories._openings import OpeningFactory
class OpeningsModelsTests(TestCase):
def test_applicants_stats(self):
opening = OpeningFactory()
self.assertEqual(opening.applicants_stats(), [])
s1 = InterviewStageFactory(name="L220", initial=True,
company=opening.company)
s2 = InterviewStageFactory(name="L33",
company=opening.company)
self.assertEqual(opening.applicants_stats(),
[[s1.name, 0], [s2.name, 0]])
application = ApplicationFactory.create(opening=opening)
application.stage_transitions.create(stage=s1)
self.assertEqual(opening.applicants_stats(),
[[s1.name, 1], [s2.name, 0]])
|
Add test for magic value check
|
<?php
namespace adrianclay\git\Pack;
use adrianclay\git\Repository;
use adrianclay\git\SHA;
use PHPUnit\Framework\TestCase;
class IndexTest extends TestCase
{
private $repository;
public function setUp(): void
{
parent::setUp();
$path = __DIR__ . '/../../';
$this->repository = new Repository( $path );
}
public function testCanGetAOffsetOfZeroPrefixedSha() {
$sha = new SHA( "00" . "f5270dc9fcb8ec4c31e04334128a4a9f596470" );
$object = $this->repository->getObject( $sha );
$this->assertNotNull( $object );
}
public function testGivenPhpFileThrowsInvalidException() {
$this->expectException(\InvalidArgumentException::class);
new Index(__FILE__);
}
}
|
<?php
namespace adrianclay\git\Pack;
use adrianclay\git\Repository;
use adrianclay\git\SHA;
use PHPUnit\Framework\TestCase;
class IndexTest extends TestCase
{
private $repository;
public function setUp(): void
{
parent::setUp();
$path = __DIR__ . '/../../';
$this->repository = new Repository( $path );
}
public function testCanGetAOffsetOfZeroPrefixedSha() {
$sha = new SHA( "00" . "f5270dc9fcb8ec4c31e04334128a4a9f596470" );
$object = $this->repository->getObject( $sha );
$this->assertNotNull( $object );
}
}
|
Set alt attr as team member's name
|
import React from 'react'
import {
Flex,
Box,
Heading,
Text,
Avatar,
Badge
} from '@hackclub/design-system'
const Base = Flex.extend`
border-radius: ${props => props.theme.radii[2]};
max-width: 36rem;
img {
flex-shrink: 0;
}
`
const Bio = ({ bg, img, name, role, text, ...props }) => (
<Base p={3} bg={`${bg}.0`} {...props}>
<Avatar size="64px" src={img} mr={2} alt={name} />
<Box>
<Flex align="center" wrap style={{ lineHeight: '1.25' }}>
<Heading.h3 f={3} m={0} mr={2} regular={false} children={name} />
<Badge px={2} f={1} bg={`${bg}.5`} children={role} />
</Flex>
<Text f={2} mt={[1, 0]} mb={0} color="black" children={text} />
</Box>
</Base>
)
export default Bio
|
import React from 'react'
import {
Flex,
Box,
Heading,
Text,
Avatar,
Badge
} from '@hackclub/design-system'
const Base = Flex.extend`
border-radius: ${props => props.theme.radii[2]};
max-width: 36rem;
img {
flex-shrink: 0;
}
`
const Bio = ({ bg, img, name, role, text, ...props }) => (
<Base p={3} bg={`${bg}.0`} {...props}>
<Avatar size="64px" src={img} mr={2} alt=""/>
<Box>
<Flex align="center" wrap style={{ lineHeight: '1.25' }}>
<Heading.h3 f={3} m={0} mr={2} regular={false} children={name} />
<Badge px={2} f={1} bg={`${bg}.5`} children={role} />
</Flex>
<Text f={2} mt={[1, 0]} mb={0} color="black" children={text} />
</Box>
</Base>
)
export default Bio
|
Store options with Minimongo indexes if passed
|
/* eslint-disable no-underscore-dangle */
export const MiniMongo = {}
const NAME_TO_CAUSE_MINIMONGO = null
if (global.Mongo) {
MiniMongo.Collection = class MiniMongoCollection extends global.Mongo.Collection {
constructor(name) {
super(NAME_TO_CAUSE_MINIMONGO)
this._name = name // eslint-disable-line no-underscore-dangle
this.indexes = []
}
_ensureIndex(keys, options) {
if (! this._c2 || ! this._c2._simpleSchema) {
throw new Error("Attach a schema before adding indexes so we can check they're valid")
}
const schemaDoc = this._c2._simpleSchema._schema
Object.keys(keys).forEach(k => {
if (! (k in schemaDoc)) {
throw new Error(`Attempt to add an index key '${k}' which is not in the schema`)
}
})
this.indexes.push(options ? { keys, options } : keys)
// MiniMongo would normally throw an exception but we ignore it
// If this was ever used on the client it should throw still
}
}
}
|
/* eslint-disable no-underscore-dangle */
export const MiniMongo = {}
const NAME_TO_CAUSE_MINIMONGO = null
if (global.Mongo) {
MiniMongo.Collection = class MiniMongoCollection extends global.Mongo.Collection {
constructor(name) {
super(NAME_TO_CAUSE_MINIMONGO)
this._name = name // eslint-disable-line no-underscore-dangle
this.indexes = []
}
_ensureIndex(keys, options) {
if (! this._c2 || ! this._c2._simpleSchema) {
throw new Error("Attach a schema before adding indexes so we can check they're valid")
}
const schemaDoc = this._c2._simpleSchema._schema
Object.keys(keys).forEach(k => {
if (! (k in schemaDoc)) {
throw new Error(`Attempt to add an index key '${k}' which is not in the schema`)
}
})
this.indexes.push(keys)
// MiniMongo would normally throw an exception but we ignore it
// If this was ever used on the client it should throw still
}
}
}
|
Allow SponsorFactory to create active sponsors.
|
import factory
from symposion.schedule.tests.factories import ConferenceFactory
from symposion.sponsorship.models import SponsorLevel, Sponsor
class SponsorLevelFactory(factory.django.DjangoModelFactory):
conference = factory.SubFactory(ConferenceFactory)
name = factory.Faker("color_name")
order = factory.Faker("pyint")
cost = factory.Faker("pyint")
description = factory.Faker("paragraph")
class Meta:
model = SponsorLevel
class SponsorFactory(factory.django.DjangoModelFactory):
name = factory.Faker("company")
display_url = factory.Faker("uri")
external_url = factory.Faker("uri")
contact_name = factory.Faker("name")
contact_email = factory.Faker("company_email")
level = factory.SubFactory(SponsorLevelFactory)
active = factory.Faker("boolean")
class Meta:
model = Sponsor
|
import factory
from symposion.schedule.tests.factories import ConferenceFactory
from symposion.sponsorship.models import SponsorLevel, Sponsor
class SponsorLevelFactory(factory.django.DjangoModelFactory):
conference = factory.SubFactory(ConferenceFactory)
name = factory.Faker("color_name")
order = factory.Faker("pyint")
cost = factory.Faker("pyint")
description = factory.Faker("paragraph")
class Meta:
model = SponsorLevel
class SponsorFactory(factory.django.DjangoModelFactory):
name = factory.Faker("company")
display_url = factory.Faker("uri")
external_url = factory.Faker("uri")
contact_name = factory.Faker("name")
contact_email = factory.Faker("company_email")
level = factory.SubFactory(SponsorLevelFactory)
class Meta:
model = Sponsor
|
Add startup delay and change interpreter prompts
The delay is so that hopefully switch connections don't IMMEDIATELY print
all over the prompt. We'll do something better eventually.
|
#!/usr/bin/python
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
import pox.messenger.messenger
# Turn on extra info for event exceptions
import pox.lib.revent.revent as revent
revent.showEventExceptions = True
def startup ():
core.register("topology", pox.topology.topology.Topology())
core.register("openflow", pox.openflow.openflow.OpenFlowHub())
core.register("switch", pox.dumb_l3_switch.dumb_l3_switch.dumb_l3_switch())
pox.openflow.of_01.start()
pox.messenger.messenger.start()
if __name__ == '__main__':
try:
startup()
core.goUp()
except:
import traceback
traceback.print_exc()
import time
time.sleep(1)
import code
import sys
sys.ps1 = "POX> "
sys.ps2 = " ... "
code.interact('Ready.', local=locals())
pox.core.core.quit()
|
#!/usr/bin/python
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
import pox.messenger.messenger
# Turn on extra info for event exceptions
import pox.lib.revent.revent as revent
revent.showEventExceptions = True
def startup ():
core.register("topology", pox.topology.topology.Topology())
core.register("openflow", pox.openflow.openflow.OpenFlowHub())
core.register("switch", pox.dumb_l3_switch.dumb_l3_switch.dumb_l3_switch())
pox.openflow.of_01.start()
pox.messenger.messenger.start()
if __name__ == '__main__':
try:
startup()
core.goUp()
except:
import traceback
traceback.print_exc()
import code
code.interact('Ready.', local=locals())
pox.core.core.quit()
|
Add GraphQL schema description for args.page
|
'use strict';
const { GraphQLInt, GraphQLString } = require('graphql');
// Pagination arguments
const paginationActionTypes = ['find'];
const getPaginationArgument = function ({ action: { actionType, multiple }, defaultPageSize, maxPageSize }) {
// Only with safe operations that return an array, i.e. only with findMany
if (!(paginationActionTypes.includes(actionType) && multiple)) { return; }
return {
page_size: {
type: GraphQLInt,
description: `Sets pagination size.
Using 0 disables pagination.
Maximum: ${maxPageSize}`,
defaultValue: defaultPageSize,
},
after: {
type: GraphQLString,
description: `Retrieves next pagination batch, using the previous response's last model's 'token'.
Using '' means 'from the beginning'`,
defaultValue: '',
},
before: {
type: GraphQLString,
description: `Retrieves previous pagination batch, using the previous response's first model's 'token'.
Using '' means 'from the end'`,
},
page: {
type: GraphQLInt,
description: `Page number, for pagination.
Starts at 1.
Cannot be used with 'before' or 'after'`,
},
};
};
module.exports = {
getPaginationArgument,
};
|
'use strict';
const { GraphQLInt, GraphQLString } = require('graphql');
// Pagination arguments
const paginationActionTypes = ['find'];
const getPaginationArgument = function ({ action: { actionType, multiple }, defaultPageSize, maxPageSize }) {
// Only with safe operations that return an array, i.e. only with findMany
if (!(paginationActionTypes.includes(actionType) && multiple)) { return; }
return {
page_size: {
type: GraphQLInt,
description: `Sets pagination size.
Using 0 disables pagination.
Maximum: ${maxPageSize}`,
defaultValue: defaultPageSize,
},
after: {
type: GraphQLString,
description: `Retrieves next pagination batch, using the previous response's last model's 'token'.
Using '' means 'from the beginning'`,
defaultValue: '',
},
before: {
type: GraphQLString,
description: `Retrieves previous pagination batch, using the previous response's first model's 'token'.
Using '' means 'from the end'`,
},
};
};
module.exports = {
getPaginationArgument,
};
|
Fix clean-css processing font @import rule
|
/**
* Gulpfile.js
*/
/* jshint node:true */
'use strict';
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
autoprefixer = require('gulp-autoprefixer'),
cssmin = require('gulp-minify-css'),
rename = require('gulp-rename'),
sourcemaps = require('gulp-sourcemaps');
// Gulp Tasks
// Core building
gulp.task('build:sass', function () {
return sass('src/main.scss', {sourcemap: true, style: 'expanded'})
.on('error', function (e) {
console.error(e.message);
})
.pipe(sourcemaps.write({sourceRoot: './'}))
.pipe(rename({basename: 'city'}))
.pipe(gulp.dest('dist/'));
});
// Production
gulp.task('production', ['build:sass'], function () {
return gulp.src('dist/city.css')
.pipe(autoprefixer({browsers: ['last 2 versions']}))
// normal version
.pipe(gulp.dest('dist/'))
// minified version
.pipe(rename({suffix: '.min'}))
.pipe(cssmin({processImport: false}))
.pipe(gulp.dest('dist/'));
});
// Default task
gulp.task('default', ['build:sass', 'watch']);
// Watch files
gulp.task('watch', function () {
gulp.watch(['src/**/*.scss', 'src/main.scss'], ['build:sass']);
});
|
/**
* Gulpfile.js
*/
/* jshint node:true */
'use strict';
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
autoprefixer = require('gulp-autoprefixer'),
cssmin = require('gulp-minify-css'),
rename = require('gulp-rename'),
sourcemaps = require('gulp-sourcemaps');
// Gulp Tasks
// Core building
gulp.task('build:sass', function () {
return sass('src/main.scss', {sourcemap: true, style: 'expanded'})
.on('error', function (e) {
console.error(e.message);
})
.pipe(sourcemaps.write({sourceRoot: './'}))
.pipe(rename({basename: 'city'}))
.pipe(gulp.dest('dist/'));
});
// Production
gulp.task('production', ['build:sass'], function () {
return gulp.src('dist/city.css')
.pipe(autoprefixer({browsers: ['last 2 versions']}))
// normal version
.pipe(gulp.dest('dist/'))
// minified version
.pipe(rename({suffix: '.min'}))
.pipe(cssmin())
.pipe(gulp.dest('dist/'));
});
// Default task
gulp.task('default', ['build:sass', 'watch']);
// Watch files
gulp.task('watch', function () {
gulp.watch(['src/**/*.scss', 'src/main.scss'], ['build:sass']);
});
|
Put paths inside quotes so spaces don't need to be escaped
|
var sudo = require('sudo-prompt');
var cmdFnPath = require.resolve('cmd-fn');
var setName = sudo.setName;
var call = function(options, cb) {
// Put paths inside quotes so spaces don't need to be escaped
var cmd = '"' + process.execPath +'" "' + cmdFnPath + '"';
if (process.execPath.indexOf("/Contents/MacOS/Electron") >= 0) {
// If we're running in Electron then make sure that the process is being
// run in node mode not as the GUI app.
cmd = 'ATOM_SHELL_INTERNAL_RUN_AS_NODE=1 ' + cmd;
}
if (options.module) {
cmd = cmd + ' --module ' + options.module;
} else {
return cb(new Error('module option is required'));
}
if (options.function) {
cmd = cmd + ' --function ' + options.function;
}
if (options.params) {
cmd = cmd + ' --params \'' + JSON.stringify(options.params) + '\'';
}
if (options.cwd) {
cmd = cmd + ' --cwd \'' + options.cwd + '\'';
}
if (options.type) {
cmd = cmd + ' --' + options.type;
}
return sudo.exec(cmd, function(err, val) {
try {
val = JSON.parse(val);
} catch (e) {
// Do Nothing
}
cb(err,val);
});
};
module.exports = {
call: call,
setName: setName
};
|
var sudo = require('sudo-prompt');
var cmdFnPath = require.resolve('cmd-fn');
var setName = sudo.setName;
var call = function(options, cb) {
var cmd = process.execPath + ' ' + cmdFnPath;
if (process.execPath.indexOf("/Contents/MacOS/Electron") >= 0) {
// If we're running in Electron then make sure that the process is being
// run in node mode not as the GUI app.
cmd = 'ATOM_SHELL_INTERNAL_RUN_AS_NODE=1 ' + cmd;
}
if (options.module) {
cmd = cmd + ' --module ' + options.module;
} else {
return cb(new Error('module option is required'));
}
if (options.function) {
cmd = cmd + ' --function ' + options.function;
}
if (options.params) {
cmd = cmd + ' --params \'' + JSON.stringify(options.params) + '\'';
}
if (options.cwd) {
cmd = cmd + ' --cwd \'' + options.cwd + '\'';
}
if (options.type) {
cmd = cmd + ' --' + options.type;
}
return sudo.exec(cmd, function(err, val) {
try {
val = JSON.parse(val);
} catch (e) {
// Do Nothing
}
cb(err,val);
});
};
module.exports = {
call: call,
setName: setName
};
|
Set default parser value in constructor.
|
<?php
/**
* PHP version 5.6
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace ComPHPPuebla\DBAL\Fixture\Loader;
use Symfony\Component\Yaml\Parser;
class YamlLoader implements Loader
{
/** @var string */
protected $path;
/** @var Parser */
protected $reader;
/**
* @param string $path
* @param Parser|null $reader
*/
public function __construct($path, Parser $reader = null)
{
$this->path = $path;
$this->reader = $reader ?: new Parser();
}
/**
* @return array
*/
public function load()
{
return $this->reader->parse(file_get_contents($this->path));
}
}
|
<?php
/**
* PHP version 5.6
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace ComPHPPuebla\DBAL\Fixture\Loader;
use Symfony\Component\Yaml\Parser;
class YamlLoader implements Loader
{
/** @var string */
protected $path;
/** @var Parser */
protected $reader;
public function __construct($path, Parser $reader = null)
{
$this->path = $path;
$this->reader = $reader;
}
public function load()
{
if (!$this->reader) {
$this->reader = new Parser();
}
return $this->reader->parse(file_get_contents($this->path));
}
}
|
Make the technique even more generic
--HG--
branch : feature/issue-229
|
"""
Handle loading a package from system or from the bundled copy
"""
import imp
_SEARCH_PATH = ['setuptools._vendor.six', 'six']
def _find_module(name, path=None):
"""
Alternative to `imp.find_module` that can also search in subpackages.
"""
parts = name.split('.')
for part in parts:
if path is not None:
path = [path]
fh, path, descr = imp.find_module(part, path)
return fh, path, descr
def _import_in_place(search_path=_SEARCH_PATH):
for mod_name in search_path:
try:
mod_info = _find_module(mod_name)
except ImportError:
continue
imp.load_module(__name__, *mod_info)
break
else:
raise ImportError(
"The '{name}' package is required; "
"normally this is bundled with this package so if you get "
"this warning, consult the packager of your "
"distribution.".format(name=_SEARCH_PATH[-1]))
_import_in_place()
|
"""
Handle loading six package from system or from the bundled copy
"""
import imp
_SIX_SEARCH_PATH = ['setuptools._vendor.six', 'six']
def _find_module(name, path=None):
"""
Alternative to `imp.find_module` that can also search in subpackages.
"""
parts = name.split('.')
for part in parts:
if path is not None:
path = [path]
fh, path, descr = imp.find_module(part, path)
return fh, path, descr
def _import_six(search_path=_SIX_SEARCH_PATH):
for mod_name in search_path:
try:
mod_info = _find_module(mod_name)
except ImportError:
continue
imp.load_module(__name__, *mod_info)
break
else:
raise ImportError(
"The 'six' module of minimum version {0} is required; "
"normally this is bundled with this package so if you get "
"this warning, consult the packager of your "
"distribution.")
_import_six()
|
Remove GitHub from the help scripts
|
// PiscoBot Script
var commandDescription = {
name: 'GitHub Mention',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: '[none]',
version: 1.0,
description: 'Have the bot reply to new commits on GitHub.',
module: 'Core'
};
var _ = require('underscore');
global.piscobot.hears(['PiscoBot.*new commits by', 'PiscoBot.*new commit by'], ['bot_message'],
function(bot, message) {
var emoji = [
'thinking_face',
'open_mouth',
'face_with_rolling_eyes',
'sweat_smile'
];
bot.api.reactions.add({
timestamp: message.ts,
channel: message.channel,
name: _.sample(emoji)
}, function(err) {
if(err) {
bot.botkit.log('Failed to add emoji reaction :(', err);
}
});
}
);
|
// PiscoBot Script
var commandDescription = {
name: 'GitHub Mention',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: '[none]',
version: 1.0,
description: 'Have the bot reply to new commits on GitHub.',
module: 'Core'
};
global.botHelp.push(commandDescription);
var _ = require('underscore');
global.piscobot.hears(['PiscoBot.*new commits by', 'PiscoBot.*new commit by'], ['bot_message'],
function(bot, message) {
var emoji = [
'thinking_face',
'open_mouth',
'face_with_rolling_eyes',
'sweat_smile'
];
bot.api.reactions.add({
timestamp: message.ts,
channel: message.channel,
name: _.sample(emoji)
}, function(err) {
if(err) {
bot.botkit.log('Failed to add emoji reaction :(', err);
}
});
}
);
|
Fix initiativeShow to subscribe to userData
|
Router.configure({
layoutTemplate: '_layout'
});
//From what I can tell this has been depreciated
//https://github.com/iron-meteor/iron-router/blob/739bcc1445db3ad6bf90bda4e0cab3203a0ae526/lib/router.js#L88
Router.map(function() {
// initiative routes
this.route('initiatives', {
path: '/',
template: 'initiatives',
data: function() {
return {
userData: Meteor.subscribe("userData"),
initiatives: Initiatives.find({}, {sort: {votes: -1}})
}
}
});
this.route('initiative', {
path: '/initiative/:_id',
template: 'initiativeShow',
data: function () {
return {
userData: Meteor.subscribe("userData"),
initiative: Initiatives.findOne(this.params._id)
}
}
});
this.route('profile', {
path: '/profile',
template: 'profileShow',
data: function() {
return {
profile: Meteor.user()
}
}
})
// login routes
this.route('login', {
path: '/login',
template: 'publicLogin'
});
this.route('about');
});
|
Router.configure({
layoutTemplate: '_layout'
});
//From what I can tell this has been depreciated
//https://github.com/iron-meteor/iron-router/blob/739bcc1445db3ad6bf90bda4e0cab3203a0ae526/lib/router.js#L88
Router.map(function() {
// initiative routes
this.route('initiatives', {
path: '/',
template: 'initiatives',
data: function() {
return {
userData: Meteor.subscribe("userData"),
initiatives: Initiatives.find({}, {sort: {votes: -1}})
}
}
});
this.route('initiative', {
path: '/initiative/:_id',
template: 'initiativeShow',
data: function () {
return {
initiative: Initiatives.findOne(this.params._id)
}
}
});
this.route('profile', {
path: '/profile',
template: 'profileShow',
data: function() {
return {
profile: Meteor.user()
}
}
})
// login routes
this.route('login', {
path: '/login',
template: 'publicLogin'
});
this.route('about');
});
|
Add responseError: takes ErrorType and maps to HTTP error
|
/*
* Copyright (c) 2015-2016, Index Data
* All rights reserved.
* See the file LICENSE for details.
*/
package okapi.util;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
public class HttpResponse {
static public void responseError(RoutingContext ctx, ErrorType t, Throwable cause) {
int code = 500;
switch (t) {
case OK: code = 200; break;
case INTERNAL: code = 500; break;
case USER: code = 400; break;
case NOT_FOUND: code = 404; break;
case ANY: code = 500; break;
}
responseError(ctx, code, cause);
}
static public void responseError(RoutingContext ctx, int code, Throwable cause) {
responseText(ctx, code).end(cause.getMessage());
}
static public HttpServerResponse responseText(RoutingContext ctx, int code) {
return ctx.response()
.setStatusCode(code)
.putHeader("Content-Type", "text/plain");
}
static public HttpServerResponse responseJson(RoutingContext ctx, int code) {
return ctx.response()
.setStatusCode(code)
.putHeader("Content-Type", "application/json");
}
}
|
/*
* Copyright (c) 2015-2016, Index Data
* All rights reserved.
* See the file LICENSE for details.
*/
package okapi.util;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
public class HttpResponse {
static public void responseError(RoutingContext ctx, int code, Throwable cause) {
responseText(ctx, code).end(cause.getMessage());
}
static public HttpServerResponse responseText(RoutingContext ctx, int code) {
return ctx.response()
.setStatusCode(code)
.putHeader("Content-Type", "text/plain");
}
static public HttpServerResponse responseJson(RoutingContext ctx, int code) {
return ctx.response()
.setStatusCode(code)
.putHeader("Content-Type", "application/json");
}
}
|
Add support for jQuery in compatibility mode
|
Materialize = {};
// Unique ID
Materialize.guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
Materialize.elementOrParentIsFixed = function(element) {
var $element = $(element);
var $checkElements = $element.add($element.parents());
var isFixed = false;
$checkElements.each(function(){
if ($(this).css("position") === "fixed") {
isFixed = true;
return false;
}
});
return isFixed;
};
// Velocity has conflicts when loaded with jQuery, this will check for it
var Vel;
if ($) {
Vel = $.Velocity;
}
else if (jQuery) {
Vel = jQuery.Velocity;
}
else {
Vel = Velocity;
}
|
Materialize = {};
// Unique ID
Materialize.guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
Materialize.elementOrParentIsFixed = function(element) {
var $element = $(element);
var $checkElements = $element.add($element.parents());
var isFixed = false;
$checkElements.each(function(){
if ($(this).css("position") === "fixed") {
isFixed = true;
return false;
}
});
return isFixed;
};
// Velocity has conflicts when loaded with jQuery, this will check for it
var Vel;
if ($) {
Vel = $.Velocity;
}
else {
Vel = Velocity;
}
|
Replace SpoonFileCSV with ForkCMS\Utility\Csv\Writer implementation
|
<?php
namespace Backend\Modules\Profiles\Actions;
use Backend\Core\Engine\Authentication;
use Backend\Core\Engine\Base\ActionAdd as BackendBaseActionAdd;
use Common\Exception\RedirectException;
use ForkCMS\Utility\Csv\Writer;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
/**
* This is the add-action, it will display a form to add a new profile.
*/
class ExportTemplate extends BackendBaseActionAdd
{
public function execute(): void
{
$this->checkToken();
$spreadSheet = new Spreadsheet();
$sheet = $spreadSheet->getActiveSheet();
$sheet->fromArray(
[
'email',
'display_name',
'password',
],
null,
'A1'
);
throw new RedirectException(
'Return the csv data',
$this->get(Writer::class)
->forBackendUser(Authentication::getUser())
->output($spreadSheet, 'import_template.csv')
);
}
}
|
<?php
namespace Backend\Modules\Profiles\Actions;
use Backend\Core\Engine\Base\ActionAdd as BackendBaseActionAdd;
/**
* This is the add-action, it will display a form to add a new profile.
*/
class ExportTemplate extends BackendBaseActionAdd
{
public function execute(): void
{
$this->checkToken();
// define path
$path = BACKEND_CACHE_PATH . '/Profiles/import_template.csv';
// define required fields
$fields = [
'email',
'display_name',
'password',
];
// define file
$file = new \SpoonFileCSV();
// download the file
$file->arrayToFile($path, [], $fields, null, ',', '"', true);
}
}
|
Fix Initiative sorting on landing page.
|
Router.configure({
layoutTemplate: '_layout'
});
//From what I can tell this has been depreciated
//https://github.com/iron-meteor/iron-router/blob/739bcc1445db3ad6bf90bda4e0cab3203a0ae526/lib/router.js#L88
Router.map(function() {
// initiative routes
this.route('initiatives', {
path: '/',
template: 'initiatives',
data: function() {
return {
initiatives: Initiatives.find({}, {sort: {votes: -1}})
}
}
});
this.route('initiative', {
path: '/initiative/:_id',
template: 'initiativeShow',
data: function () {
return {
initiative: Initiatives.findOne(this.params._id)
}
}
});
// login routes
this.route('login', {
path: '/login',
template: 'publicLogin'
});
this.route('about');
});
|
Router.configure({
layoutTemplate: '_layout'
});
//From what I can tell this has been depreciated
//https://github.com/iron-meteor/iron-router/blob/739bcc1445db3ad6bf90bda4e0cab3203a0ae526/lib/router.js#L88
Router.map(function() {
// initiative routes
this.route('initiatives', {
path: '/',
template: 'initiatives',
data: {
initiatives: function() {
return Initiatives.find({}, {$sort: {votes: -1}});
}
}
});
this.route('initiative', {
path: '/initiative/:_id',
template: 'initiativeShow',
data: function () {
return {
initiative: Initiatives.findOne(this.params._id)
}
}
});
// login routes
this.route('login', {
path: '/login',
template: 'publicLogin'
});
this.route('about');
});
|
Add an addiction event dispatcher test
|
<?php
namespace SmoothPhp\Tests\EventDispatcher;
use SmoothPhp\EventDispatcher\SimpleEventDispatcher;
/**
* Class SimpleEventDispatcherTest
* @package SmoothPhp\Tests\EventDispatcher
* @author Simon Bennett <simon@smoothphp.com>
*/
final class SimpleEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function check_dispatcher_runs()
{
$dispatcher = new SimpleEventDispatcher();
$runCount = 0;
$dispatcher->addListener('test',function()use(&$runCount)
{
$runCount ++;
});
$this->assertEquals(0,$runCount);
$dispatcher->dispatch('test',[]);
$this->assertEquals(1,$runCount);
}
/**
* @test
*/
public function check_dispatcher_does_not_run()
{
$dispatcher = new SimpleEventDispatcher();
$runCount = 0;
$dispatcher->addListener('test',function()use(&$runCount)
{
$runCount ++;
});
$dispatcher->dispatch('test_does_not_run',[]);
$this->assertEquals(0,$runCount);
}
}
|
<?php
namespace SmoothPhp\Tests\EventDispatcher;
use SmoothPhp\EventDispatcher\SimpleEventDispatcher;
/**
* Class SimpleEventDispatcherTest
* @package SmoothPhp\Tests\EventDispatcher
* @author Simon Bennett <simon@smoothphp.com>
*/
final class SimpleEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function check_dispatcher_runs()
{
$dispatcher = new SimpleEventDispatcher();
$runCount = 0;
$dispatcher->addListener('test',function()use(&$runCount)
{
$runCount ++;
});
$this->assertEquals(0,$runCount);
$dispatcher->dispatch('test',[]);
$this->assertEquals(1,$runCount);
}
}
|
Update report_rendering test to use ReportExport
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from corehq.apps.userreports.reports.view import ConfigurableReportView
from corehq.apps.userreports.reports.util import ReportExport
class VeryFakeReportExport(ReportExport):
def __init__(self, data):
self._data = data
def get_table(self):
return self._data
class VeryFakeReportView(ConfigurableReportView):
# note: this is very coupled to what it tests below, but it beats bootstrapping a whole UCR thing
def __init__(self, data):
self._data = data
@property
def report_export(self):
return VeryFakeReportExport(self._data)
class ReportRenderingTest(SimpleTestCase):
def test_email_response_unicode(self):
report = VeryFakeReportView(data=[
['hello', 'हिन्दी']
])
# this used to fail: https://manage.dimagi.com/default.asp?263803
report.email_response
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from corehq.apps.userreports.reports.view import ConfigurableReportView
class VeryFakeReportView(ConfigurableReportView):
# note: this is very coupled to what it tests below, but it beats bootstrapping a whole UCR thing
def __init__(self, data):
self._data = data
@property
def export_table(self):
return self._data
class ReportRenderingTest(SimpleTestCase):
def test_email_response_unicode(self):
report = VeryFakeReportView(data=[
['hello', 'हिन्दी']
])
# this used to fail: https://manage.dimagi.com/default.asp?263803
report.email_response
|
Add a test for making a file
|
import os
from os.path import isdir
import pytest
from filesystem_tree import FilesystemTree
@pytest.yield_fixture
def fs():
fs = FilesystemTree()
yield fs
fs.remove()
def test_it_can_be_instantiated():
assert FilesystemTree().__class__.__name__ == 'FilesystemTree'
def test_args_go_to_mk_not_root():
fs = FilesystemTree('foo', 'bar')
assert fs.root != 'foo'
def test_it_makes_a_directory(fs):
assert isdir(fs.root)
def test_resolve_resolves(fs):
path = fs.resolve('some/dir')
assert path == os.path.realpath(os.sep.join([fs.root, 'some', 'dir']))
def test_mk_makes_a_dir(fs):
fs.mk('some/dir')
assert isdir(fs.resolve('some/dir'))
def test_mk_makes_a_file(fs):
fs.mk(('some/dir/file.txt', 'Greetings, program!'))
contents = open(fs.resolve('some/dir/file.txt')).read()
assert contents == 'Greetings, program!'
def test_remove_removes(fs):
assert isdir(fs.root)
fs.remove()
assert not isdir(fs.root)
def test_resolve_with_no_arg_is_equivalent_to_root(fs):
assert fs.resolve() == fs.root
|
import os
from os.path import isdir
import pytest
from filesystem_tree import FilesystemTree
@pytest.yield_fixture
def fs():
fs = FilesystemTree()
yield fs
fs.remove()
def test_it_can_be_instantiated():
assert FilesystemTree().__class__.__name__ == 'FilesystemTree'
def test_args_go_to_mk_not_root():
fs = FilesystemTree('foo', 'bar')
assert fs.root != 'foo'
def test_it_makes_a_directory(fs):
assert isdir(fs.root)
def test_resolve_resolves(fs):
path = fs.resolve('some/dir')
assert path == os.path.realpath(os.sep.join([fs.root, 'some', 'dir']))
def test_mk_makes_a_dir(fs):
fs.mk('some/dir')
assert isdir(fs.resolve('some/dir'))
def test_remove_removes(fs):
assert isdir(fs.root)
fs.remove()
assert not isdir(fs.root)
def test_resolve_with_no_arg_is_equivalent_to_root(fs):
assert fs.resolve() == fs.root
|
[assets] Fix the way asset types are retrieved
Get relations to retrieve the related workflow.
|
import client from '@/store/api/client'
export default {
getAssetTypes (callback) {
client.get('/api/data/asset-types?relations=true', callback)
},
getAssetType (assetTypeId, callback) {
client.get(`/api/data/entity-types/${assetTypeId}`, callback)
},
newAssetType (assetType, callback) {
const data = {
name: assetType.name,
task_types: assetType.task_types
}
return client.ppost('/api/data/entity-types', data)
},
updateAssetType (assetType, callback) {
const data = {
name: assetType.name,
task_types: assetType.task_types
}
return client.pput(`/api/data/entity-types/${assetType.id}`, data)
},
deleteAssetType (assetType, callback) {
return client.pdel(`/api/data/entity-types/${assetType.id}`)
}
}
|
import client from '@/store/api/client'
export default {
getAssetTypes (callback) {
client.get('/api/data/asset-types', callback)
},
getAssetType (assetTypeId, callback) {
client.get(`/api/data/entity-types/${assetTypeId}`, callback)
},
newAssetType (assetType, callback) {
const data = {
name: assetType.name,
task_types: assetType.task_types
}
return client.ppost('/api/data/entity-types', data)
},
updateAssetType (assetType, callback) {
const data = {
name: assetType.name,
task_types: assetType.task_types
}
return client.pput(`/api/data/entity-types/${assetType.id}`, data)
},
deleteAssetType (assetType, callback) {
return client.pdel(`/api/data/entity-types/${assetType.id}`)
}
}
|
Fix code which executes on module load.
|
from pkg_resources import iter_entry_points
from spicedham.config import load_config
_plugins = None
def load_plugins():
"""
If not already loaded, load plugins.
"""
if _plugins == None
load_config()
_plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
_plugins.append(pluginClass())
def train(tag, training_data, is_spam):
"""
Calls each plugin's train function.
"""
for plugin in _plugins:
plugin.train(tag, training_data, is_spam)
def classify(tag, classification_data):
"""
Calls each plugin's classify function and averages the results.
"""
average_score = 0
total = 0
for plugin in _plugins:
value = plugin.classify(tag, classification_data)
# Skip _plugins which give a score of None
if value != None:
total += 1
average_score += value
# On rare occasions no _plugins will give scores. If so, return 0
if total > 0:
return average_score / total
else:
return 0
|
from pkg_resources import iter_entry_points
from spicedham.config import config
# TODO: Wrap all of this in an object with this in an __init__ function
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(tag, training_data, is_spam):
"""
Calls each plugin's train function.
"""
for plugin in plugins:
plugin.train(tag, training_data, is_spam)
def classify(tag, classification_data):
"""
Calls each plugin's classify function and averages the results.
"""
average_score = 0
total = 0
for plugin in plugins:
value = plugin.classify(tag, classification_data)
# Skip plugins which give a score of None
if value != None:
total += 1
average_score += value
# On rare occasions no plugins will give scores. If so, return 0
if total > 0:
return average_score / total
else:
return 0
|
Use SVGPointList API in test
|
describe('svgStar', function () {
var $compile,
$rootScope;
beforeEach(module('md5.svg-star'));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('should work as an element', function () {
var elt = angular.element('<svg-star></svg-star>');
$compile(elt)($rootScope);
$rootScope.$digest();
var svg = elt.find('svg');
expect(svg.length).toBe(1);
expect(svg.eq(0).attr('viewBox')).toBe('0 0 20 20');
var star = svg.find('polygon');
expect(star.length).toBe(1);
var points = star.eq(0).prop('points');
expect(points).not.toBeNull();
expect(points.numberOfItems).toBe(10);
});
});
|
describe('svgStar', function () {
var $compile,
$rootScope;
beforeEach(module('md5.svg-star'));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('should work as an element', function () {
var elt = angular.element('<svg-star></svg-star>');
$compile(elt)($rootScope);
$rootScope.$digest();
var svg = elt.find('svg');
expect(svg.length).toBe(1);
expect(svg.eq(0).attr('viewBox')).toBe('0 0 20 20');
var star = svg.find('polygon');
expect(star.length).toBe(1);
var points = star.eq(0).attr('points');
expect(points).not.toBeNull();
expect(points.split(/ /).length).toBe(10);
});
});
|
Add `pytest-cov` to collect test coverages
|
#!/usr/bin/env python
from __future__ import with_statement
from setuptools import setup, find_packages
import re
version = "0.0.1.dev.0"
with open("tdclient/version.py") as fp:
m = re.search(r"^__version__ *= *\"([^\"]*)\" *$", fp.read(), re.MULTILINE)
if m is not None:
version = m.group(1)
setup(
name="td-client",
version=version,
description="Treasure Data API library for Python",
author="Treasure Data, Inc.",
author_email="support@treasure-data.com",
url="http://treasuredata.com/",
install_requires=[
"msgpack-python>=0.4,<0.5",
"pytest>=2.6,<2.7",
"pytest-cov>=1.8,<1.9",
"tox>=1.8,<1.9",
],
packages=find_packages(),
test_suite="tdclient.test",
license="Apache Software License",
platforms="Posix; MacOS X; Windows",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Topic :: Internet",
],
)
|
#!/usr/bin/env python
from __future__ import with_statement
from setuptools import setup, find_packages
import re
version = "0.0.1.dev.0"
with open("tdclient/version.py") as fp:
m = re.search(r"^__version__ *= *\"([^\"]*)\" *$", fp.read(), re.MULTILINE)
if m is not None:
version = m.group(1)
setup(
name="td-client",
version=version,
description="Treasure Data API library for Python",
author="Treasure Data, Inc.",
author_email="support@treasure-data.com",
url="http://treasuredata.com/",
install_requires=[
"msgpack-python>=0.4,<0.5",
"pytest>=2.6,<2.7.0",
"tox>=1.8,<1.9.0",
],
packages=find_packages(),
test_suite="tdclient.test",
license="Apache Software License",
platforms="Posix; MacOS X; Windows",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Topic :: Internet",
],
)
|
Convert everything other than assets to app config
We're using Laravel's config resolving classes:
```PHP
$config = $app->make('config');
$config->get('app.version'); // '5.7.0b2'
```
|
<?php
namespace Concrete\Core\Config;
use Illuminate\Config\FileLoader;
use Illuminate\Filesystem\Filesystem;
class ConfigLoader extends FileLoader {
protected $config;
public function __construct(Filesystem $files, Config $config) {
$this->config = $config;
parent::__construct($files, DIR_APPLICATION . '/config');
$this->addNamespace('core', DIR_BASE . '/concrete/config');
}
public function load($environment, $group, $namespace = null)
{
if (is_null($namespace)) {
return array_replace_recursive(
(array) parent::load($environment, $group, 'core'),
(array) parent::load($environment, $group, $namespace)
);
}
return parent::load($environment, $group, $namespace);
}
}
|
<?php
namespace Concrete\Core\Config;
use Illuminate\Config\FileLoader;
use Illuminate\Filesystem\Filesystem;
class ConfigLoader extends FileLoader {
protected $config;
public function __construct(Filesystem $files, Config $config) {
$this->config = $config;
parent::__construct($files, DIR_APPLICATION . '/config');
$this->addNamespace('core', DIR_BASE . '/concrete/config');
}
public function load($environment, $group, $namespace = null)
{
if (is_null($namespace)) {
return array_replace_recursive(
parent::load($environment, $group, 'core'),
parent::load($environment, $group, $namespace)
(array) parent::load($environment, $group, 'core'),
(array) parent::load($environment, $group, $namespace)
);
}
return parent::load($environment, $group, $namespace);
}
}
|
Clean up view name in render performance tree
|
/**
A tree structure for assembling a list of render calls so they can be grouped and displayed nicely afterwards.
@class ProfileNode
**/
var ProfileNode = function(start, payload, parent) {
this.start = start;
this.timestamp = Date.now();
if (payload) {
if (payload.template) { this.name = payload.template; }
if (payload.object) {
var name = payload.object.toString();
var match = name.match(/:(ember\d+)>$/);
this.name = name.replace(/:?:ember\d+>$/, '').replace(/^</, '');
if (match && match.length > 1) {
this.viewGuid = match[1];
}
}
} else {
this.name = "unknown view";
}
if (parent) { this.parent = parent; }
this.children = [];
};
ProfileNode.prototype = {
finish: function(timestamp) {
this.time = (timestamp - this.start);
this.calcDuration();
// Once we attach to our parent, we remove that reference
// to avoid a graph cycle when serializing:
if (this.parent) {
this.parent.children.push(this);
this.parent = null;
}
},
calcDuration: function() {
this.duration = Math.round(this.time * 100) / 100;
}
};
export default ProfileNode;
|
/**
A tree structure for assembling a list of render calls so they can be grouped and displayed nicely afterwards.
@class ProfileNode
**/
var ProfileNode = function(start, payload, parent) {
this.start = start;
this.timestamp = Date.now();
if (payload) {
if (payload.template) { this.name = payload.template; }
if (payload.object) {
this.name = payload.object.toString();
var match = this.name.match(/:(ember\d+)>$/);
if (match && match.length > 1) {
this.viewGuid = match[1];
}
}
} else {
this.name = "unknown view";
}
if (parent) { this.parent = parent; }
this.children = [];
};
ProfileNode.prototype = {
finish: function(timestamp) {
this.time = (timestamp - this.start);
this.calcDuration();
// Once we attach to our parent, we remove that reference
// to avoid a graph cycle when serializing:
if (this.parent) {
this.parent.children.push(this);
this.parent = null;
}
},
calcDuration: function() {
this.duration = Math.round(this.time * 100) / 100;
}
};
export default ProfileNode;
|
Use base name as default package name
|
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var assignDeep = require('assign-deep');
var values = require('object-values');
var configureCommon = require('./configureCommon');
var configureDevelopment = require('./configureDevelopment');
module.exports = function(port, entryFile, config) {
var env = process.env.NODE_ENV || 'development';
var rootDir = path.dirname(entryFile);
var packagePath = path.resolve(rootDir, './package.json');
var options = {
globals: {
__DEV__: (env === 'development'),
'process.env.NODE_ENV': JSON.stringify(env)
},
package: fs.existsSync(packagePath) ? require(packagePath) : {name: path.basename(rootDir), title: 'Packup-App', version: '0.0.0', description: '', dependencies: {}},
root: rootDir,
entry: config.entry || entryFile,
port: port
}
var packupConfig = assignDeep(configureCommon(options), configureDevelopment(options));
var webpackConfig = assignDeep(packupConfig, {
module: {
loaders: values(packupConfig.loaders)
}
});
return webpackConfig;
}
|
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var assignDeep = require('assign-deep');
var values = require('object-values');
var configureCommon = require('./configureCommon');
var configureDevelopment = require('./configureDevelopment');
module.exports = function(port, entryFile, config) {
var env = process.env.NODE_ENV || 'development';
var rootDir = path.dirname(entryFile);
var packagePath = path.resolve(rootDir, './package.json');
var options = {
globals: {
__DEV__: (env === 'development'),
'process.env.NODE_ENV': JSON.stringify(env)
},
package: fs.existsSync(packagePath) ? require(packagePath) : {name: 'packup-app', title: 'Packup-App', version: '0.0.0', description: '', dependencies: {}},
root: rootDir,
entry: config.entry || entryFile,
port: port
}
var packupConfig = assignDeep(configureCommon(options), configureDevelopment(options));
var webpackConfig = assignDeep(packupConfig, {
module: {
loaders: values(packupConfig.loaders)
}
});
return webpackConfig;
}
|
Save Interactive State in addition to URL
Since calling `setLearnerUrl` does not alter the app behavior, we also
call `interactiveState` and post the current URL in a JSON blob there.
This does get saved on their end, and allows us to devise a redirection
mechanism to this saved URL when the user comes back.
|
"use strict";
var _ = require('lodash'),
iframePhone = require('iframe-phone'),
EMBED_FLAG = 'itsi_embed',
QUERY_SUFFIX = EMBED_FLAG + '=true';
var ItsiEmbed = function() {
this.phone = new iframePhone.getIFrameEndpoint();
this.url = window.location.href + '?' + QUERY_SUFFIX;
this.interactiveState = { url: this.url };
this.setLearnerUrl = function(url) {
if (url) {
this.url = url + (url.indexOf('?') > 0 ? '&' : '?') + QUERY_SUFFIX;
this.interactiveState = { url: this.url };
}
this.phone.post('setLearnerUrl', this.url);
this.phone.post('interactiveState', this.interactiveState);
};
this.phone.addListener('getLearnerUrl', _.bind(this.setLearnerUrl, this));
this.phone.addListener('getInteractiveState', _.bind(this.setLearnerUrl, this));
this.phone.initialize();
};
module.exports = {
ItsiEmbed: ItsiEmbed
};
|
"use strict";
var _ = require('lodash'),
iframePhone = require('iframe-phone'),
EMBED_FLAG = 'itsi_embed',
QUERY_SUFFIX = EMBED_FLAG + '=true';
var ItsiEmbed = function() {
this.phone = new iframePhone.getIFrameEndpoint();
this.url = window.location.href + '?' + QUERY_SUFFIX;
this.setLearnerUrl = function(url) {
if (url) {
this.url = url + (url.indexOf('?') > 0 ? '&' : '?') + QUERY_SUFFIX;
}
this.phone.post('setLearnerUrl', this.url);
};
this.phone.addListener('getLearnerUrl', _.bind(this.setLearnerUrl, this));
this.phone.initialize();
};
module.exports = {
ItsiEmbed: ItsiEmbed
};
|
Upgrade the version to force reinstall by wheels
|
from setuptools import setup
import os
setup(
name = "cmsplugin-bootstrap-carousel",
packages = ['cmsplugin_bootstrap_carousel',],
package_data = {
'': [
'templates/cmsplugin_bootstrap_carousel/*.html',
]
},
version = "0.1.3",
description = "Bootstrap carousel plugin for django-cms 2.2",
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
author = "Antoine Nguyen",
author_email = "tonio@ngyn.org",
url = "http://bitbucket.org/tonioo/cmsplugin-bootstrap-carousel",
license = "BSD",
keywords = ["django", "django-cms", "bootstrap", "carousel"],
classifiers = [
"Programming Language :: Python",
"Environment :: Web Environment",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Framework :: Django"
],
include_package_data = True,
zip_safe = True,
install_requires = ['Django-CMS>=2.2'],
)
|
from setuptools import setup
import os
setup(
name = "cmsplugin-bootstrap-carousel",
packages = ['cmsplugin_bootstrap_carousel',],
package_data = {
'': [
'templates/cmsplugin_bootstrap_carousel/*.html',
]
},
version = "0.1.2",
description = "Bootstrap carousel plugin for django-cms 2.2",
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
author = "Antoine Nguyen",
author_email = "tonio@ngyn.org",
url = "http://bitbucket.org/tonioo/cmsplugin-bootstrap-carousel",
license = "BSD",
keywords = ["django", "django-cms", "bootstrap", "carousel"],
classifiers = [
"Programming Language :: Python",
"Environment :: Web Environment",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Framework :: Django"
],
include_package_data = True,
zip_safe = True,
install_requires = ['Django-CMS>=2.2'],
)
|
Make variable names more explicit
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division, absolute_import
from openfisca_core.commons import to_unicode
def build_entities(tax_benefit_system):
entities = {
entity.key: build_entity(entity)
for entity in tax_benefit_system.entities
}
return entities
def build_entity(entity):
formatted_entity = {
'plural': entity.plural,
'description': to_unicode(entity.label),
'documentation': to_unicode(entity.doc)
}
if hasattr(entity, 'roles'):
formatted_entity['roles'] = {
role.key: build_role(role)
for role in entity.roles
}
return formatted_entity
def build_role(role):
formatted_role = {
'plural': role.plural,
'description': role.doc
}
if role.max:
formatted_role['max'] = role.max
if role.subroles:
formatted_role['max'] = len(role.subroles)
formatted_role['mandatory'] = True if formatted_role.get('max') else False
return formatted_role
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division, absolute_import
from openfisca_core.commons import to_unicode
def build_entities(tax_benefit_system):
entities = {
entity.key: build_entity(entity)
for entity in tax_benefit_system.entities
}
return entities
def build_entity(entity):
entity_formated = {
'plural': entity.plural,
'description': to_unicode(entity.doc)
}
if hasattr(entity, 'roles'):
entity_formated['roles'] = \
{
role.key: build_role(role)
for role in entity.roles
}
return entity_formated
def build_role(role):
role_formated = {
'plural': role.plural,
'description': role.doc
}
if role.max:
role_formated['max'] = role.max
if role.subroles:
role_formated['max'] = len(role.subroles)
role_formated['mandatory'] = True if role_formated.get('max') else False
return role_formated
|
Remove some fork specific documentation
|
<?php
namespace SumoCoders\FrameworkCoreBundle\ValueObject;
use Doctrine\ORM\Mapping as ORM;
/**
* The following things are mandatory to use this class.
*
* You need to implement the method getUploadDir.
* When using this class in an entity certain life cycle callbacks should be called
* prepareToUpload for @ORM\PrePersist() and @ORM\PreUpdate()
* upload for @ORM\PostPersist() and @ORM\PostUpdate()
* remove for @ORM\PostRemove()
*
* The following things are optional
* A fallback image can be set by setting the full path of the image to the FALLBACK_IMAGE constant
*/
abstract class AbstractImage extends AbstractFile
{
/**
* @var string|null
*/
const FALLBACK_IMAGE = null;
/**
* @return string
*/
public function getWebPath()
{
$webPath = parent::getWebPath();
if (empty($webPath)) {
return static::FALLBACK_IMAGE;
}
return $webPath;
}
/**
* @return null|string
*/
public function getFallbackImage()
{
return static::FALLBACK_IMAGE;
}
}
|
<?php
namespace SumoCoders\FrameworkCoreBundle\ValueObject;
use Doctrine\ORM\Mapping as ORM;
/**
* The following things are mandatory to use this class.
*
* You need to implement the method getUploadDir.
* When using this class in an entity certain life cycle callbacks should be called
* prepareToUpload for @ORM\PrePersist() and @ORM\PreUpdate()
* upload for @ORM\PostPersist() and @ORM\PostUpdate()
* remove for @ORM\PostRemove()
*
* The following things are optional
* A fallback image can be set by setting the full path of the image to the FALLBACK_IMAGE constant
* By default we will use the fork way for image sizes (source, 100X100 etc)
* if you don't want it set GENERATE_THUMBNAILS to false
*/
abstract class AbstractImage extends AbstractFile
{
/**
* @var string|null
*/
const FALLBACK_IMAGE = null;
/**
* @return string
*/
public function getWebPath()
{
$webPath = parent::getWebPath();
if (empty($webPath)) {
return static::FALLBACK_IMAGE;
}
return $webPath;
}
/**
* @return null|string
*/
public function getFallbackImage()
{
return static::FALLBACK_IMAGE;
}
}
|
Set default race and class without extra database queries
|
from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/index.html', context)
def view_character(request, character_id):
character = get_object_or_404(Character, pk=character_id)
context = {'character': character}
return render(request, 'characters/view_character.html', context)
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race_id=1,
cclass_id=1
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
|
from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/index.html', context)
def view_character(request, character_id):
character = get_object_or_404(Character, pk=character_id)
context = {'character': character}
return render(request, 'characters/view_character.html', context)
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
race = Race.objects.get(id=1)
cclass = Class.objects.get(id=1)
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race=race,
cclass=cclass
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
|
Add correction between CodeMirror lint plugin to display warning on expected line number
|
/*jslint browser*/
// This file is the shim layer to connect jslint to CodeMirror editor
import jslint from "./jslint.mjs";
const CodeMirror = window.CodeMirror;
function validator(text, options) {
let data = jslint(text, options, options.globals);
let warnings = data.warnings;
let output = [];
if (data.stop) {
output.push({
message: "JSLint was unable to finish.",
severity: "warning",
from: new CodeMirror.Pos(0, 0),
to: new CodeMirror.Pos(0, 0)
});
}
warnings.forEach(function (warning) {
output.push({
message: warning.message,
severity: "error",
from: new CodeMirror.Pos(warning.line - 1, warning.column - 1),
to: new CodeMirror.Pos(warning.line - 1, warning.column + 1)
});
});
return output;
}
CodeMirror.registerHelper("lint", "javascript", validator);
|
/*jslint browser*/
// This file is the shim layer to connect jslint to CodeMirror editor
import jslint from "./jslint.mjs";
const CodeMirror = window.CodeMirror;
function validator(text, options) {
let data = jslint(text, options, options.globals);
let warnings = data.warnings;
let output = [];
if (data.stop) {
output.push({
message: "JSLint was unable to finish.",
severity: "warning",
from: new CodeMirror.Pos(0, 0),
to: new CodeMirror.Pos(0, 0)
});
}
warnings.forEach(function (warning) {
output.push({
message: warning.message,
severity: "error",
from: new CodeMirror.Pos(warning.line, warning.column - 1),
to: new CodeMirror.Pos(warning.line, warning.column + 1)
});
});
return output;
}
CodeMirror.registerHelper("lint", "javascript", validator);
|
Load OSM tiles via https
|
"use strict";
import React from "react";
import ReactDOM from "react-dom";
import Leaflet from "leaflet";
export default class DocMap extends React.Component {
componentDidMount() {
this.map = Leaflet.map(ReactDOM.findDOMNode(this));
this.map.addLayer(Leaflet.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"));
this.updateMap();
}
componentWillUnmount() {
this.map.remove();
this.map = null;
}
updateMap() {
if (this.multiPolyline) {
this.map.removeLayer(this.multiPolyline);
}
const latlngs = this.props.log.tracks.map((track) => {
return track.map((point) => {
return [point.lat, point.lon];
});
});
this.multiPolyline = Leaflet.multiPolyline(latlngs, { color: "red" });
this.multiPolyline.addTo(this.map);
this.map.fitBounds(this.multiPolyline.getBounds());
}
render() {
if (this.map) {
this.updateMap();
}
return <div className="log-map"></div>;
}
}
|
"use strict";
import React from "react";
import ReactDOM from "react-dom";
import Leaflet from "leaflet";
export default class DocMap extends React.Component {
componentDidMount() {
this.map = Leaflet.map(ReactDOM.findDOMNode(this));
this.map.addLayer(Leaflet.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"));
this.updateMap();
}
componentWillUnmount() {
this.map.remove();
this.map = null;
}
updateMap() {
if (this.multiPolyline) {
this.map.removeLayer(this.multiPolyline);
}
const latlngs = this.props.log.tracks.map((track) => {
return track.map((point) => {
return [point.lat, point.lon];
});
});
this.multiPolyline = Leaflet.multiPolyline(latlngs, { color: "red" });
this.multiPolyline.addTo(this.map);
this.map.fitBounds(this.multiPolyline.getBounds());
}
render() {
if (this.map) {
this.updateMap();
}
return <div className="log-map"></div>;
}
}
|
Remove warn only from fabric file
|
from fabric.api import local
CMD_MANAGE = "python manage.py "
def auto_schema():
schema('rockit.foundation.core')
schema('rockit.plugins.mailout')
schema('rockit.plugins.razberry')
def build():
migrate('rockit.foundation.core')
migrate('rockit.plugins.mailout')
migrate('rockit.plugins.razberry')
load_data('rockit/foundation/core/fixtures/settings.json')
load_data('rockit/plugins/mailout/fixtures/servers.json')
test()
def load_data(path):
local(CMD_MANAGE + 'loaddata %s' % path)
def migrate(app):
local(CMD_MANAGE + 'migrate %s' % app)
def runserver(localonly=True):
if localonly:
local(CMD_MANAGE + 'runserver')
else:
local(CMD_MANAGE + 'runserver 0.0.0.0')
def schema(app):
local(CMD_MANAGE + 'schemamigration %s --auto' % app)
def setup(environment):
local('pip install -r requirements/%s' % environment)
def test():
local(CMD_MANAGE + 'test')
|
from fabric.api import local
from fabric.api import warn_only
CMD_MANAGE = "python manage.py "
def auto_schema():
with warn_only():
schema('rockit.foundation.core')
schema('rockit.plugins.mailout')
schema('rockit.plugins.razberry')
def build():
migrate('rockit.foundation.core')
migrate('rockit.plugins.mailout')
migrate('rockit.plugins.razberry')
load_data('rockit/foundation/core/fixtures/settings.json')
load_data('rockit/plugins/mailout/fixtures/servers.json')
test()
def load_data(path):
local(CMD_MANAGE + 'loaddata %s' % path)
def migrate(app):
local(CMD_MANAGE + 'migrate %s' % app)
def runserver(localonly=True):
if localonly:
local(CMD_MANAGE + 'runserver')
else:
local(CMD_MANAGE + 'runserver 0.0.0.0')
def schema(app):
local(CMD_MANAGE + 'schemamigration %s --auto' % app)
def setup(environment):
local('pip install -r requirements/%s' % environment)
def test():
local(CMD_MANAGE + 'test')
|
Check firm object exists to avoid error
|
<!---
<?php
if (!empty(Yii::app()->session['user'])) {
$user = Yii::app()->session['user'];
} else {
$user = User::model()->findByPk(Yii::app()->user->id);
}
$firm = Firm::model()->findByPk($this->selectedFirmId);
if (file_exists("/etc/hostname")) {
$hostname = trim(file_get_contents("/etc/hostname"));
} else {
$hostname = trim(`hostname`);
}
if (is_object($user)) {
$username = "$user->username ($user->id)";
if($firm) {
$firm = "$firm->name ($firm->id)";
} else {
$firm = 'Not found'; // selectedFirmId seems to not be getting initialised sometimes
}
} else {
$username = 'Not logged in';
$firm = 'Not logged in';
}
$commit = preg_replace('/[\s\t].*$/s','',@file_get_contents(@$_SERVER['DOCUMENT_ROOT']."/.git/FETCH_HEAD"));
?>
Server: <?php echo $hostname?>
Date: <?php echo date('d.m.Y H:i:s')?>
Commit: <?php echo $commit?>
User agent: <?php echo @$_SERVER['HTTP_USER_AGENT']?>
Client IP: <?php echo @$_SERVER['REMOTE_ADDR']?>
Username: <?php echo $username?>
Firm: <?php echo $firm?>
-->
|
<!---
<?php
if (!empty(Yii::app()->session['user'])) {
$user = Yii::app()->session['user'];
} else {
$user = User::model()->findByPk(Yii::app()->user->id);
}
$firm = Firm::model()->findByPk($this->selectedFirmId);
if (file_exists("/etc/hostname")) {
$hostname = trim(file_get_contents("/etc/hostname"));
} else {
$hostname = trim(`hostname`);
}
if (is_object($user)) {
$username = "$user->username ($user->id)";
$firm = "$firm->name ($firm->id)";
} else {
$username = 'Not logged in';
$firm = 'Not logged in';
}
$commit = preg_replace('/[\s\t].*$/s','',@file_get_contents(@$_SERVER['DOCUMENT_ROOT']."/.git/FETCH_HEAD"));
?>
Server: <?php echo $hostname?>
Date: <?php echo date('d.m.Y H:i:s')?>
Commit: <?php echo $commit?>
User agent: <?php echo @$_SERVER['HTTP_USER_AGENT']?>
Client IP: <?php echo @$_SERVER['REMOTE_ADDR']?>
Username: <?php echo $username?>
Firm: <?php echo $firm?>
-->
|
Fix in temp client data.
|
<?php
/*
* Bear CMS addon for Bear Framework
* https://bearcms.com/
* Copyright (c) 2016 Amplilabs Ltd.
* Free to use under the MIT license.
*/
namespace BearCMS\Internal;
use BearFramework\App;
class TempClientData
{
static function get($key)
{
$app = App::get();
$dataHash = substr($key, 0, 32);
try {
$data = gzuncompress($app->encryption->decrypt(base64_decode(substr($key, 32))));
} catch (\Exception $e) {
return;
}
if (md5($data) !== $dataHash) {
return;
}
$data = json_decode($data, true);
if (is_array($data) && isset($data[0], $data[1]) && $data[0] === 'bearcms') {
return $data[1];
}
return false;
}
static function set($data)
{
$app = App::get();
$encodedData = json_encode(['bearcms', $data]);
return md5($encodedData) . base64_encode($app->encryption->encrypt(gzcompress($encodedData)));
}
}
|
<?php
/*
* Bear CMS addon for Bear Framework
* https://bearcms.com/
* Copyright (c) 2016 Amplilabs Ltd.
* Free to use under the MIT license.
*/
namespace BearCMS\Internal;
use BearFramework\App;
class TempClientData
{
static function get($key)
{
$app = App::get();
$dataHash = substr($key, 0, 32);
try {
$data = gzuncompress($app->encryption->decrypt(base64_decode(substr($key, 32))));
} catch (\Exception $e) {
return;
}
if (md5($data) !== $dataHash) {
return;
}
$data = json_decode($data);
if (is_array($data) && isset($data[0], $data[1]) && $data[0] === 'bearcms') {
return $data[1];
}
return false;
}
static function set($data)
{
$app = App::get();
$encodedData = json_encode(['bearcms', $data]);
return md5($encodedData) . base64_encode($app->encryption->encrypt(gzcompress($encodedData)));
}
}
|
gltfpack: Fix texture compression spawn in node.js
Our previous code blindly replaced the executable in the input command
with the env. variable value, which actually didn't handle cases when
the environment variable wasn't set and additionally didn't handle paths
with spaces well.
We now use shell:false execution option and give it a pre-split command
line - this doesn't work for arguments with spaces but we never handled
them correctly (and also they shouldn't occur as the paths that are
passed to the compressor are that of temp files...).
|
#!/usr/bin/env node
// This file is part of gltfpack and is distributed under the terms of MIT License.
var gltfpack = require('./library.js');
var fs = require('fs');
var cp = require('child_process');
var args = process.argv.slice(2);
var paths = {
"basisu": process.env["BASISU_PATH"],
"toktx": process.env["TOKTX_PATH"],
};
var interface = {
read: function (path) {
return fs.readFileSync(path);
},
write: function (path, data) {
fs.writeFileSync(path, data);
},
execute: function (command) {
var arg = command.split(' ');
var exe = arg.shift();
// perform substitution of command executable with environment-specific paths
exe = paths[exe] || exe;
var ret = cp.spawnSync(exe, arg);
return ret.status == null ? 256 : ret.status;
},
unlink: function (path) {
fs.unlinkSync(path);
},
};
gltfpack.pack(args, interface)
.then(function (log) {
process.stdout.write(log);
process.exit(0);
})
.catch(function (err) {
process.stderr.write(err.message);
process.exit(1);
});
|
#!/usr/bin/env node
// This file is part of gltfpack and is distributed under the terms of MIT License.
var gltfpack = require('./library.js');
var fs = require('fs');
var cp = require('child_process');
var args = process.argv.slice(2);
var paths = {
"basisu": process.env["BASISU_PATH"],
"toktx": process.env["TOKTX_PATH"],
};
var interface = {
read: function (path) {
return fs.readFileSync(path);
},
write: function (path, data) {
fs.writeFileSync(path, data);
},
execute: function (command) {
// perform substitution of command executable with environment-specific paths
var pk = Object.keys(paths);
for (var pi = 0; pi < pk.length; ++pi) {
if (command.startsWith(pk[pi] + " ")) {
command = paths[pk[pi]] + command.substr(pk[pi].length);
break;
}
}
var ret = cp.spawnSync(command, [], {shell:true});
return ret.status == null ? 256 : ret.status;
},
unlink: function (path) {
fs.unlinkSync(path);
},
};
gltfpack.pack(args, interface)
.then(function (log) {
process.stdout.write(log);
process.exit(0);
})
.catch(function (err) {
process.stderr.write(err.message);
process.exit(1);
});
|
FIx null pointer in gcm registration service
|
package com.rehivetech.beeeon.gcm;
import android.app.IntentService;
import android.content.Intent;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.rehivetech.beeeon.R;
import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.model.GcmModel;
import java.io.IOException;
import timber.log.Timber;
/**
* Created by martin on 21.01.16.
*/
public class GcmRegistrationIntentService extends IntentService {
public GcmRegistrationIntentService() {
super("GcmRegistrationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
String token = InstanceID.getInstance(this).getToken(getString(R.string.api_keys_google_console_project_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Controller controller = Controller.getInstance(this);
GcmModel gcmModel = controller.getGcmModel();
gcmModel.saveGcm(token);
} catch (IOException | NullPointerException e) {
Timber.e("Error while getting GCM token");
e.printStackTrace();
}
}
}
|
package com.rehivetech.beeeon.gcm;
import android.app.IntentService;
import android.content.Intent;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.rehivetech.beeeon.R;
import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.model.GcmModel;
import java.io.IOException;
import timber.log.Timber;
/**
* Created by martin on 21.01.16.
*/
public class GcmRegistrationIntentService extends IntentService {
public GcmRegistrationIntentService() {
super("GcmRegistrationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
String token = InstanceID.getInstance(this).getToken(getString(R.string.api_keys_google_console_project_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Controller controller = Controller.getInstance(this);
GcmModel gcmModel = controller.getGcmModel();
gcmModel.saveGcm(token);
} catch (IOException e) {
Timber.e("Error while getting GCM token");
e.printStackTrace();
}
}
}
|
Remove namespace package metadata to fix sdist
|
from setuptools import setup
with open('README.md') as desc:
long_description = desc.read()
setup(name='beets-check',
version='0.9.0-beta.2',
description='beets plugin verifying file integrity with checksums',
long_description=long_description,
author='Thomas Scholtes',
author_email='thomas-scholtes@gmx.de',
url='http://www.github.com/geigerzaehler/beets-check',
license='MIT',
platforms='ALL',
test_suite='test',
packages=['beetsplug'],
install_requires=[
'beets>=1.3.4',
],
classifiers=[
'Topic :: Multimedia :: Sound/Audio',
'Topic :: Multimedia :: Sound/Audio :: Players :: MP3',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Environment :: Web Environment',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
|
from setuptools import setup
with open('README.md') as desc:
long_description = desc.read()
setup(name='beets-check',
version='0.9.0-beta.2',
description='beets plugin verifying file integrity with checksums',
long_description=long_description,
author='Thomas Scholtes',
author_email='thomas-scholtes@gmx.de',
url='http://www.github.com/geigerzaehler/beets-check',
license='MIT',
platforms='ALL',
test_suite='test',
packages=['beetsplug'],
namespace_packages=['beetsplug'],
install_requires=[
'beets>=1.3.4',
],
classifiers=[
'Topic :: Multimedia :: Sound/Audio',
'Topic :: Multimedia :: Sound/Audio :: Players :: MP3',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Environment :: Web Environment',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
|
Add documentation of the new functions
|
"""Example of reversible reaction."""
import os
from chemkinlib.utils import Parser
from chemkinlib.reactions import ReactionSystems
from chemkinlib.config import DATA_DIRECTORY
# USER INPUT: reaction (xml) file
xml_filename = os.path.join(DATA_DIRECTORY, "rxns_reversible.xml")
parser = Parser.ReactionParser(xml_filename)
# USER INPUTS (concentrations and temperatures)
concentration = ({'H':1, 'H2':1, 'H2O':1, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1})
temperature = 1000
# Set up reaction system
rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list,
parser.NASA_poly_coefs,
temperature,
concentration)
#compute the concentration change with timestep
for i in range(10):
dt = 0.001
print(rxnsys.step(dt))
# Compute and sort reaction rates
rxnrates_dict = rxnsys.sort_reaction_rates()
# display reaction rates by species
for k, v in rxnrates_dict.items():
print("d[{0}]/dt : \t {1:e}".format(k, v))
|
"""Example of reversible reaction."""
import os
from chemkinlib.utils import Parser
from chemkinlib.reactions import ReactionSystems
from chemkinlib.config import DATA_DIRECTORY
# USER INPUT: reaction (xml) file
xml_filename = os.path.join(DATA_DIRECTORY, "rxns_reversible.xml")
parser = Parser.ReactionParser(xml_filename)
# USER INPUTS (concentrations and temperatures)
concentration = ({'H':1, 'H2':1, 'H2O':1, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1})
temperature = 1000
# Set up reaction system
rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list,
parser.NASA_poly_coefs,
temperature,
concentration)
# Compute and sort reaction rates
rxnrates_dict = rxnsys.sort_reaction_rates()
# display reaction rates by species
for k, v in rxnrates_dict.items():
print("d[{0}]/dt : \t {1:e}".format(k, v))
|
Update deps to pull in YAML support
|
#!/usr/bin/env python
import os, sys, glob
from setuptools import setup, find_packages
setup(
name='aegea',
version='0.2.0',
url='https://github.com/kislyuk/aegea',
license='Proprietary',
author='Andrey Kislyuk',
author_email='kislyuk@gmail.com',
description='Amazon Web Services Operator Interface',
long_description=open('README.rst').read(),
install_requires=[
'boto3 >= 1.2.6',
'argcomplete >= 1.1.0',
'paramiko >= 1.16.0',
'requests >= 2.9.1',
'tweak >= 0.1.0',
'keymaker >= 0.1.7',
'pyyaml >= 3.11'
],
extras_require={
':python_version == "2.7"': ['enum34 >= 1.0.4', 'ipaddress >= 1.0.16'],
':python_version == "3.3"': ['enum34 >= 1.0.4']
},
packages=find_packages(exclude=['test']),
scripts=glob.glob('scripts/*'),
platforms=['MacOS X', 'Posix'],
test_suite='test',
include_package_data=True
)
|
#!/usr/bin/env python
import os, sys, glob
from setuptools import setup, find_packages
setup(
name='aegea',
version='0.1.0',
url='https://github.com/kislyuk/aegea',
license='Proprietary',
author='Andrey Kislyuk',
author_email='kislyuk@gmail.com',
description='Amazon Web Services Operator Interface',
long_description=open('README.rst').read(),
install_requires=[
'boto3 >= 1.2.6',
'argcomplete >= 1.1.0',
'paramiko >= 1.16.0',
'requests >= 2.9.1',
'tweak >= 0.0.2',
'keymaker >= 0.1.7',
'pyyaml >= 3.11'
],
extras_require={
':python_version == "2.7"': ['enum34 >= 1.0.4', 'ipaddress >= 1.0.16'],
':python_version == "3.3"': ['enum34 >= 1.0.4']
},
packages=find_packages(exclude=['test']),
scripts=glob.glob('scripts/*'),
platforms=['MacOS X', 'Posix'],
test_suite='test',
include_package_data=True
)
|
Fix tests using testdata with trailing newlines by slicing off whitespace
|
package mbtest
import (
"bytes"
"io/ioutil"
"path/filepath"
"testing"
)
const testdataDir = "testdata"
// Testdata returns a file's bytes based on the path relative to the testdata
// directory. It fails the test if the testdata file can not be read.
func Testdata(t *testing.T, relativePath string) []byte {
path := filepath.Join(testdataDir, relativePath)
b, err := ioutil.ReadFile(path)
if err != nil {
t.Fatalf("%s", err)
}
return b
}
// AssertTestdata gets testdata and asserts it equals actual. We start by
// slicing off all leading and trailing white space, as defined by Unicode.
func AssertTestdata(t *testing.T, relativePath string, actual []byte) {
expected := bytes.TrimSpace(Testdata(t, relativePath))
actual = bytes.TrimSpace(actual)
if !bytes.Equal(expected, actual) {
t.Fatalf("expected %s, got %s", expected, actual)
}
}
// AssertEndpointCalled fails the test if the last request was not made to the
// provided endpoint (e.g. combination of HTTP method and path).
func AssertEndpointCalled(t *testing.T, method, path string) {
if Request.Method != method {
t.Fatalf("expected %s, got %s", method, Request.Method)
}
if escapedPath := Request.URL.EscapedPath(); escapedPath != path {
t.Fatalf("expected %s, got %s", path, escapedPath)
}
}
|
package mbtest
import (
"bytes"
"io/ioutil"
"path/filepath"
"testing"
)
const testdataDir = "testdata"
// Testdata returns a file's bytes based on the path relative to the testdata
// directory. It fails the test if the testdata file can not be read.
func Testdata(t *testing.T, relativePath string) []byte {
path := filepath.Join(testdataDir, relativePath)
b, err := ioutil.ReadFile(path)
if err != nil {
t.Fatalf("%s", err)
}
return b
}
// AssertTestdata gets testdata and asserts it equals actual.
func AssertTestdata(t *testing.T, relativePath string, actual []byte) {
expected := Testdata(t, relativePath)
if !bytes.Equal(expected, actual) {
t.Fatalf("expected %s, got %s", expected, actual)
}
}
// AssertEndpointCalled fails the test if the last request was not made to the
// provided endpoint (e.g. combination of HTTP method and path).
func AssertEndpointCalled(t *testing.T, method, path string) {
if Request.Method != method {
t.Fatalf("expected %s, got %s", method, Request.Method)
}
if escapedPath := Request.URL.EscapedPath(); escapedPath != path {
t.Fatalf("expected %s, got %s", path, escapedPath)
}
}
|
Replace manual packages list with find_packages
|
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='LoadStone',
version='0.1',
description='Interface for FFXIV Lodestone',
author='Sami Elahmadie',
author_email='s.elahmadie@gmail.com',
url='https://github.com/Demotivated/loadstone/',
packages=find_packages(),
install_requires=[
'flask==0.10.1',
'flask_sqlalchemy==2.0',
'lxml==3.4.4',
'psycopg2==2.6.1',
'pytest==2.8.2',
'pytest-flask==0.10.0',
'requests==2.8.1',
'sphinx==1.3.1',
'sphinx-rtd-theme==0.1.9',
]
)
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='LoadStone',
version='0.1',
description='Interface for FFXIV Lodestone',
author='Sami Elahmadie',
author_email='s.elahmadie@gmail.com',
url='https://github.com/Demotivated/loadstone/',
packages=['api'],
install_requires=[
'flask==0.10.1',
'flask_sqlalchemy==2.0',
'lxml==3.4.4',
'psycopg2==2.6.1',
'pytest==2.8.2',
'pytest-flask==0.10.0',
'requests==2.8.1',
'sphinx==1.3.1',
'sphinx-rtd-theme==0.1.9',
]
)
|
Add a line break between each version in changelog.
|
<?php
$template->assign('PageTopic','Change Log');
$db2 = new SmrMySqlDatabase();
$db->query('SELECT *
FROM version
WHERE version_id <= ' . $var['version_id'] . '
ORDER BY version_id DESC');
while ($db->nextRecord())
{
$version_id = $db->getField('version_id');
$version = $db->getField('major_version') . '.' . $db->getField('minor_version') . '.' . $db->getField('patch_level');
$went_live = $db->getField('went_live');
// get human readable format for date
if ($went_live > 0)
$went_live = date(DATE_FULL_SHORT, $went_live);
else
$went_live = 'never';
$PHP_OUTPUT.=('<b><small>'.$version.' ('.$went_live.'):</small></b>');
$PHP_OUTPUT.=('<ul>');
$db2->query('SELECT *
FROM changelog
WHERE version_id = '.$version_id.'
ORDER BY changelog_id');
while ($db2->nextRecord())
$PHP_OUTPUT.=('<li>' . stripslashes($db2->getField('change_title')) . '<br /><small>' . stripslashes($db2->getField('change_message')) . '</small></li>');
$PHP_OUTPUT.=('</ul><br />');
}
?>
|
<?php
$template->assign('PageTopic','Change Log');
$db2 = new SmrMySqlDatabase();
$db->query('SELECT *
FROM version
WHERE version_id <= ' . $var['version_id'] . '
ORDER BY version_id DESC');
while ($db->nextRecord()) {
$version_id = $db->getField('version_id');
$version = $db->getField('major_version') . '.' . $db->getField('minor_version') . '.' . $db->getField('patch_level');
$went_live = $db->getField('went_live');
// get human readable format for date
if ($went_live > 0)
$went_live = date(DATE_FULL_SHORT, $went_live);
else
$went_live = 'never';
$PHP_OUTPUT.=('<b><small>'.$version.' ('.$went_live.'):</small></b>');
$PHP_OUTPUT.=('<ul>');
$db2->query('SELECT *
FROM changelog
WHERE version_id = '.$version_id.'
ORDER BY changelog_id');
while ($db2->nextRecord())
$PHP_OUTPUT.=('<li>' . stripslashes($db2->getField('change_title')) . '<br /><small>' . stripslashes($db2->getField('change_message')) . '</small></li>');
$PHP_OUTPUT.=('</ul>');
}
?>
|
Reset methode toegevoegd voor de resetKnop
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package keygamep3;
/**
*
* @author rubenvde
*/
public class Dimensie {
private int x;
private int y;
public Dimensie(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public void setDimensieReset(){
this.x = 0;
this.y = 0;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package keygamep3;
/**
*
* @author rubenvde
*/
public class Dimensie {
private int x;
private int y;
public Dimensie(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
}
|
Use ASTRUNDIR, not /tmp, for the lockfile
Use "scheduler.lock" as the lockfile name.
Need to read in the configuration files first,
so we know which directory will hold the lock.
|
#!/usr/bin/env php
<?php
// vim: set ai ts=4 sw=4 ft=php:
// License for all code of this FreePBX module can be found in the license file inside the module directory
// Copyright 2013 Schmooze Com Inc.
//
// Dashboard Scheduler.
// Runs every minute.
//
// Start quickly.
$bootstrap_settings['freepbx_auth'] = false; // Just in case.
$restrict_mods = true; // Takes startup from 0.2 seconds to 0.07 seconds.
include '/etc/freepbx.conf';
$lockfile = \FreePBX::Config()->get('ASTRUNDIR')."/scheduler.lock";
// Sleep to fix crazy issues with large VM hosting providers
sleep(mt_rand(1,30));
// Create a lock to make sure no more than one instance of this
// program can be running on a machine at a time
$fh = fopen($lockfile, "a");
if (!$fh || !flock($fh, LOCK_EX|LOCK_NB)) {
// Unable to lock, we're already running.
exit;
}
// Run the trigger
\FreePBX::Dashboard()->runTrigger();
// remove lockfile, and then close handle to release kernel lock
unlink($lockfile);
fclose($fh);
?>
|
#!/usr/bin/env php
<?php
// vim: set ai ts=4 sw=4 ft=php:
// License for all code of this FreePBX module can be found in the license file inside the module directory
// Copyright 2013 Schmooze Com Inc.
//
// Dashboard Scheduler.
// Runs every minute.
//
$lockfile = "/tmp/scheduler-lock";
// Sleep to fix crazy issues with large VM hosting providers
sleep(mt_rand(1,30));
// Create a lock to make sure no more than one instance of this
// program can be running on a machine at a time
$fh = fopen($lockfile, "a");
if (!$fh || !flock($fh, LOCK_EX|LOCK_NB)) {
// Unable to lock, we're already running.
exit;
}
// Start quickly.
$bootstrap_settings['freepbx_auth'] = false; // Just in case.
$restrict_mods = true; // Takes startup from 0.2 seconds to 0.07 seconds.
include '/etc/freepbx.conf';
// Run the trigger
\FreePBX::Dashboard()->runTrigger();
// remove lockfile, and then close handle to release kernel lock
unlink($lockfile);
fclose($fh);
?>
|
Make sure serialized content don't get unserialized
|
var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(name, val, opt) {
_cookies[name] = val;
// Cookies only work in the browser
if (typeof document === 'undefined') return;
// allow you to work with cookies as objects.
// make sure a serialized value returns as serialized again
if (typeof val === 'object' || typeof val === 'string') val = JSON.stringify(val);
document.cookie = cookie.serialize(name, val, opt);
}
function remove(name) {
if (typeof document === 'undefined') return;
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
var reactCookie = {
load: load,
save: save,
remove: remove
};
if (typeof module !== 'undefined') {
module.exports = reactCookie
}
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
}
|
var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(name, val, opt) {
_cookies[name] = val;
// Cookies only work in the browser
if (typeof document === 'undefined') return;
// allow you to work with cookies as objects.
if (typeof val === 'object') val = JSON.stringify(val);
document.cookie = cookie.serialize(name, val, opt);
}
function remove(name) {
if (typeof document === 'undefined') return;
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
var reactCookie = {
load: load,
save: save,
remove: remove
};
if (typeof module !== 'undefined') {
module.exports = reactCookie
}
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
}
|
Optimize heavily called function `isSameNodeType()`
|
import { clone, isString, toLowerCase, hasOwnProperty } from '../util';
import { isFunctionalComponent } from './functional-component';
import { getNodeType } from '../dom';
/** Check if two nodes are equivalent.
* @param {Element} node
* @param {VNode} vnode
* @private
*/
export function isSameNodeType(node, vnode) {
if (isString(vnode)) return getNodeType(node)===3;
let nodeName = vnode.nodeName,
type = typeof nodeName;
if (type==='string') {
return node.normalizedNodeName===nodeName || isNamedNode(node, nodeName);
}
if (type==='function') {
return node._componentConstructor===nodeName || isFunctionalComponent(vnode);
}
}
export function isNamedNode(node, nodeName) {
return toLowerCase(node.nodeName)===toLowerCase(nodeName);
}
/**
* Reconstruct Component-style `props` from a VNode.
* Ensures default/fallback values from `defaultProps`:
* Own-properties of `defaultProps` not present in `vnode.attributes` are added.
* @param {VNode} vnode
* @returns {Object} props
*/
export function getNodeProps(vnode) {
let props = clone(vnode.attributes),
c = vnode.children;
if (c) props.children = c;
let defaultProps = vnode.nodeName.defaultProps;
if (defaultProps) {
for (let i in defaultProps) {
if (hasOwnProperty.call(defaultProps, i) && !(i in props)) {
props[i] = defaultProps[i];
}
}
}
return props;
}
|
import { clone, toLowerCase, isFunction, isString, hasOwnProperty } from '../util';
import { isFunctionalComponent } from './functional-component';
import { getNodeType } from '../dom/index';
/** Check if two nodes are equivalent.
* @param {Element} node
* @param {VNode} vnode
* @private
*/
export function isSameNodeType(node, vnode) {
if (isFunctionalComponent(vnode)) return true;
let nodeName = vnode.nodeName;
if (isFunction(nodeName)) return node._componentConstructor===nodeName;
if (getNodeType(node)===3) return isString(vnode);
return toLowerCase(node.nodeName)===nodeName;
}
/**
* Reconstruct Component-style `props` from a VNode.
* Ensures default/fallback values from `defaultProps`:
* Own-properties of `defaultProps` not present in `vnode.attributes` are added.
* @param {VNode} vnode
* @returns {Object} props
*/
export function getNodeProps(vnode) {
let props = clone(vnode.attributes),
c = vnode.children;
if (c) props.children = c;
let defaultProps = vnode.nodeName.defaultProps;
if (defaultProps) {
for (let i in defaultProps) {
if (hasOwnProperty.call(defaultProps, i) && !(i in props)) {
props[i] = defaultProps[i];
}
}
}
return props;
}
|
[FAB-9222] Fix ledger test race condition
There seems to be contention for a base ledger
directory used throughout the tests. This change
adds a random directory to the paths for tests in
the base package.
Change-Id: I25a9f4312cf0f4b55596d69e46ab0b4b07f0912c
Signed-off-by: Gari Singh <10008a422f4be611b73174084ba2f7f909d5b402@gmail.com>
|
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kvledger
import (
"math/rand"
"os"
"path/filepath"
"strconv"
"testing"
"github.com/spf13/viper"
)
type testEnv struct {
t testing.TB
path string
}
func newTestEnv(t testing.TB) *testEnv {
path := filepath.Join(
os.TempDir(),
"fabric",
"ledgertests",
"kvledger",
strconv.Itoa(rand.Int()))
return createTestEnv(t, path)
}
func createTestEnv(t testing.TB, path string) *testEnv {
env := &testEnv{
t: t,
path: path}
env.cleanup()
viper.Set("peer.fileSystemPath", env.path)
return env
}
func (env *testEnv) cleanup() {
os.RemoveAll(env.path)
}
|
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kvledger
import (
"os"
"testing"
"github.com/hyperledger/fabric/core/config"
"github.com/spf13/viper"
)
type testEnv struct {
t testing.TB
}
func newTestEnv(t testing.TB) *testEnv {
return createTestEnv(t, "/tmp/fabric/ledgertests/kvledger")
}
func createTestEnv(t testing.TB, path string) *testEnv {
viper.Set("peer.fileSystemPath", path)
env := &testEnv{t}
env.cleanup()
return env
}
func (env *testEnv) cleanup() {
path := config.GetPath("peer.fileSystemPath")
os.RemoveAll(path)
}
|
Add a reference to jasmine typings
|
/// <reference path="typings/globals/jasmine/index.d.ts" />
'use strict';
describe('javaScript', function () {
it('Revealing prototype pattern', function () {
var Calculator = function(seed){
this.seed = seed;
};
Calculator.prototype = function (){
function add (item){
return this.seed + item;
};
return {
add: add
};
}();
var calculator = new Calculator(2);
var result = calculator.add(3);
expect(result).toBe(5);
});
});
|
'use strict';
describe('javaScript', function () {
it('Revealing prototype pattern', function () {
var Calculator = function(seed){
this.seed = seed;
};
Calculator.prototype = function (){
function add (item){
return this.seed + item;
};
return {
add: add
};
}();
var calculator = new Calculator(2);
var result = calculator.add(3);
expect(result).toBe(5);
});
});
|
Fix eclipse build: “UnicodeDecodeError: 'ascii' codec can't decode byte”
Closes https://github.com/espressif/esp-idf/pull/6505
|
#!/usr/bin/env python
#
# Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths
# to Windows paths, for Eclipse
from __future__ import division, print_function
import os.path
import re
import subprocess
import sys
UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+')
paths = {}
def check_path(path):
try:
return paths[path]
except KeyError:
pass
paths[path] = path # cache as failed, replace with success if it works
try:
winpath = subprocess.check_output(['cygpath', '-w', path]).decode('utf-8').strip()
except subprocess.CalledProcessError:
return path # something went wrong running cygpath, assume this is not a path!
if not os.path.exists(winpath):
return path # not actually a valid path
winpath = winpath.replace('\\', '/') # make consistent with forward-slashes used elsewhere
paths[path] = winpath
return winpath
def main():
print("Running make in '%s'" % check_path(os.getcwd()))
make = subprocess.Popen(['make'] + sys.argv[1:] + ['BATCH_BUILD=1'], stdout=subprocess.PIPE)
for line in iter(make.stdout.readline, ''):
line = re.sub(UNIX_PATH_RE, lambda m: check_path(m.group(0)), line)
print(line.rstrip())
sys.exit(make.wait())
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
#
# Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths
# to Windows paths, for Eclipse
from __future__ import division, print_function
import os.path
import re
import subprocess
import sys
UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+')
paths = {}
def check_path(path):
try:
return paths[path]
except KeyError:
pass
paths[path] = path # cache as failed, replace with success if it works
try:
winpath = subprocess.check_output(['cygpath', '-w', path]).decode().strip()
except subprocess.CalledProcessError:
return path # something went wrong running cygpath, assume this is not a path!
if not os.path.exists(winpath):
return path # not actually a valid path
winpath = winpath.replace('\\', '/') # make consistent with forward-slashes used elsewhere
paths[path] = winpath
return winpath
def main():
print("Running make in '%s'" % check_path(os.getcwd()))
make = subprocess.Popen(['make'] + sys.argv[1:] + ['BATCH_BUILD=1'], stdout=subprocess.PIPE)
for line in iter(make.stdout.readline, ''):
line = re.sub(UNIX_PATH_RE, lambda m: check_path(m.group(0)), line)
print(line.rstrip())
sys.exit(make.wait())
if __name__ == '__main__':
main()
|
Use the new API to register a build plugin
|
Package.describe({
summary: "Jade template language",
version: "0.2.9",
name: "mquandalle:jade",
git: "https://github.com/mquandalle/meteor-jade.git"
});
Package.registerBuildPlugin({
name: "compileJade",
use: [
"underscore",
"htmljs",
"html-tools",
"spacebars-compiler",
],
sources: [
"plugin/lexer.js",
"plugin/parser.js",
"plugin/compiler.js",
"plugin/handler.js",
],
npmDependencies: {
"jade": "https://github.com/mquandalle/jade/tarball/f3f956fa1031e05f85be7bc7b67f12e9ec80ba37"
}
});
Package.onTest(function (api) {
api.versionsFrom("METEOR@0.9.0");
api.use("tinytest");
api.use(["mquandalle:jade", "ui", "spacebars", "templating"]);
api.addFiles(["tests/match.jade", "tests/match.html", "tests/runtime.jade"]);
api.addFiles(["tests/match.js", "tests/runtime.js"], "client");
});
|
Package.describe({
summary: "Jade template language",
version: "0.2.9",
name: "mquandalle:jade",
git: "https://github.com/mquandalle/meteor-jade.git"
});
Package._transitional_registerBuildPlugin({
name: "compileJade",
use: [
"underscore",
"htmljs",
"html-tools",
"spacebars-compiler",
],
sources: [
"plugin/lexer.js",
"plugin/parser.js",
"plugin/compiler.js",
"plugin/handler.js",
],
npmDependencies: {
"jade": "https://github.com/mquandalle/jade/tarball/f3f956fa1031e05f85be7bc7b67f12e9ec80ba37"
}
});
Package.onTest(function (api) {
api.versionsFrom("METEOR@0.9.0");
api.use("tinytest");
api.use(["mquandalle:jade", "ui", "spacebars", "templating"]);
api.addFiles(["tests/match.jade", "tests/match.html", "tests/runtime.jade"]);
api.addFiles(["tests/match.js", "tests/runtime.js"], "client");
});
|
Fix type cache getting result on func calls
|
import { GraphQLObjectType, GraphQLID } from 'graphql';
import buildAttributes from './buildAttributes';
import buildRelationships from './buildRelationships';
import titleizeType from './titleizeType';
const getDefaultDescription = (name) => `The ${titleizeType(name)} Cohere model.`;
const typeCache = {};
export default (schema) => {
const graphQLObjectTypes = schema.types.reduce((prev, type) => {
const { meta, name } = type;
if (!meta) {
throw new Error(
'Micrograph requires every defined type to have a valid meta key. The ' +
`${name} type did not have a meta key.`
);
}
if (typeCache.hasOwnProperty(name)) return prev;
typeCache[name] = true;
return {
...prev,
[name]: new GraphQLObjectType({
description: meta.description || getDefaultDescription(name),
name: `${titleizeType(name)}`,
fields: () => ({
id: { type: GraphQLID },
...buildAttributes(type),
...buildRelationships(type, graphQLObjectTypes),
}),
}),
};
}, {});
return graphQLObjectTypes;
};
|
import { GraphQLObjectType, GraphQLID } from 'graphql';
import buildAttributes from './buildAttributes';
import buildRelationships from './buildRelationships';
import titleizeType from './titleizeType';
const getDefaultDescription = (name) => `The ${titleizeType(name)} Cohere model.`;
export default (schema) => {
const typeCache = {};
const graphQLObjectTypes = schema.types.reduce((prev, type) => {
const { meta, name } = type;
if (!meta) {
throw new Error(
'Micrograph requires every defined type to have a valid meta key. The ' +
`${name} type did not have a meta key.`
);
}
if (typeCache.hasOwnProperty(name)) return prev;
typeCache[name] = true;
return {
...prev,
[name]: new GraphQLObjectType({
description: meta.description || getDefaultDescription(name),
name: `${titleizeType(name)}`,
fields: () => ({
id: { type: GraphQLID },
...buildAttributes(type),
...buildRelationships(type, graphQLObjectTypes),
}),
}),
};
}, {});
return graphQLObjectTypes;
};
|
Make plugin work on case-sensitive systems
JSON5 package is published as `json5` not `JSON5` to npm.
Requiring it as `JSON5` make case-sensitive systems fail
|
var path = require('path');
var gutil = require('gulp-util');
var map = require('map-stream');
var JSON5 = require('json5');
var PluginError = gutil.PluginError;
const PLUGIN_NAME = 'gulp-json5';
module.exports = function(options) {
options = typeof options !== 'object' ? {} : options;
options.beautify = options.hasOwnProperty('beautify') ? !!options.beautify : true;
function parseJSON5(file, callback) {
var obj = {};
if (!file.isNull()) {
try {
obj = JSON5.parse(file.contents + '');
} catch (err) {
throw new PluginError(PLUGIN_NAME, "JSON5 parser error", err);
}
}
file.contents = new Buffer(JSON5.stringify(obj, null, options['beautify'] ? 4 : null));
file.path = path.join(file.base, path.basename(file.path, path.extname(file.path)) + '.json');
callback(null, file);
}
return map(parseJSON5);
}
|
var path = require('path');
var gutil = require('gulp-util');
var map = require('map-stream');
var JSON5 = require('JSON5');
var PluginError = gutil.PluginError;
const PLUGIN_NAME = 'gulp-json5';
module.exports = function(options) {
options = typeof options !== 'object' ? {} : options;
options.beautify = options.hasOwnProperty('beautify') ? !!options.beautify : true;
function parseJSON5(file, callback) {
var obj = {};
if (!file.isNull()) {
try {
obj = JSON5.parse(file.contents + '');
} catch (err) {
throw new PluginError(PLUGIN_NAME, "JSON5 parser error", err);
}
}
file.contents = new Buffer(JSON5.stringify(obj, null, options['beautify'] ? 4 : null));
file.path = path.join(file.base, path.basename(file.path, path.extname(file.path)) + '.json');
callback(null, file);
}
return map(parseJSON5);
}
|
Update manipulator include for setup
|
document.write('<script type="text/javascript" src="/janitor/admin/js/manipulator/v0_9_3-janitor/merged/seg_desktop.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/manipulator/v0_9_3-janitor/src/beta-u-notifier.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/manipulator/v0_9_3-janitor/src/beta-u-form-onebuttonform.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/lib/desktop/m-page.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/lib/u-basics.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/setup/desktop/m-progress.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/setup/desktop/m-upgrade.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/setup/desktop/m-pull.js"></script>');
|
document.write('<script type="text/javascript" src="/janitor/admin/js/manipulator/v0_9_3-janitor/merged/seg_desktop.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/manipulator/v0_9_3-janitor/src/beta-u-notifier.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/manipulator/v0_9_3-janitor/src/beta-u-form-onebuttonform.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/lib/desktop/i-page.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/lib/u-basics.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/setup/desktop/i-progress.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/setup/desktop/i-upgrade.js"></script>');
document.write('<script type="text/javascript" src="/janitor/admin/js/setup/desktop/i-pull.js"></script>');
|
Fix delete client: authorizations should be removed.
Signed-off-by: François de Metz <4073ce8ed0c8af431a3bf625d935cc2c9542ae9c@af83.com>
Signed-off-by: Virtuo <ff019a5748a52b5641624af88a54a2f0e46a9fb5@ruyssen.fr>
|
/* Where is defined the DB connection.
*
* We got the following collections (cf. schema.js):
* - User
* - Client
* - Grant
*
*/
require.paths.unshift(__dirname + "/../vendors/rest-mongo/src")
var events = require('events')
, rest_mongo = require("rest-mongo/core")
, mongo_backend = require("rest-mongo/mongo_backend")
, config = require('./lib/config_loader').get_config()
, schema = require('./schema').schema
, server_schema = require('./server_schema').schema
;
var backend = mongo_backend.get_backend(config.db);
exports.RFactory = rest_mongo.getRFactory(schema, backend, {
additional_schema: server_schema
});
// The RFactory to serve public data:
exports.RFactoryPublic = rest_mongo.getRFactory(schema, backend);
// Ensure indexes are created:
backend.db.createIndex('User', 'email', true, function(){}); // email is unique
// To ensure DB concistency:
var emitter = exports.emitter = new events.EventEmitter();
// When removing a client, remove its authorizations
emitter.on('DELETE:Client', function(ids) {
var R = exports.RFactory();
R.Authorization.remove({query: {
client: {'$in': ids.map(function(id){return {id: id}})}
}});
});
|
/* Where is defined the DB connection.
*
* We got the following collections (cf. schema.js):
* - User
* - Client
* - Grant
*
*/
require.paths.unshift(__dirname + "/../vendors/rest-mongo/src")
var events = require('events')
, rest_mongo = require("rest-mongo/core")
, mongo_backend = require("rest-mongo/mongo_backend")
, config = require('./lib/config_loader').get_config()
, schema = require('./schema').schema
, server_schema = require('./server_schema').schema
;
var backend = mongo_backend.get_backend(config.db);
exports.RFactory = rest_mongo.getRFactory(schema, backend, {
additional_schema: server_schema
});
// The RFactory to serve public data:
exports.RFactoryPublic = rest_mongo.getRFactory(schema, backend);
// Ensure indexes are created:
backend.db.createIndex('User', 'email', true, function(){}); // email is unique
// To ensure DB concistency:
var emitter = exports.emitter = new events.EventEmitter();
// When removing a client, remove its authorizations
emitter.on('DELETE:Client', function(ids) {
var R = RFactory();
R.Authorization.remove({query: {
client: {'$in': ids.map(function(id){return {id: id}})}
}});
});
|
Adjust day size to 100k. Change status flag placement.
|
import capture
from picamera import PiCamera
import time
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (854, 480)
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.image_size(latest[1])
capture.copy_latest(latest[1])
day = 100000 # image size when light is good
if size > day:
wait = 60
else:
wait = 600
status = capture.shutdown(camera)
print('Next capture begins in {} seconds.'.format(wait))
time.sleep(wait)
# status = capture.shutdown(camera)
image_cap_loop(camera, status)
def main():
camera = PiCamera()
image_cap_loop(camera)
print("Images captured")
if __name__ == '__main__':
main()
|
import capture
from picamera import PiCamera
import time
def image_cap_loop(camera):
"""Set image parameters, capture image, set wait time, repeat"""
images = 18
status = None
resolution = (854, 480)
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.image_size(latest[1])
capture.copy_latest(latest[1])
day = 1000 # image size when light is good
if size > day:
wait = 60
else:
wait = 600
status = capture.shutdown(camera)
print('Next capture begins in {} seconds.'.format(wait))
time.sleep(wait)
# status = capture.shutdown(camera)
image_cap_loop(camera)
def main():
camera = PiCamera()
image_cap_loop(camera)
print("Images captured")
if __name__ == '__main__':
main()
|
Fix find_neighbours_2D to ignore out of bounds points
... rather than 'trim' the coords, which made no sense.
|
from __future__ import division
import itertools
def get_offsets(span):
"""
Get matrix offsets for a square of distance `span`.
"""
if span < 0:
raise ValueError('Cannot return neighbours for negative distance')
all_offsets = set(itertools.product([x for x in range(-span, span + 1)], repeat=2))
if span >= 1:
inner_offsets = set(itertools.product([x for x in range(-(span - 1), span)], repeat=2))
else:
inner_offsets = set()
return all_offsets - inner_offsets
def find_neighbours_2D(array, start, span):
"""
Return neighbours in a 2D array, given a start point and range.
Checks array bounds so we don't get index errors.
"""
x, y = start # Start coords
rows = len(array) # How many rows
cols = len(array[0]) # Assume square matrix
offsets = get_offsets(span)
neighbours = set()
for dx, dy in offsets:
i = x + dx
j = y + dy
if i < 0 or i >= rows or j < 0 or j >= cols:
continue # Don't add coords outside of array bounds
neighbours.add((i, j))
return neighbours
def new(size, value=None):
""" Initialize a new square matrix. """
return [[value] * size for _ in range(size)]
|
from __future__ import division
import itertools
def get_offsets(span):
"""
Get matrix offsets for a square of distance `span`.
"""
if span < 0:
raise ValueError('Cannot return neighbours for negative distance')
all_offsets = set(itertools.product([x for x in range(-span, span + 1)], repeat=2))
if span >= 1:
inner_offsets = set(itertools.product([x for x in range(-(span - 1), span)], repeat=2))
else:
inner_offsets = set()
return all_offsets - inner_offsets
def find_neighbours_2D(array, start, span):
"""
Return neighbours in a 2D array, given a start point and range.
"""
x, y = start # Start coords
rows = len(array) # How many rows
cols = len(array[0]) # Assume square matrix
offsets = get_offsets(span)
print(offsets)
neighbours = set()
for dx, dy in offsets:
i = max(0, min(x + dx, rows))
j = max(0, min(y + dy, cols))
neighbours.add((i, j))
return neighbours
def new(size, value=None):
""" Initialize a new square matrix. """
return [[value] * size for _ in range(size)]
|
Use newer interface for filtering
The image provided by `plone.app.contenttypes` does reintroduce the global
IImage identifier lost during the transition to dexterity based types
|
# -*- coding: utf-8 -*-
"""Module providing views for asset storage folder"""
from Products.Five.browser import BrowserView
from plone import api
from plone.app.contenttypes.interfaces import IImage
class AssetRepositoryView(BrowserView):
""" Folderish content page default view """
def contained_items(self, uid):
stack = api.content.get(UID=uid)
return stack.restrictedTraverse('@@folderListing')()
def item_index(self, uid):
return len(self.contained_items(uid))
def preview_image(self, uid):
images = self.contained_items(uid)
preview = None
if len(images):
first_item = images[0].getObject()
if IImage.providedBy(first_item):
preview = first_item
return preview
|
# -*- coding: utf-8 -*-
"""Module providing views for asset storage folder"""
from Products.Five.browser import BrowserView
from plone import api
from plone.app.blob.interfaces import IATBlobImage
class AssetRepositoryView(BrowserView):
""" Folderish content page default view """
def contained_items(self, uid):
stack = api.content.get(UID=uid)
return stack.restrictedTraverse('@@folderListing')()
def item_index(self, uid):
return len(self.contained_items(uid))
def preview_image(self, uid):
images = self.contained_items(uid)
preview = None
if len(images):
first_item = images[0].getObject()
if IATBlobImage.providedBy(first_item):
preview = first_item
return preview
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.