text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Check for view function in objects. | var solarflare = function (rays) {
var $element = document.createElement('div');
if (Array.isArray(rays)) {
rays.forEach(function (e, i) {
if (i === 0 && typeof e === 'string') {
if (e.length > 0) {
$element = document.createElement(e);
}
return;
}
if (typeof e === 'string') {
... | var solarflare = function (rays) {
var $element = document.createElement('div');
if (Array.isArray(rays)) {
rays.forEach(function (e, i) {
if (i === 0 && typeof e === 'string') {
if (e.length > 0) {
$element = document.createElement(e);
}
return;
}
if (typeof e === 'string') {
... |
Check if token is an error | const Boom = require('boom');
const bookshelf = require('../lib/bookshelf');
exports.register = function (server, pluginOptions, next) {
server.auth.scheme('email_token', (server, schemeOptions) => {
return {
async authenticate(request, reply) {
try {
var token = await schemeOptions.findT... | const Boom = require('boom');
const bookshelf = require('../lib/bookshelf');
exports.register = function (server, pluginOptions, next) {
server.auth.scheme('email_token', (server, schemeOptions) => {
return {
async authenticate(request, reply) {
try {
var token = await schemeOptions.findT... |
Write set values to log file | var express = require('express'),
Memcached = require('memcached'),
fs = require('fs');
// Constants
var port = 3000;
var env = process.env.NODE_ENV || 'production';
var mc = new Memcached(process.env.MC_PORT.replace('tcp://', ''));
// App
var app = express();
app.use(express.urlencoded());
app.get('/', func... | var express = require('express'),
Memcached = require('memcached');
// Constants
var port = 3000;
var env = process.env.NODE_ENV || 'production';
var mc = new Memcached(process.env.MC_PORT.replace('tcp://', ''));
// App
var app = express();
app.use(express.urlencoded());
app.get('/', function (req, res) {
res.... |
Add eval command for JS scripting | var find_common_pkg = function(pkglist) {
var common = [pkglist[0].split(/\./)];
pkglist.forEach(function(pkg) {
var spl = pkg.split(/\./);
var fnd = false;
common.forEach(function(com, ind) {
if (spl[0] === com[0]) {
common[ind] = spl.filter(function(n) {
... | var find_common_pkg = function(pkglist) {
var common = [pkglist[0].split(/\./)];
pkglist.forEach(function(pkg) {
var spl = pkg.split(/\./);
var fnd = false;
common.forEach(function(com, ind) {
if (spl[0] === com[0]) {
common[ind] = spl.filter(function(n) {
... |
Add benchmark for geocode function. | package main
import (
"testing"
"github.com/kellydunn/golang-geo"
)
func TestGeocode(t *testing.T) {
query := "1600 amphitheatre parkway"
expectedAddress := "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"
expectedLatitude, expectedLongitude := 37.4219998, -122.0839596
result, err := geocode(query, n... | package main
import (
"testing"
"github.com/kellydunn/golang-geo"
)
func TestGeocode(t *testing.T) {
query := "1600 amphitheatre parkway"
expectedAddress := "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"
expectedLatitude, expectedLongitude := 37.4219998, -122.0839596
result, err := geocode(query, n... |
Remove newline at beginning of file | /**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-co... |
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-c... |
Add jQuery load to master template | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>@yield('title')</title>
{{ HTML::style('css/cnq.css') }}
<script type="text/javascript" src="//use.typekit.net/fky8rov.js"></script>
<script type="text/javascript">try{Ty... | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>@yield('title')</title>
{{ HTML::style('css/cnq.css') }}
<script type="text/javascript" src="//use.typekit.net/fky8rov.js"></script>
<script type="text/javascript">try{Ty... |
Add note to gcp session utils method | """Session management utilities for Google Cloud Platform (GCP)."""
from typing import Optional, Any
try:
import google.auth
from google.auth.transport import requests as google_requests
except ImportError:
raise ImportError(
'The `dicomweb-client` package needs to be installed with the '
'... | """Session management utilities for Google Cloud Platform (GCP)."""
from typing import Optional, Any
try:
import google.auth
from google.auth.transport import requests as google_requests
except ImportError:
raise ImportError(
'The `dicomweb-client` package needs to be installed with the '
'... |
Remove create button in collection header when endpoint is database. | <h3 class="panel-title">
<span class="text-left"><?php echo ucwords(str_replace('_', ' ', ($this->response->meta->collection))); ?></span>
<?php
if ($this->m_users->get_user_permission('', $this->response->meta->collection, 'c') and $this->response->meta->collection != 'confi... | <h3 class="panel-title">
<span class="text-left"><?php echo ucwords(str_replace('_', ' ', ($this->response->meta->collection))); ?></span>
<?php
if ($this->m_users->get_user_permission('', $this->response->meta->collection, 'c') and $this->response->meta->collection != 'confi... |
Comment for the competition settings did not make sense. | # competition_settings.py
# This file contains settings for the current competition.
# This include start and end dates along with round information.
import datetime # Only used to dynamically set the round dates.
# The start and end date of the competition.
COMPETITION_START = (datetime.date.today() - datetime.timede... | # competition_settings.py
# This file contains settings for the current competition.
# This include start and end dates along with round information.
import datetime # Only used to dynamically set the round dates.
# The start and end date of the competition.
COMPETITION_START = (datetime.date.today() - datetime.timede... |
Test france compatibility with the new API | # -*- coding: utf-8 -*-
import subprocess
import time
from unittest import TestCase
from nose.tools import assert_equal
class TestOldApi(TestCase):
def setUp(self):
self.process = subprocess.Popen("openfisca-serve")
def tearDown(self):
self.process.terminate()
def test_response(self):
... | # -*- coding: utf-8 -*-
import subprocess
import time
from unittest import TestCase
from nose.tools import assert_equal
class TestOldApi(TestCase):
def setUp(self):
self.process = subprocess.Popen("openfisca-serve")
def tearDown(self):
self.process.terminate()
def test_response(self):
... |
Fix case of filename keyboardShortcuts.json | 'use strict';
var App = require('../app');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var _ = require('underscore');
var keyboardShortcuts = require('./keyboardShortcuts.json');
var marked = require('marked');
var controller = {
showHelp: function () {
var HelpView = re... | 'use strict';
var App = require('../app');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var _ = require('underscore');
var keyboardShortcuts = require('./keyboardshortcuts.json');
var marked = require('marked');
var controller = {
showHelp: function () {
var HelpView = re... |
Set correct type of cache map | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the ... | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the ... |
Add renaming of nextTab -> switchTab | /* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTab... | /* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTab... |
Fix float type flag definition | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... |
Add test to check excplicitly if the attribute is set | #!/usr/bin/env
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "licens... | #!/usr/bin/env
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "licens... |
Add test case without output file for expand.go
Signed-off-by: Sergey <95b6115869faa4e182a269b2ddf6435382b0fe53@gmail.com> | package commands
import (
"os"
"path/filepath"
"testing"
flags "github.com/jessevdk/go-flags"
"github.com/stretchr/testify/assert"
)
// Commands requires at least one arg
func TestCmd_Expand(t *testing.T) {
v := &ExpandSpec{}
testRequireParam(t, v)
}
func TestCmd_Expand_NoError(t *testing.T) {
specDoc := fi... | package commands
import (
"os"
"path/filepath"
"testing"
flags "github.com/jessevdk/go-flags"
)
// Commands requires at least one arg
func TestCmd_Expand(t *testing.T) {
v := &ExpandSpec{}
testRequireParam(t, v)
}
func TestCmd_Expand_NoError(t *testing.T) {
specDoc := filepath.Join(fixtureBase, "bugs", "1536... |
Fix cookie options parser for php 5.4 | <?php
namespace SimplyTestable\WebClientBundle\Services\TestOptions\Adapter\Request\FeatureParser;
class CookieOptionsParser extends OptionsParser {
private $requiredNonBlankFields = [
'name',
'value'
];
public function getOptions() {
$options = parent::getOptions();
if (... | <?php
namespace SimplyTestable\WebClientBundle\Services\TestOptions\Adapter\Request\FeatureParser;
class CookieOptionsParser extends OptionsParser {
private $requiredNonBlankFields = [
'name',
'value'
];
public function getOptions() {
$options = parent::getOptions();
if (... |
Remove specs from suite (separate) | <?php
require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');
class MustacheTestSuite extends TestSuite {
function MustacheTestSuite() {
$this->TestSuite('All Mustache tests');
$this->addFile(dirname(__FILE__)."/testStringScanner.php");
$t... | <?php
require_once(dirname(__FILE__).'/../vendor/simpletest/autorun.php');
require_once(dirname(__FILE__).'/../Mustache.php');
class MustacheTestSuite extends TestSuite {
function MustacheTestSuite() {
$this->TestSuite('All Mustache tests');
$this->addFile(dirname(__FILE__)."/testStringScanner.php");
$t... |
Switch node sortkey on Workload page.
The node sortkey was displayname instead of node.sortName which
caused sorting to behave strangely.
I switched the sortkeys and added more to the sortkey array to
help provide a more stable sort.
rancher/rancher#21218 | import Component from '@ember/component';
import ManageLabels from 'shared/mixins/manage-labels';
import layout from './template';
export default Component.extend(ManageLabels, {
layout,
model: null,
expandOnInit: true,
sortBy: 'displayState',
showKind: true,
descending: true,
ini... | import Component from '@ember/component';
import ManageLabels from 'shared/mixins/manage-labels';
import layout from './template';
export default Component.extend(ManageLabels, {
layout,
model: null,
expandOnInit: true,
sortBy: 'displayState',
showKind: true,
descending: true,
ini... |
Remove num_members as it's not exposed anymore | package slack
// Conversation is the foundation for IM and BaseGroupConversation
type conversation struct {
ID string `json:"id"`
Created JSONTime `json:"created"`
IsOpen bool `json:"is_open"`
LastRead string `json:"last_read,omitempty"`
Latest ... | package slack
// Conversation is the foundation for IM and BaseGroupConversation
type conversation struct {
ID string `json:"id"`
Created JSONTime `json:"created"`
IsOpen bool `json:"is_open"`
LastRead string `json:"last_read,omitempty"`
Latest ... |
Use a fast password hasher for tests.
Speed is obviously more important than security in tests. | from __future__ import unicode_literals
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"sesame.backends.ModelBackend",
]
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}}
INSTALLED_AP... | from __future__ import unicode_literals
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"sesame.backends.ModelBackend",
]
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}}
INSTALLED_AP... |
Fix error in callback on login post | /**
* Module dependencies.
*/
var passport = require('passport'),
login = require('connect-ensure-login'),
router = require('express').Router(),
oauth2 = require('./oauth2'),
user = require('./user');
router.get('/dialog/authorize', oauth2.authorization);
//router.post('/dialog/authorize/deci... | /**
* Module dependencies.
*/
var passport = require('passport'),
login = require('connect-ensure-login'),
router = require('express').Router(),
oauth2 = require('./oauth2'),
user = require('./user');
router.get('/dialog/authorize', oauth2.authorization);
//router.post('/dialog/authorize/deci... |
Add test case to check inOrder when tree is empty. Throws NoSuchElement exception | package binary_search_tree;
import java.util.NoSuchElementException;
import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree
/*
Class to test class Bst. (Binary Search Tree)
*/
class TestBst{
// Tests Insertion
public static void testInsertion(){
// Create ... | package binary_search_tree;
import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree
/*
Class to test class Bst. (Binary Search Tree)
*/
class TestBst{
// Tests Insertion
public static void testInsertion(){
// Create a bst object
Bst bst = new Bst();
//... |
Tweak documentation for order in order book reconstruction | package org.jvirtanen.parity.top;
/**
* An order in an order book.
*/
public class Order {
private Level parent;
private long remainingQuantity;
Order(Level parent, long size) {
this.parent = parent;
this.remainingQuantity = size;
}
OrderBook getOrderBook() {
return p... | package org.jvirtanen.parity.top;
/**
* <code>Order</code> represents an order in an order book.
*/
public class Order {
private Level parent;
private long remainingQuantity;
Order(Level parent, long size) {
this.parent = parent;
this.remainingQuantity = size;
}
OrderBook get... |
Load JS data now that there is a first data set available | var fs = require('fs'),
path = require('path'),
extend = require('extend');
function load() {
// Recursively load one or more directories passed as arguments.
var dir, result = {};
function processFilename(fn) {
var fp = path.join(dir, fn),
// If the given filename is a direct... | var fs = require('fs'),
path = require('path'),
extend = require('extend');
function load() {
// Recursively load one or more directories passed as arguments.
var dir, result = {};
function processFilename(fn) {
var fp = path.join(dir, fn),
// If the given filename is a direct... |
fix: Fix global name and add preact to the list of externals.
#1150 | const browsers = require('./test/browsers');
module.exports = {
type: 'web-module',
npm: {
cjs: false,
esModules: true,
umd: {
externals: { preact: 'preact' },
global: 'skate'
}
},
karma: process.argv.indexOf('--ci') === -1 ? {
browsers: [require('karma-chrome-launcher')]
} : ... | const browsers = require('./test/browsers');
module.exports = {
type: 'web-module',
npm: {
cjs: false,
esModules: true,
umd: true
},
karma: process.argv.indexOf('--ci') === -1 ? {
browsers: [require('karma-chrome-launcher')]
} : {
browsers: Object.keys(browsers),
plugins: ['karma-sauc... |
Add a test case for very large sparse matrix | /*
* Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
*
* This file is part of la4j project (http://la4j.org)
*
* 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
*
* ... | /*
* Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
*
* This file is part of la4j project (http://la4j.org)
*
* 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
*
* ... |
Resolve packages relative to the package.json file instead of to the root
Fixes #47 | 'use strict';
const path = require('path');
const pkgUp = require('pkg-up');
const multimatch = require('multimatch');
const arrify = require('arrify');
const resolvePkg = require('resolve-pkg');
module.exports = (grunt, options = {}) => {
const pattern = arrify(options.pattern || ['grunt-*', '@*/grunt-*']);
const s... | 'use strict';
const path = require('path');
const pkgUp = require('pkg-up');
const multimatch = require('multimatch');
const arrify = require('arrify');
const resolvePkg = require('resolve-pkg');
module.exports = (grunt, options = {}) => {
const pattern = arrify(options.pattern || ['grunt-*', '@*/grunt-*']);
const s... |
Use new column for score. | import sqlite3
def main():
conn = sqlite3.connect("database")
cursor = conn.cursor()
# I claim this gives the current score. Another formulation is
# select trackid, score, max(scoreid) from scores group by trackid;
# cursor.execute("""select trackid, score from scores
# group b... | import sqlite3
def main():
conn = sqlite3.connect("database")
cursor = conn.cursor()
# I claim this gives the current score. Another formulation is
# select trackid, score, max(scoreid) from scores group by trackid;
# cursor.execute("""select trackid, score from scores
# group b... |
Include base version for msgpack, because 0.3 doesn't work
If I import neovim with less than version 0.4 of msgpack installed, I get this stack trace:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/chartdev/venvs/chartio/local/lib/python2.7/site-packages/neovim/__init_... | import platform
import sys
from setuptools import setup
install_requires = [
'msgpack-python>=0.4.0',
]
if sys.version_info < (3, 4):
# trollius is just a backport of 3.4 asyncio module
install_requires.append('trollius')
if not platform.python_implementation() == 'PyPy':
# pypy already includes an ... | import platform
import sys
from setuptools import setup
install_requires = [
'msgpack-python',
]
if sys.version_info < (3, 4):
# trollius is just a backport of 3.4 asyncio module
install_requires.append('trollius')
if not platform.python_implementation() == 'PyPy':
# pypy already includes an impleme... |
Change dividend for all benchmark tests to 1024 | package main
import (
"testing"
)
func BenchmarkDivisionMod(b *testing.B) {
d := NewDivisionMod(1024)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkDivisionPow2(b *testing.B) {
d := NewDivisionPow2(1024)
// run the dividable check... | package main
import (
"testing"
)
func BenchmarkDivisionMod(b *testing.B) {
d := NewDivisionMod(1000)
// run the dividable check function b.N times
for n := 0; n < b.N; n++ {
d.IsRestlessDividable(uint64(n))
}
}
func BenchmarkDivisionPow2(b *testing.B) {
d := NewDivisionPow2(1024)
// run the dividable check... |
/jserror: Refactor to handle errors better | 'use strict';
const log4js = require('log4js');
const clientLogger = log4js.getLogger('client');
const formidable = require('formidable');
const apiHandler = require('../../handler/APIHandler');
exports.expressCreateServer = (hookName, args, cb) => {
// The Etherpad client side sends information about how a disconn... | 'use strict';
const log4js = require('log4js');
const clientLogger = log4js.getLogger('client');
const formidable = require('formidable');
const apiHandler = require('../../handler/APIHandler');
exports.expressCreateServer = (hookName, args, cb) => {
// The Etherpad client side sends information about how a disconn... |
Add a specific test for the updatesfromdict hard coded foreignkey fields | from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
... | from django.test import TestCase
from django.db import models as djangomodels
from opal.models import UpdatesFromDictMixin
class UpdatesFromDictMixinTest(TestCase):
class TestDiagnosis(UpdatesFromDictMixin, djangomodels.Model):
condition = djangomodels.CharField(max_length=255, blank=True, null=True)
... |
Use database number from redis url if available. | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... |
Revert "Temporarily removed the first line from the survey-complete page"
This reverts commit 803aa203 | <?php if ($valid_token) { ?>
<?=heading('Hartelijk dank voor het invullen van deze vragenlijst.', 2); ?>
<p>
Hartelijk dank voor het invullen van de vragenlijst <em><?=$test_name; ?></em>.
Uw antwoorden zijn opgeslagen en worden met de grootste zorg behandeld.
</p>
<p>
Als u verder nog vragen heeft over de v... | <?php if ($valid_token) { ?>
<?=heading('Hartelijk dank voor het invullen van deze vragenlijst.', 2); ?>
<p>
<!-- Hartelijk dank voor het invullen van de vragenlijst <em>--><?//=$test_name; ?><!--</em>. -->
Uw antwoorden zijn opgeslagen en worden met de grootste zorg behandeld.
</p>
<p>
Als u verder nog vragen... |
Add back a newline to have two rows between class definitions. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Ninhursag'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
# Serve... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Ninhursag'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
# Serve... |
Optimize only main.js, skip all other files
The directory does not need to be optimized because only main.js is
loaded by the end user. This saves compilation time for JS/CSS. | ({
appDir: './app',
baseUrl: 'scripts',
mainConfigFile: './app/scripts/main.js',
dir: './build',
pragmasOnSave: {
excludeCoffeeScript: true,
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: 'uglify',
... | ({
appDir: './app',
baseUrl: 'scripts',
mainConfigFile: './app/scripts/main.js',
dir: './build',
pragmasOnSave: {
excludeCoffeeScript: true,
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: 'uglify',
... |
Fix build process on linux | var isWindows = /^win/.test(process.platform)
if(isWindows){
spawn = require('child_process').exec
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -o build -cw source")
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -cw test/index.cjsx")
spawn(__dirname + "/node_modules/.bin/watchify.cmd test/index.js -o test/b... | var isWindows = /^win/.test(process.platform)
if(isWindows){
spawn = require('child_process').exec
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -o build -cw source")
spawn(__dirname + "/node_modules/.bin/cjsx.cmd -cw test/index.cjsx")
spawn(__dirname + "/node_modules/.bin/watchify.cmd test/index.js -o test/b... |
Rename fqdn to fqname in DialogEditorHttpService
https://bugzilla.redhat.com/show_bug.cgi?id=1553846 | ManageIQ.angular.app.service('DialogEditorHttp', ['$http', 'API', function($http, API) {
this.loadDialog = function(id) {
return API.get('/api/service_dialogs/' + id + '?attributes=content,buttons,label');
};
this.saveDialog = function(id, action, data) {
return API.post('/api/service_dialogs' + id, {
... | ManageIQ.angular.app.service('DialogEditorHttp', ['$http', 'API', function($http, API) {
this.loadDialog = function(id) {
return API.get('/api/service_dialogs/' + id + '?attributes=content,buttons,label');
};
this.saveDialog = function(id, action, data) {
return API.post('/api/service_dialogs' + id, {
... |
Move get user out of loop
It's good practice to get not changing data before loop | <?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
public function __construct(array $config = array())
{
$data = array();
$components = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component')... | <?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
public function __construct(array $config = array())
{
$data = array();
$components = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component')... |
Minor: Update errors for other versions of Pyro
git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@775 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7 | #!/usr/bin/env python
import sys
import Pyro
import Tkinter, tkMessageBox
from VisionEgg.PyroApps.UberClientGUI import client_list, AppWindow
# You can add your own controllers and GUIs to client_list
try:
app_window = AppWindow(client_list=client_list)
except Pyro.errors.PyroError, x:
uber_server_error = 0
... | #!/usr/bin/env python
import sys
import Pyro
import Tkinter, tkMessageBox
from VisionEgg.PyroApps.UberClientGUI import client_list, AppWindow
# You can add your own controllers and GUIs to client_list
try:
app_window = AppWindow(client_list=client_list)
except Pyro.errors.ProtocolError, x:
if str(x) == 'conn... |
Split gulp build into parts | var gulp = require("gulp"),
jade = require("gulp-jade"),
minCSS = require("gulp-minify-css"),
minHTML = require("gulp-minify-html"),
react = require("gulp-react"),
uglify = require("gulp-uglify");
gulp.task("build:jade", function () {
gulp.src("src/public/index.jade")
.pipe(jade())
.pipe(minHTML())... | var gulp = require("gulp"),
jade = require("gulp-jade"),
minCSS = require("gulp-minify-css"),
minHTML = require("gulp-minify-html"),
react = require("gulp-react"),
uglify = require("gulp-uglify");
gulp.task("build", function () {
gulp.src("src/public/index.jade")
.pipe(jade())
.pipe(minHTML())
.p... |
Add missing authorization in some places
Missed the headers count check. | <?php
$authorization = '';
if ($route['authenticated']) {
$authorization .= ' -H "Authorization: Bearer {{token}}"';
if(count($route['headers']) > 0) {
$authorization .= ' \\';
}
}
?>
```bash
curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ... | <?php
$authorization = '';
if ($route['authenticated']) {
$authorization .= ' -H "Authorization: Bearer {{token}}"';
if(count($route['headers']) > 0) {
$authorization .= ' \\';
}
}
?>
```bash
curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ... |
Add Seven Hour mock data. | const CurrentData = {
display_location: {
full: 'Den'
},
temp_f: 70
};
const ForecastData = {
txt_forecast: {
forecastday:[{
title: 'Monday',
fcttext: 'Clear all day',
}]
},
simpleforecast: {
forecastday:[{
conditions: 'Clear',
high: {
fahrenheit: 70,
}... | const CurrentData = {
display_location: {
full: 'Den'
},
temp_f: 70
};
const ForecastData = {
txt_forecast: {
forecastday:[{
title: 'Monday',
fcttext: 'Clear all day',
}]
},
simpleforecast: {
forecastday:[{
conditions: 'Clear',
high: {
fahrenheit: 70,
}... |
Fix to validate schema function | from jsonschema import validate, ValidationError
from flask import current_app
import json
import os
def validate_schema(data, schema_name):
"""
Validate the provided data against the provided JSON schema.
:param data: JSON data to be validated
:param schema_name: Name of the schema
:return:... | from jsonschema import validate, ValidationError
from flask import current_app
import json
import os
def validate_schema(data, schema_name):
"""
Validate the provided data against the provided JSON schema.
:param data: JSON data to be validated
:param schema_name: Name of the schema
:return:... |
Disable SQLALCHEMY_TRACK_MODIFICATIONS to fix deprecation warning and meet recommendation | from flask import Flask
from flask_talisman import Talisman
from flask_seasurf import SeaSurf
from redditflair.redditflair import redditflair, limiter
from redissession import RedisSessionInterface
from database import db, User, Specials
import os.path
content_security_policy = {
'script-src': '\'unsafe-inline\'',
'... | from flask import Flask
from flask_talisman import Talisman
from flask_seasurf import SeaSurf
from redditflair.redditflair import redditflair, limiter
from redissession import RedisSessionInterface
from database import db, User, Specials
import os.path
content_security_policy = {
'script-src': '\'unsafe-inline\'',
'... |
Fix getting category's descendants before save | from django import forms
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from unidecode import unidecode
from ...product.models import Category
class CategoryForm(forms.ModelForm):
parent = TreeNodeChoiceField(queryset=Categ... | from django import forms
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from unidecode import unidecode
from ...product.models import Category
class CategoryForm(forms.ModelForm):
parent = TreeNodeChoiceField(queryset=Categ... |
Fix mixin error
Add an empty string alternative to avoid mixin error when a form field is left empty during submission | import Ember from 'ember';
export default Ember.Component.extend({
// Hide the form
addNewQuestion: false,
actions: {
// Show the form
showQuestionForm() {
this.set('addNewQuestion', true)
},
saveQuestion() {
// Get the user input and store them
... | import Ember from 'ember';
export default Ember.Component.extend({
// Hide the form
addNewQuestion: false,
actions: {
// Show the form
showQuestionForm() {
this.set('addNewQuestion', true)
},
saveQuestion() {
// Get the user input and store them
... |
Replace extra deps with sync packages | from setuptools import setup, find_packages
classifiers = [
'License :: OSI Approved :: BSD License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Environment :: Web Environment',
... | from setuptools import setup, find_packages
classifiers = [
'License :: OSI Approved :: BSD License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Environment :: Web Environment',
... |
[FIX] website_product_supplier: Add images key in manifest file | # -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería S.L. - Sergio Teruel
# (c) 2015 Antiun Ingeniería S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': "Website Product Supplier",
'category': 'Website',
'version': '8.0.1.0.0',
'depends': [
'website... | # -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería S.L. - Sergio Teruel
# (c) 2015 Antiun Ingeniería S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': "Website Product Supplier",
'category': 'Website',
'version': '8.0.1.0.0',
'depends': [
'website... |
Make DataFrame available to module user | #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import DataFrame, Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevi... | #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
latti... |
Use getDeclaredField to access Unsafe
getField() only gets public fields :( | package net.md_5.bungee.event;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class UnsafeUtils {
private UnsafeUtils() {}
private static final Unsafe UNSAFE;
static {
Unsafe unsafe;
try {
Class c = Class.forName("sun.misc.Unsafe");
Field f = c.get... | package net.md_5.bungee.event;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class UnsafeUtils {
private UnsafeUtils() {}
private static final Unsafe UNSAFE;
static {
Unsafe unsafe;
try {
Class c = Class.forName("sun.misc.Unsafe");
Field f = c.get... |
Modify camera angle from 105 to 115 degrees. | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Yulli
*/
public class Camera extends Subsystem {
// Put ... | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Yulli
*/
public class Camera extends Subsystem {
// Put ... |
Increase the leak test timeout for CI | /* jshint esversion: 6 */
var ssr = require("../lib/");
var helpers = require("./helpers");
var iterate = require("leakage").iterate;
var path = require("path");
var through = require("through2");
describe("Memory leaks", function(){
this.timeout(30000);
before(function(){
this.oldXHR = global.XMLHttpRequest;
g... | var ssr = require("../lib/");
var helpers = require("./helpers");
var assert = require("assert");
var iterate = require("leakage").iterate;
var path = require("path");
var through = require("through2");
describe("Memory leaks", function(){
this.timeout(10000);
before(function(){
this.oldXHR = global.XMLHttpReques... |
Add game over when trying to move in game over state
Signed-off-by: Joern Bernhardt <7b85a41a628204b76aba4326273a3ccc74bd009a@campudus.com> | var Board = require('./Board');
var tiles = document.querySelectorAll('.tile');
var board = new Board(tiles);
console.log(board);
board.nextRound();
board.nextRound();
document.onkeydown = onKeyDown;
function onKeyDown(e) {
var event = e || window.event;
event.preventDefault();
event.stopPropagation();
mov... | var Board = require('./Board');
var tiles = document.querySelectorAll('.tile');
var board = new Board(tiles);
console.log(board);
board.nextRound();
board.nextRound();
document.onkeydown = onKeyDown;
function onKeyDown(e) {
var event = e || window.event;
event.preventDefault();
event.stopPropagation();
mov... |
Reorder arg list, set default for static params | # -*- coding: utf-8 -*-
import copy
def init_abscissa(abscissae, abscissa_name, params = {}):
"""
List of dicts to initialize object w/ calc method
This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of ... | # -*- coding: utf-8 -*-
import copy
def init_abscissa(params, abscissae, abscissa_name):
"""
List of dicts to initialize object w/ calc method
This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of as th... |
Put both output and console | const config = require("./../config.json");
const MSS = require("./../functions/");
const Sandbox = require("sandbox");
module.exports = function(message) {
var s = new Sandbox;
if(message.author.id === config.MSS.sysadmin) {
let input = message.content.replace (/\n/g, " ").split(" ");
input[0] = input[0].subst... | const config = require("./../config.json");
const MSS = require("./../functions/");
const Sandbox = require("sandbox");
module.exports = function(message) {
var s = new Sandbox;
if(message.author.id === config.MSS.sysadmin) {
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substr... |
Implement new MPDChildProcess object into production code | var Q = require('q'),
spawn = require('child_process').spawn,
fs = require('fs'),
net = require('net'),
logger = require('winston'),
waitForSocket = require('./wait-for-socket'),
mpdChildProcess = require('./mpd-child-process'),
mpdConfig = require('./mpd-config');
exp... | var Q = require('q'),
spawn = require('child_process').spawn,
fs = require('fs'),
net = require('net'),
logger = require('winston'),
waitForSocket = require('./wait-for-socket.js'),
mpdConfig = require(__dirname+'/mpd-config.js');
exports.create = function(config) {
var mpdConf =... |
Update the "six" to force version 1.10.0 | """
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""
from setuptools import setup, find_packages # noqa
setup(
name='tensorpy',
version='1.0.1',
url='http://tensorpy.com',
author='Michael Mi... | """
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""
from setuptools import setup, find_packages # noqa
setup(
name='tensorpy',
version='1.0.1',
url='http://tensorpy.com',
author='Michael Mi... |
Add Let's Encrypt env var | from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(ma... | from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(ma... |
Clean up name field assignments | import generateActions from './actions';
import generateApi from './api';
import generateNames from './names';
import generateStore from './store';
/**
* Base Flux resource class
*
* This isn't very useful by itself. Use the bindings for an actual Flux
* framework.
*/
export default class FluxResource {
constru... | import generateActions from './actions';
import generateApi from './api';
import generateNames from './names';
import generateStore from './store';
/**
* Base Flux resource class
*
* This isn't very useful by itself. Use the bindings for an actual Flux
* framework.
*/
export default class FluxResource {
constru... |
Update test to match changes in index | module.exports = {
'Filtering on search page': function (browser) {
browser
.url('http://localhost:8000/search?q=rocket')
.waitForElementVisible('body', 1000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.... | module.exports = {
'Filtering on search page': function (browser) {
browser
.url('http://localhost:8000/search?q=rocket')
.waitForElementVisible('body', 1000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.... |
Add close and destroy; force fixed chunk length | module.exports = Storage
function Storage (chunkLength) {
if (!(this instanceof Storage)) return new Storage()
this.chunks = []
this.chunkLength = Number(chunkLength)
this.closed = false
if (!this.chunkLength) throw new Error('First argument must be a chunk length')
}
Storage.prototype.put = function (index... | module.exports = Storage
function Storage () {
if (!(this instanceof Storage)) return new Storage()
this.chunks = []
}
Storage.prototype.put = function (index, buf, cb) {
this.chunks[index] = buf
if (cb) process.nextTick(cb)
}
function nextTick (cb, err, val) {
process.nextTick(function () {
cb(err, va... |
Add method to say Achmed like jews. | package com.github.aureliano.achmed.helper;
import java.util.Properties;
public final class ApplicationHelper {
private ApplicationHelper() {
throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
}
public static String help() {
String help = FileHelper.readResource("meta/help... | package com.github.aureliano.achmed.helper;
import java.util.Properties;
public final class ApplicationHelper {
private ApplicationHelper() {
throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
}
public static String help() {
String help = FileHelper.readResource("meta/help... |
Add comment as to how important the call to render() is | import React, { PropTypes } from 'react';
import { Link, IndexLink } from 'react-router';
import { Login } from 'auth';
import { ErrorHandler } from 'error';
import { rendered } from 'lib/fetchData';
export default class App extends React.Component {
static propTypes = {
children: PropTypes.object,
};
comp... | import React, { PropTypes } from 'react';
import { Link, IndexLink } from 'react-router';
import { Login } from 'auth';
import { ErrorHandler } from 'error';
import { rendered } from 'lib/fetchData';
export default class App extends React.Component {
static propTypes = {
children: PropTypes.object,
};
comp... |
Fix gofmt formating for a file | package tools
import (
"fmt"
"log"
"strings"
)
// UploadFile used to upload file by S3 pre-signed URL
func UploadFile(path, url string) int {
log.Println("Uploading file from path:", path)
file, info := prepareFile(path)
resp := sendRequest(url, &file, info)
return getStatusOfUpload(resp)
}
// GetFileName ret... | package tools
import (
"log"
"strings"
"fmt"
)
// UploadFile used to upload file by S3 pre-signed URL
func UploadFile(path, url string) int {
log.Println("Uploading file from path:", path)
file, info := prepareFile(path)
resp := sendRequest(url, &file, info)
return getStatusOfUpload(resp)
}
// GetFileName ret... |
Fix critical Image delete observer!!!
Update ImageObserver.php | <?php
namespace Despark\Cms\Admin\Observers;
use Illuminate\Database\Eloquent\Model;
use Despark\Cms\Contracts\ImageContract;
/**
* Class ImageObserver.
*/
class ImageObserver
{
/**
* @param Model $model
*/
public function saved(Model $model)
{
$model->saveImages();
}
/**
... | <?php
namespace Despark\Cms\Admin\Observers;
use Illuminate\Database\Eloquent\Model;
use Despark\Cms\Contracts\ImageContract;
/**
* Class ImageObserver.
*/
class ImageObserver
{
/**
* @param Model $model
*/
public function saved(Model $model)
{
$model->saveImages();
}
/**
... |
[test] Fix typo in whitelist and blacklist | // @flow
const { JSDOM } = require('jsdom');
const Node = require('jsdom/lib/jsdom/living/node-document-position');
// We can use jsdom-global at some point if maintaining these lists is a burden.
const whitelist = ['HTMLElement', 'Performance'];
const blacklist = ['sessionStorage', 'localStorage'];
function createD... | // @flow
const { JSDOM } = require('jsdom');
const Node = require('jsdom/lib/jsdom/living/node-document-position');
// We can use jsdom-global at some point if maintaining that list turns out to be a burden.
const whiteList = ['HTMLElement', 'Performance'];
const blackList = ['sessionStorage', 'localStorage'];
funct... |
Simplify and utilize request()->user() and request()->guard() | <?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
trait HasTimezones
{
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
*
* @return \Illuminate\Support\Carbon
*/
... | <?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
trait HasTimezones
{
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
*
* @return \Illuminate\Support\Carbon
*/
... |
Fix issue when hydrating settings with missing default keys | import { observable, toJS } from 'mobx';
import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra';
import { SETTINGS_PATH, DEFAULT_APP_SETTINGS } from '../config';
const debug = require('debug')('Settings');
export default class Settings {
@observable store = DEFAULT_APP_SETTINGS;
constructor() {... | import { observable, toJS } from 'mobx';
import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra';
import { SETTINGS_PATH, DEFAULT_APP_SETTINGS } from '../config';
const debug = require('debug')('Settings');
export default class Settings {
@observable store = DEFAULT_APP_SETTINGS;
constructor() {... |
Make sure pwd strength API is not required to be able to register | <?php
namespace App\Validator;
use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Annotation
*/
class Password extends Compound
{
/**
* @param array<string, mixed> $options
*/
protected function getConstraints(array $options): array... | <?php
namespace App\Validator;
use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Annotation
*/
class Password extends Compound
{
/**
* @param array<string, mixed> $options
*/
protected function getConstraints(array $options): array... |
[FIX] Move code outside of exception | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
su... | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
su... |
Fix test by adding missing index | <?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';
class OrganismsTest extends PHPUnit_Framework_TestCase
{
public function testExecute()
{
list($service) = \WebService::factory('listing/Organisms');
$results = ($service->execute(array('limit' => 2)));
$this->asse... | <?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';
class OrganismsTest extends PHPUnit_Framework_TestCase
{
public function testExecute()
{
list($service) = \WebService::factory('listing/Organisms');
$results = ($service->execute(array('limit' => 2)));
$this->asse... |
Comment out flutter tests until we have set up CI to download it | var path = require('path');
var childProcess = require('child_process');
const env = Object.create(process.env);
const args = ['node_modules/vscode/bin/test'];
var exitCode = 0;
function runTests(testFolder, workspaceFolder) {
env.CODE_TESTS_WORKSPACE = path.join(process.cwd(), 'test', 'test_projects', workspaceFold... | var path = require('path');
var childProcess = require('child_process');
const env = Object.create(process.env);
const args = ['node_modules/vscode/bin/test'];
var exitCode = 0;
function runTests(testFolder, workspaceFolder) {
env.CODE_TESTS_WORKSPACE = path.join(process.cwd(), 'test', 'test_projects', workspaceFold... |
[SysApps] Make the JavaScript shim dispatch events
The first thing to be done is make the JavaScript DeviceCapabilties an EventTarget
(which is also a BindingObject). The BindingObjects are JavaScripts objects with
a link with some native object and they use a unique ID for routing messages
between them.
common.Event... | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Implementation of the W3C's Device Capabilities API.
// http://www.w3.org/2012/sysapps/device-capabilities/
var internal = requireNative('internal');... | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Implementation of the W3C's Device Capabilities API.
// http://www.w3.org/2012/sysapps/device-capabilities/
var internal = requireNative('internal');... |
Make it clear it's an empty loop. | var Events = {
add: function(obj, events) {
for (var type in events) {
var func = events[type];
if (obj.addEventListener) {
obj.addEventListener(type, func, false);
} else if (obj.attachEvent) {
// Make a bound closure that calls on the right object and
// passes on the global event object as a ... | var Events = {
add: function(obj, events) {
for (var type in events) {
var func = events[type];
if (obj.addEventListener) {
obj.addEventListener(type, func, false);
} else if (obj.attachEvent) {
// Make a bound closure that calls on the right object and
// passes on the global event object as a ... |
Add update store packet code | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
W... | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
W... |
Check if type is undefined first | const squanch = (...patterns) => {
return v => {
const primitives = ['Number', 'String', 'Boolean', 'Symbol'];
const isIdentical = (p, v) => p === v;
const isNull = (p, v) => isIdentical(null, p) && isIdentical(p, v);
const isUndefined = (p, v) => isIdentical(undefined, p) && isIdentical(p, v);
const isPrim... | const squanch = (...patterns) => {
return v => {
const primitives = ['Number', 'String', 'Boolean', 'Symbol'];
const isIdentical = (p, v) => p === v;
const isNull = (p, v) => isIdentical(null, p) && isIdentical(p, v);
const isUndefined = (p, v) => isIdentical(undefined, p) && isIdentical(p, v);
const isPrim... |
Allow tty process longer time to spawn in feature tests | import time, pexpect, re
PROMPT = "root@\w+:[^\r]+"
UP_ARROW = "\x1b[A"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', process.before).strip()
@when(u'I run the inter... | import time, pexpect, re
import nose.tools as nt
import subprocess as spr
PROMPT = "root@\w+:[^\r]+"
ENTER = "\n"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', proce... |
Update to include the latest web platform tests
Includes https://github.com/w3c/web-platform-tests/pull/5792. | "use strict";
if (process.env.NO_UPDATE) {
process.exit(0);
}
const path = require("path");
const fs = require("fs");
const request = require("request");
// Pin to specific version, reflecting the spec version in the readme.
//
// To get the latest commit:
// 1. Go to https://github.com/w3c/web-platform-tests/tree... | "use strict";
if (process.env.NO_UPDATE) {
process.exit(0);
}
const path = require("path");
const fs = require("fs");
const request = require("request");
// Pin to specific version, reflecting the spec version in the readme.
//
// To get the latest commit:
// 1. Go to https://github.com/w3c/web-platform-tests/tree... |
Update CSS Selector to Match ExHentai Changes | <?php
class ExPage_Index extends ExPage_Abstract
{
public function isLastPage()
{
return (count($this->find('td.ptds + td.ptdd')) > 0);
}
public function getGalleries()
{
$ret = array();
$links = $this->find('.itg.gld .gl1t .glname a');
foreach ($links as $linkElem... | <?php
class ExPage_Index extends ExPage_Abstract
{
public function isLastPage()
{
return (count($this->find('td.ptds + td.ptdd')) > 0);
}
public function getGalleries()
{
$ret = array();
$links = $this->find('td.itd .it5 a');
foreach ($links as $linkElem) {
... |
Add Shifting Sands to benchmark tests | """Script to run performance check."""
import time
from examples.game_of_life import (
GameOfLife, GOLExperiment
)
from examples.shifting_sands import (
ShiftingSands, ShiftingSandsExperiment
)
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
("... | """Script to run performance check."""
import time
from examples.game_of_life import GameOfLife, GOLExperiment
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
... |
Fix getting view path name. | <?php
namespace Ouzo;
use Ouzo\Utilities\Path;
class ViewPathResolver
{
public static function resolveViewPath($name)
{
return Path::join(ROOT_PATH, 'application', 'view', $name . self::getViewPostfix());
}
private static function getViewPostfix()
{
if (Uri::isAjax()) {
... | <?php
namespace Ouzo;
use Ouzo\Utilities\Path;
class ViewPathResolver
{
public static function resolveViewPath($name)
{
return Path::join(ROOT_PATH, 'application', 'view', $name . self::getViewPostfix());
}
private static function getViewPostfix()
{
if (Uri::isAjax()) {
... |
Check VE is available before running unit tests
Bug: T127763
Change-Id: Ic5eef55c3327f95362e2f69fbebc86be306790f7 | <?php
/**
* Graph extension Hooks
*
* @file
* @ingroup Extensions
*/
namespace Graph;
use ResourceLoader;
class Hooks {
/**
* Conditionally register the unit testing module for the ext.graph.visualEditor module
* only if that module is loaded
*
* @param array $testModules The array of registered test m... | <?php
/**
* Graph extension Hooks
*
* @file
* @ingroup Extensions
*/
namespace Graph;
use ResourceLoader;
class Hooks {
/**
* Conditionally register the unit testing module for the ext.graph.visualEditor module
* only if that module is loaded
*
* @param array $testModules The array of registered test m... |
Correct import order in tests init file | # tests.__init__
import os
import os.path
import shutil
import tempfile
from mock import patch
import yvs.shared as yvs
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCA... | # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCA... |
Add column width to posts for larger displays | <div class="post col-md-10 col-lg-8">
@if (isset($post))
<h1>{{{ $post->title }}}</h1>
{{-- Escape html entities, format with paragraph tags --}}
{{-- Leading and trailing paragraph tags are required for leading and trailing paragraphs respectively --}}
<p>{{ str_replace(array("\n",... | <div class="post">
@if (isset($post))
<h1>{{{ $post->title }}}</h1>
{{-- Escape html entities, format with paragraph tags --}}
{{-- Leading and trailing paragraph tags are required for leading and trailing paragraphs respectively --}}
<p>{{ str_replace(array("\n","\r\n"), "</p><p>",... |
Check update against right property | module.exports = function(sugar, models, assert) {
return function updateMultipleAuthors(cb) {
var firstAuthor = {name: 'foo'};
var secondAuthor = {name: 'bar'};
var authors = [firstAuthor, secondAuthor];
sugar.create(models.Author, authors, function(err, d) {
if(err) re... | module.exports = function(sugar, models, assert) {
return function updateMultipleAuthors(cb) {
var firstAuthor = {name: 'foo'};
var secondAuthor = {name: 'bar'};
var authors = [firstAuthor, secondAuthor];
sugar.create(models.Author, authors, function(err, d) {
if(err) re... |
Use regex instead of explode | <?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>
class BookmarkHelper extends AppHelper {
var $helpers = array('Html');
function print_bookmark($bookmark) {
echo $this->favicon($bookmark);
echo '<td>';
echo $this->Html->link($bookmark['title'],
array('controller' => 'bookmarks', 'action' => '... | <?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>
class BookmarkHelper extends AppHelper {
var $helpers = array('Html');
function print_bookmark($bookmark) {
echo $this->favicon($bookmark);
echo '<td>';
echo $this->Html->link($bookmark['title'],
array('controller' => 'bookmarks', 'action' => '... |
ca_on_candidates: Make CSV URL more specific | from utils import CSVScraper
from datetime import date
class OntarioCandidatesPersonScraper(CSVScraper):
csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv'
encoding = 'utf-8'
... | from utils import CSVScraper
from datetime import date
class OntarioCandidatesPersonScraper(CSVScraper):
csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv'
encoding = 'utf-8'
updated_at = date(2018, 1,... |
Remove unnecessary "/" in path | package cmd
import (
"fmt"
"net/http"
"net/url"
"os"
"github.com/cozy/cozy-stack/config"
"github.com/spf13/cobra"
"strconv"
)
// statusCmd represents the status command
var statusCmd = &cobra.Command{
Use: "status",
Short: "Check if the HTTP server is running",
Long: `Check if the HTTP server has been s... | package cmd
import (
"fmt"
"net/http"
"net/url"
"os"
"github.com/cozy/cozy-stack/config"
"github.com/spf13/cobra"
"strconv"
)
// statusCmd represents the status command
var statusCmd = &cobra.Command{
Use: "status",
Short: "Check if the HTTP server is running",
Long: `Check if the HTTP server has been s... |
Replace $this->container->get() with $this->get() in controllers extending abstract controller. | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Contr... | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Contr... |
Set initialLine of found file | 'use babel'
import * as util from './util'
import { Range } from 'atom'
export default {
wordRegExp: /([\w\.\-_]+)/,
providerName: "moie-modelica",
setClient(client) {
this.client = client
console.log("setting client in hyperclickProvider")
},
getSuggestionForWord(editor, text, range) {
self = ... | 'use babel'
import * as util from './util'
import { Range } from 'atom'
export default {
wordRegExp: /([\w\.\-_]+)/,
providerName: "moie-modelica",
setClient(client) {
this.client = client
console.log("setting client in hyperclickProvider")
},
getSuggestionForWord(editor, text, range) {
self = ... |
Add another url pattern for debugging public layers | from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_pu... | from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<se... |
Trim whitespace from argument on insert | /* Copyright 2015 Troy D. Heninger
*
* 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 ... | /* Copyright 2015 Troy D. Heninger
*
* 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 ... |
Disable timezone support for tests, as the date / time fields' tests use naive datatime objects and fail if it's enabled. | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import os
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
# IMO this is unimportant
#if django.VERSION[0] >= 1 and django.VERSION[1] >= 3:
#INS... | # -*- coding: utf-8 -*-
"""
Settings overrided for test time
"""
import os
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'modeltranslation.tests',
)
# IMO this is unimportant
#if django.VERSION[0] >= 1 and django.VERSION[1] >= 3:
#INS... |
Write sourcemaps to a separate file. | var gulp = require('gulp'),
mocha = require('gulp-mocha'),
eslint = require('gulp-eslint'),
babel = require('gulp-babel'),
sourcemaps = require('gulp-sourcemaps');
require('babel/register');
gulp.task('lint', function () {
return gulp
.src(['./src/**/*.js', './tests/**/*.js'])
.pip... | var gulp = require('gulp'),
mocha = require('gulp-mocha'),
eslint = require('gulp-eslint'),
babel = require('gulp-babel'),
sourcemaps = require('gulp-sourcemaps');
require('babel/register');
gulp.task('lint', function () {
return gulp
.src(['./src/**/*.js', './tests/**/*.js'])
.pip... |
Use is instead of == for types. | from nolang.error import AppError
from nolang.objects.root import W_Root
class W_ListObject(W_Root):
def __init__(self, w_items):
self._w_items = w_items
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._w_items]) + ']'
def len(self, space):
return len(sel... | from nolang.error import AppError
from nolang.objects.root import W_Root
class W_ListObject(W_Root):
def __init__(self, w_items):
self._w_items = w_items
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._w_items]) + ']'
def len(self, space):
return len(sel... |
Fix early return failure to reset context |
var Picker = function(context) {
this.context = context;
}
Picker.prototype = {
pick: function(node, x, y, lx, ly) {
var ctx = this.context;
var tx = node.x || 0;
var ty = node.y || 0;
ctx.save();
ctx.translate(tx, ty);
// Apply transform to local coordinate values
lx -= tx;
ly... |
var Picker = function(context) {
this.context = context;
}
Picker.prototype = {
pick: function(node, x, y, lx, ly) {
var ctx = this.context;
var tx = node.x || 0;
var ty = node.y || 0;
ctx.save();
ctx.translate(tx, ty);
// Apply transform to local coordinate values
lx -= tx;
ly... |
Upgrade Localstack image to version 0.12.3 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.