text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use statusCode instead of code | /**
* Various HTTP helper functions and defaults.
*/
'use strict';
/**
* Module dependencies.
*/
var http = require('http');
/**
* Default charset.
*/
var CHARSET = 'utf-8';
/**
* Reply to options request
*/
function options(req, res, methods) {
res.setHeader('Allow', methods.join(' '));
}
/**
* Repl... | /**
* Various HTTP helper functions and defaults.
*/
'use strict';
/**
* Module dependencies.
*/
var http = require('http');
/**
* Default charset.
*/
var CHARSET = 'utf-8';
/**
* Reply to options request
*/
function options(req, res, methods) {
res.setHeader('Allow', methods.join(' '));
}
/**
* Repl... |
Move updating preview text to its own function | 'use strict';
var GameDataCreator = require('../gamedata');
var PointView = require('../prefabs/pointview');
function Editor() {}
Editor.prototype = {
create: function() {
this.game.data = new GameDataCreator.GameData();
var background = this.game.add.sprite(0, 0, 'background');
this.sprites = this.game.... | 'use strict';
var GameDataCreator = require('../gamedata');
var PointView = require('../prefabs/pointview');
function Editor() {}
Editor.prototype = {
create: function() {
this.game.data = new GameDataCreator.GameData();
var background = this.game.add.sprite(0, 0, 'background');
this.sprites = this.game.... |
Add support to register body from struct data | package httpfake
import (
"encoding/json"
"fmt"
"net/http"
)
// Response stores the settings defined by the request handler
// of how it will respond the request back
type Response struct {
StatusCode int
BodyBuffer []byte
Header http.Header
}
// NewResponse creates a new Response
func NewResponse() *Respo... | package httpfake
import "net/http"
// Response stores the settings defined by the request handler
// of how it will respond the request back
type Response struct {
StatusCode int
BodyBuffer []byte
Header http.Header
}
// NewResponse creates a new Response
func NewResponse() *Response {
return &Response{
He... |
Improve formatting of schema format exception messages |
class SchemaFormatException(Exception):
"""Exception which encapsulates a problem found during the verification of a
a schema."""
def __init__(self, message, path):
self._message = message.format('\"{}\"'.format(path))
self._path = path
@property
def path(self):
"""The fi... |
class SchemaFormatException(Exception):
"""Exception which encapsulates a problem found during the verification of a
a schema."""
def __init__(self, message, path):
self._message = message.format(path)
self._path = path
@property
def path(self):
"""The field path at which... |
Add variables to send to the view | <?php
namespace RadDB\Http\Controllers;
use Charts;
use RadDB\GenData;
use RadDB\HVLData;
use RadDB\Machine;
use RadDB\TestDates;
use RadDB\RadSurveyData;
use RadDB\RadiationOutput;
use Illuminate\Http\Request;
class QAController extends Controller
{
/**
* Index page for QA/survey data section
*
*... | <?php
namespace RadDB\Http\Controllers;
use Charts;
use RadDB\Machine;
use RadDB\TestDates;
use RadDB\GenData;
use RadDB\HVLData;
use RadDB\RadSurveyData;
use RadDB\RadiationOutput;
use Illuminate\Http\Request;
class QAController extends Controller
{
/**
* Index page for QA/survey data section
*
*... |
Rename "Label" to "TextView" in jquery example
Done to reflect eclipsesource/tabris-js@ca0f105e82a2d27067c9674ecf71a93af2c7b7bd
Change-Id: I1c267e0130809077c1339ba0395da1a7e1c6b281 | // jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle"
// https://github.com/jquery/jquery#how-to-build-your-own-jquery
var $ = require("./lib/jquery.min.js");
var MARGIN = 12;
var page = tabris.create(... | // jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle"
// https://github.com/jquery/jquery#how-to-build-your-own-jquery
var $ = require("./lib/jquery.min.js");
var MARGIN = 12;
var page = tabris.create(... |
Reduce bounds on generic: Java lacks most of the stuff to actually use it. | package to.etc.domui.component.ntbl;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;
/**
* Event handler for row-based editors.
*
* @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
* Created on Dec 21, 2009
*/
public interface IRowEditorEvent<T, E ... | package to.etc.domui.component.ntbl;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;
/**
* Event handler for row-based editors.
*
* @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
* Created on Dec 21, 2009
*/
public interface IRowEditorEvent<T, E ... |
Add a useful standard ACE shortcut. | var $ = document.getElementById.bind(document);
var exampleTests = require('./example-tests');
var Main = require('../src/main/main-controller');
var providedByAceEditor = function() {/* noop() */};
var isMac = navigator.platform.indexOf('Mac') === 0;
var metaKey = isMac ? 'Meta' : 'Control';
var shortcuts = [
[[met... | var $ = document.getElementById.bind(document);
var exampleTests = require('./example-tests');
var Main = require('../src/main/main-controller');
var providedByAceEditor = function() {/* noop() */};
var isMac = navigator.platform.indexOf('Mac') === 0;
var metaKey = isMac ? 'Meta' : 'Control';
var shortcuts = [
[[met... |
Tag list now uses the simple table style
Signed-off-by: Prashant P Shah <80f978b5ac27fb318171799f0fb6a277863f2bf5@gmail.com> | <?php
$tags_q = $this->db->get("tags");
echo "<table border=0 cellpadding=5 class=\"simple-table tag-table\">";
echo "<thead><tr><th>Title</th><th>Color</th><th colspan=5></th></tr></thead>";
echo "<tbody>";
$odd_even = "odd";
foreach ($tags_q->result() as $row)
{
echo "<tr class=\"tr-" . $odd_even. "\">";
e... | <?php
$tags_q = $this->db->get("tags");
echo "<table border=0 cellpadding=5 class=\"generaltable\">";
echo "<thead><tr><th>Title</th><th>Color</th><th colspan=5>Actions</th></tr></thead>";
echo "<tbody>";
$odd_even = "odd";
foreach ($tags_q->result() as $row)
{
echo "<tr class=\"tr-" . $odd_even. "\">";
echo... |
Correct class name of arduino nano | BOARDS = {
'arduino': {
'digital': tuple(x for x in range(14)),
'analog': tuple(x for x in range(6)),
'pwm': (3, 5, 6, 9, 10, 11),
'use_ports': True,
'disabled': (0, 1) # Rx, Tx, Crystal
},
'arduino_mega': {
'digital': tuple(x for x in range(54)),
'an... | BOARDS = {
'arduino': {
'digital': tuple(x for x in range(14)),
'analog': tuple(x for x in range(6)),
'pwm': (3, 5, 6, 9, 10, 11),
'use_ports': True,
'disabled': (0, 1) # Rx, Tx, Crystal
},
'arduino_mega': {
'digital': tuple(x for x in range(54)),
'an... |
Add distutils for legacy pypi | #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
__author__ = 'Mike Helmick <me@michaelhelmick.com>'
__version__ = '1.1.1'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
setup(
n... | #!/usr/bin/env python
import os
import sys
from setuptools import setup
__author__ = 'Mike Helmick <me@michaelhelmick.com>'
__version__ = '1.1.1'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
setup(
name='python-tumblpy',
version=__version__,
install_require... |
Add redirect from / to /polls | """vote URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | """vote URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... |
Allow slashes and backslashes in the code's content. | <?php
/*
* (c) Jeroen van den Enden <info@endroid.nl>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Endroid\Bundle\QrCodeBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraB... | <?php
/*
* (c) Jeroen van den Enden <info@endroid.nl>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Endroid\Bundle\QrCodeBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraB... |
Exclude counter from chart form | from collections import defaultdict
from django.http import QueryDict
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from charter.models import Chart, ChartDataSet, DataRow
from charter.form_utils import BaseFormSet
class ChartForm(djangoforms.ModelForm):
class Meta:
mo... | from collections import defaultdict
from django.http import QueryDict
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from charter.models import Chart, ChartDataSet, DataRow
from charter.form_utils import BaseFormSet
class ChartForm(djangoforms.ModelForm):
class Meta:
mo... |
Make migration rerunable (just for simplicity's sake) | <?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
/**
* Migration script for adding mail preference option to incremental registration
**/
class Migration20130715111246ModIncrementalRegistration extends Hubzero_Migration
{
/**
* Up
**/
protected static fu... | <?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
/**
* Migration script for ...
**/
class Migration20130715111246ModIncrementalRegistration extends Hubzero_Migration
{
/**
* Up
**/
protected static function up($db)
{
$queries = array(
'alter table ... |
Remove auto generated code by Intellj | package com.sailthru.client;
import com.google.gson.JsonSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonNull;
import java.lang.reflect.Type;... | package com.sailthru.client;
import com.google.gson.JsonSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonNull;
import java.lang.reflect.Type;... |
Add support for per Argument help data | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None, help=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must h... | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at leas... |
Change time frequency to publish message | 'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const config = require('./config')
const app = express()
const publisher = require('./publisher')
var cronJob = require('cron').CronJob
app.set('port', (process.env.PORT || config.PORT))
app.use(bodyParser.urlencoded({extended:... | 'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const config = require('./config')
const app = express()
const publisher = require('./publisher')
var cronJob = require('cron').CronJob
app.set('port', (process.env.PORT || config.PORT))
app.use(bodyParser.urlencoded({extended:... |
proxy: Reduce SO_LINGER timeout to 10 seconds
The existing value of 1 minute can put a lot of stress on the proxymap table in
an environment with many concurrent, short lived connections.
Signed-off-by: Thomas Graf <5f50a84c1fa3bcff146405017f36aec1a10a9e38@cilium.io> | // Copyright 2017 Authors of Cilium
//
// 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 2017 Authors of Cilium
//
// 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 ... |
Include correct Paweł's email :camel: | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Shipping\Model;
use Doctrine\Common\Collections\Collection;
/**
* @autho... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Shipping\Model;
use Doctrine\Common\Collections\Collection;
/**
* @autho... |
Correct typo in documentation of crop_corners | import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y2' or a four-tuple of integers.
"""
if not box:
return image
if not isinstance(box... | import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
if not box:
return image
if not isinstance(box... |
Add real author to author key too. | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Module name",
"summary": "Module summary",
"version": "8.0.1.0.0",
"category": "Uncategorized",
"license": "AGPL-3",
"website": "https://odoo-community.org/",
"au... | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Module name",
"summary": "Module summary",
"version": "8.0.1.0.0",
"category": "Uncategorized",
"license": "AGPL-3",
"website": "https://odoo-community.org/",
"au... |
Implement method to search group for clients | /**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
let counter = 0
/**
* Represent connected client
* @type {Client}
*/
module.exports = class Client {
constructor(socket) {
this.socket = socket
this.name = 'anonymous'
... | /**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
let counter = 0
/**
* Represent connected client
* @type {Client}
*/
module.exports = class Client {
constructor(socket) {
this.socket = socket
this.name = 'anonymous'
... |
Fix caching time dependant MNT provider query (api) | const db = require('../db.js');
async function getTrips(id, coachOnly) {
return (await db.query(`
SELECT TIME_TO_SEC(time) AS time, TIME_TO_SEC(time) - TIME_TO_SEC(NOW()) as countdown, route.name, trip.destination, route.type, 'mnt' AS provider FROM stops AS stop
JOIN stop_times ON stop_id = id
JOIN trips A... | const db = require('../db.js');
const cache = require('../utils/cache.js');
async function getTrips(id, coachOnly) {
return await cache.use('mnt-trips', id, async () => (await db.query(`
SELECT TIME_TO_SEC(time) AS time, TIME_TO_SEC(time) - TIME_TO_SEC(NOW()) as countdown, route.name, trip.destination, route.typ... |
Fix webpack context path on windows | /* global __dirname */
'use strict';
var webpack = require('webpack');
var path = require('path');
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');
module.exports = {
context: path.resolve(__dirname, 'client'),
entry: {
index: './js/index',
embed: './js/embed'
},
output: {
... | /* global __dirname */
'use strict';
var webpack = require('webpack');
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');
module.exports = {
context: __dirname + '/client',
entry: {
index: './js/index',
embed: './js/embed'
},
output: {
filename: '[name].bundle.js',
chu... |
Mark all of these tests too. | import pytest
from components.people.models import Group, Idol, Membership, Staff
from components.people.factories import (GroupFactory, IdolFactory,
MembershipFactory, StaffFactory)
pytestmark = pytest.mark.django_db
def test_group_factory():
factory = GroupFactory()
assert isinstance(factory, Group)
... | import pytest
from components.people.models import Group, Idol, Membership, Staff
from components.people.factories import (GroupFactory, IdolFactory,
MembershipFactory, StaffFactory)
@pytest.mark.django_db
def test_group_factory():
factory = GroupFactory()
assert isinstance(factory, Group)
assert 'gr... |
Test validator can now be used as a module | #! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = None
jsons = []
valid_vms = []
def load_schema(filename):
global vm_schema
vm_schema = json.loads(open(filename).read());
def validate_vm_spec(filename):
global valid_vms
vm_spec = None
# Load and parse as JSON
... | #! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = json.loads(open("vm.schema.json").read());
def validate_vm_spec(filename):
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + file... |
Remove another reference to DeferredResult. | #!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reacto... | #!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reacto... |
Fix purchase confirmation decimal points | import React, { PropTypes } from 'react';
import { FormattedTime } from 'react-intl';
import { epochToDate } from '../_utils/DateUtils';
import { M, NumberPlain } from '../_common';
const PurchaseConfirmation = ({ receipt }) => (
<div>
<table>
<thead>
<th colSpan="2">{`Contract Ref. ${receipt.contract_id}`}<... | import React, { PropTypes } from 'react';
import { FormattedTime } from 'react-intl';
import { epochToDate } from '../_utils/DateUtils';
import { M } from '../_common';
const PurchaseConfirmation = ({ receipt }) => (
<div>
<table>
<tbody>
<tr>
<td colSpan="2">
{receipt.longcode}
</td>
</t... |
Add missing properties to SNS::Subscription | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
try:
from awacs.aws import Policy
policytypes = (dict, Policy)
except ImportError:
policytypes = dict,
class Subscription(AWSProperty):
props = {
... | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
try:
from awacs.aws import Policy
policytypes = (dict, Policy)
except ImportError:
policytypes = dict,
class Subscription(AWSProperty):
props = {
... |
Add minimal compatibility with changes in DBAL 2.11 RunSqlCommand
Proper fix would be more involved, relying on interfaces in DBAL to not change, which we cannot assume won't happen at this point. Full, proper fix needs to be done once DBAL 2.11 API is stable. Such fix will probably involve deprecating our current com... | <?php
namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy;
use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Execute a SQL query and output the res... | <?php
namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy;
use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Execute a SQL query and output the res... |
Use System.import instead of require | import React from 'react';
import {render} from 'react-dom';
import {AppContainer} from 'react-hot-loader';
import store from './store';
import Root from './Root';
render(
<AppContainer>
<Root store={store} />
</AppContainer>,
document.getElementById('content')
);
if (module.hot) {
module.hot... | import React from 'react';
import {render} from 'react-dom';
import {AppContainer} from 'react-hot-loader';
import store from './store';
import Root from './Root';
render(
<AppContainer>
<Root store={store} />
</AppContainer>,
document.getElementById('content')
);
if (module.hot) {
module.hot... |
Set small modal for catch all | import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { Modal, ContentModal, FooterModal, ResetButton } from 'react-components';
import AddressesTable from './AddressesTable';
const CatchAllModal = ({ domain, show, onClose }) => {
return (
<Modal modalClassName="p... | import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { Modal, ContentModal, FooterModal, ResetButton } from 'react-components';
import AddressesTable from './AddressesTable';
const CatchAllModal = ({ domain, show, onClose }) => {
return (
<Modal modalClassName="p... |
Bump version numbers of ppp_datamodel and ppp_core. | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_nlp_ml_standalone',
version='0.1',
description='Compute triplets from a question, with an ML approach',
url='https://github.com/ProjetPP',
author='Quentin Cormier',
author_email='quentin.cormier@ens-lyon.fr',
... | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_nlp_ml_standalone',
version='0.1',
description='Compute triplets from a question, with an ML approach',
url='https://github.com/ProjetPP',
author='Quentin Cormier',
author_email='quentin.cormier@ens-lyon.fr',
... |
Drop FK before dropping instance_id column. | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... |
Fix potential issue when parsing text content charset | package com.vtence.molecule.testing.http;
import com.vtence.molecule.http.ContentType;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class TextContent implements HttpContent {
private final String text;
private fina... | package com.vtence.molecule.testing.http;
import com.vtence.molecule.http.ContentType;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class TextContent implements HttpContent {
private final String text;
private fina... |
[Google] Add the possibility to get more details on an api error | <?php
/**
* This file is part of the CalendArt package
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*
* @copyright Wisembly
* @license http://www.opensource.org/licenses/MIT-License MIT License
*/
namespace CalendArt\Adapter\Go... | <?php
/**
* This file is part of the CalendArt package
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*
* @copyright Wisembly
* @license http://www.opensource.org/licenses/MIT-License MIT License
*/
namespace CalendArt\Adapter\Go... |
fix: Use different import for better testing | """AWS Spinnaker Application."""
from pprint import pformat
from foremast.app import base
from foremast.utils import wait_for_task
class SpinnakerApp(base.BaseApp):
"""Create AWS Spinnaker Application."""
def create(self):
"""Send a POST to spinnaker to create a new application with class variables.... | """AWS Spinnaker Application."""
from pprint import pformat
from foremast.app.base import BaseApp
from foremast.utils import wait_for_task
class SpinnakerApp(BaseApp):
"""Create AWS Spinnaker Application."""
def create(self):
"""Send a POST to spinnaker to create a new application with class variable... |
Add missing keepalive on TCP connection | package livestatus
import (
"net"
)
const bufferSize = 1024
// Client represents a Livestatus client instance.
type Client struct {
network string
address string
dialer *net.Dialer
conn net.Conn
}
// NewClient creates a new Livestatus client instance.
func NewClient(network, address string) *Client {
retu... | package livestatus
import (
"net"
)
const bufferSize = 1024
// Client represents a Livestatus client instance.
type Client struct {
network string
address string
dialer *net.Dialer
conn net.Conn
}
// NewClient creates a new Livestatus client instance.
func NewClient(network, address string) *Client {
retu... |
Add code box utils file. | import React from "react";
import CSSModules from 'react-css-modules';
import styles from "../../../scss/_code-box.scss";
import _ from "lodash";
import {compare} from '../../utils/code-box-utils';
class CSSView extends React.Component {
constructor(){
super();
}
render() {
const{dispatch, cssView, pi... | import React from "react";
import CSSModules from 'react-css-modules';
import styles from "../../../scss/_code-box.scss";
import _ from "lodash";
import {compare} from '../../utils/code-box-utils';
class CSSView extends React.Component {
constructor(){
super();
}
render() {
const{dispatch, cssView, pi... |
Improve subprocess call during deployment | import subprocess
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def dep... | import subprocess
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def dep... |
TabBarIcon: Use platformPrefixIcon to smartly prefix the icon
Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
Tested-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com> | // @flow
import * as React from 'react'
import {StyleSheet, Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
const styles = StyleSheet.create({
icon: {
fontSize: Platform.select({
ios: 30,
android: 24,
}),
},
})
type Props = {
tintColor: string,
focused: boolean,
}
ex... | // @flow
import * as React from 'react'
import {StyleSheet, Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
const styles = StyleSheet.create({
icon: {
fontSize: Platform.select({
ios: 30,
android: 24,
}),
},
})
type Props = {
tintColor: string,
focused: boolean,
}
ex... |
Use .some instead of ES6 .find | import Ui from "./Ui";
import Generator from "./Generator";
Ui.initializeDefaults();
$.getJSON("/features.json").done(displayFeatures);
$.getJSON("/formats.json").done(displayFormats);
function displayFeatures(features) {
features.forEach(function (feature) {
var checkbox = createFeatureCheckbox(feature)... | import Ui from "./Ui";
import Generator from "./Generator";
Ui.initializeDefaults();
$.getJSON("/features.json").done(displayFeatures);
$.getJSON("/formats.json").done(displayFormats);
function displayFeatures(features) {
features.forEach(function (feature) {
var checkbox = createFeatureCheckbox(feature)... |
Set age groups to match paper registration. | calculateAgeGroup = function (age) {
/*
* Calculate the age group
* based on an age input
* return the age group string
* 0-5: child
* 6-12: youth
* 13-17: teen
* 18-25: yaf
* 26+: adult
*/
// Make sure age is an integer
try {
parseInt(age);
}
catch (erro... | calculateAgeGroup = function (age) {
/*
* Calculate the age group
* based on an age input
* return the age group string
* 0-5: child
* 6-10: youth
* 11-17: teen
* 18-25: yaf
* 26+: adult
*/
// Make sure age is an integer
try {
parseInt(age);
}
catch (erro... |
Read the config file only from /etc/autocloud/autocloud.cfg file. | # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
name = '/etc/autocloud/autocloud.cfg'
if not os.path.exists(name):
raise Exception('Please add a proper cofig file under /etc/autocloud/')
config.read(name)
KOJI_SERVER_URL = config.get('autocloud', ... | # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
name = "{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT)
if not os.path.exists(name):
name = '/etc/autocloud/autocloud.cfg'
conf... |
Clean up the description for PyPI | import sys
import re
if sys.version < '3.4':
print('Sorry, this is not a compatible version of Python. Use 3.4 or later.')
exit(1)
from setuptools import setup, find_packages
with open('README.md') as f:
description = f.read()
description = re.sub(r'\[!\[.+\].+\]\(.+\)', '', description)
descript... | import sys
if sys.version < '3.4':
print('Sorry, this is not a compatible version of Python. Use 3.4 or later.')
exit(1)
from setuptools import setup, find_packages
with open('README.md') as f:
description = f.read()
from circle_asset.version import VERSION, SHORT_DESCRIPTION
setup(name='circle-asset',... |
Create a transaction ID from a string UUID | <?php
declare(strict_types=1);
namespace PerFi\Domain\Transaction;
use Ramsey\Uuid\Uuid;
class TransactionId
{
/**
* @var Uuid
*/
private $id;
/**
* Create an transaction ID
*
* @param Uuid $id
*/
private function __construct(Uuid $id)
{
$this->id = $id;
... | <?php
declare(strict_types=1);
namespace PerFi\Domain\Transaction;
use Ramsey\Uuid\Uuid;
class TransactionId
{
/**
* @var Uuid
*/
private $id;
/**
* Create an transaction ID
*
* @param Uuid $id
*/
private function __construct(Uuid $id)
{
$this->id = $id;
... |
Add second constructor for already formed string
Summary: When catching an exception that has formatting chars in it, we can run into issues if we try to format again
Reviewed By: cjhopman
shipit-source-id: 1929d59f1795cfbdefd0c86688b6c852f4438205 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 applic... | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 applic... |
Fix the initial factionId bug | import { List } from 'immutable';
import { Reducer } from 'flux-reducer';
import factions from '../models/faction';
export default class ShipInputReducer extends Reducer({
shipName: '',
factionId: '',
factions: new List,
}) {
static create() {
var allFactions = factions.getAll();
return new ShipInputRe... | import { List } from 'immutable';
import { Reducer } from 'flux-reducer';
import factions from '../models/faction';
export default class ShipInputReducer extends Reducer({
shipName: '',
factionId: '',
factions: new List,
}) {
static create() {
return new ShipInputReducer({
factions: new List(factions... |
Enable Node 16 and NPM 7/8 support on generation
Signed-off-by: Derrick Mehaffy <d3de28f82f22c58e03cd756b0176b069ba189978@gmail.com> | 'use strict';
/**
* Expose main package JSON of the application
* with basic info, dependencies, etc.
*/
module.exports = opts => {
const {
strapiDependencies,
additionalsDependencies,
strapiVersion,
projectName,
uuid,
packageJsonStrapi,
} = opts;
// Finally, return the JSON.
retur... | 'use strict';
/**
* Expose main package JSON of the application
* with basic info, dependencies, etc.
*/
module.exports = opts => {
const {
strapiDependencies,
additionalsDependencies,
strapiVersion,
projectName,
uuid,
packageJsonStrapi,
} = opts;
// Finally, return the JSON.
retur... |
Apply golang opts, and give an example | package main
import (
"fmt"
"os"
"time"
"github.com/voxelbrain/goptions"
)
func main() {
options := struct {
Servers []string `goptions:"-s, --server, obligatory, description='Servers to connect to'"`
Password string `goptions:"-p, --password, description='Don\\'t prompt for password'"`
Timeo... | package main
import (
"github.com/voxelbrain/goptions"
"os"
"time"
)
func main() {
options := struct {
Servers []string `goptions:"-s, --server, obligatory, description='Servers to connect to'"`
Password string `goptions:"-p, --password, description='Don\\'t prompt for password'"`
Timeout time... |
Fix bug where domains were valid entries. | /* Returns a clever domain for the given text, if one exists. */
function checkDomains() {
/* Get the input string */
var userString = document.getElementById("domainInput").value;
/* Sample list of domain suffixes */
var data = [
'io',
'biz',
'im',
'info'
];
/* Try to find a matching dom... | /* Returns a clever domain for the given text, if one exists. */
function checkDomains() {
/* Get the input string */
var userString = document.getElementById("domainInput").value;
/* Sample list of domain suffixes */
var data = [
'io',
'biz',
'im',
'info'
];
/* Try to find a matching dom... |
Fix typo in jsbox URLs. | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.... | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.... |
Use logrus.FieldLogger instead of *logrus.Logger
This allows supplying a logrus logger that already has fields configured | // Package logrusadapter provides a logger that writes to a github.com/sirupsen/logrus.Logger
// log.
package logrusadapter
import (
"github.com/jackc/pgx"
"github.com/sirupsen/logrus"
)
type Logger struct {
l logrus.FieldLogger
}
func NewLogger(l logrus.FieldLogger) *Logger {
return &Logger{l: l}
}
func (l *Lo... | // Package logrusadapter provides a logger that writes to a github.com/sirupsen/logrus.Logger
// log.
package logrusadapter
import (
"github.com/jackc/pgx"
"github.com/sirupsen/logrus"
)
type Logger struct {
l *logrus.Logger
}
func NewLogger(l *logrus.Logger) *Logger {
return &Logger{l: l}
}
func (l *Logger) Lo... |
STYLE: Fix missing line at end of file
Fix missing line
Remove whitespace | """
Tests corresponding to sandbox.stats.runs
"""
from numpy.testing import assert_almost_equal
from statsmodels.sandbox.stats.runs import runstest_1samp
def test_mean_cutoff():
x = [1] * 5 + [2] * 6 + [3] * 8
cutoff = "mean"
expected = (-4.007095978613213, 6.146988816717466e-05)
results = runstest_1s... | """
Tests corresponding to sandbox.stats.runs
"""
from numpy.testing import assert_almost_equal
from statsmodels.sandbox.stats.runs import runstest_1samp
def test_mean_cutoff():
x = [1] * 5 + [2] * 6 + [3] * 8
cutoff = "mean"
expected = (-4.007095978613213, 6.146988816717466e-05)
results = runstest_1s... |
Store yang store snapshot cache using soft reference.
Change-Id: I9b159db83ba204b4a636f2314fd4fc2e7b6f654c
Signed-off-by: Tomas Olvecky <15c0b3ba77d9541ebd8ccf1bd003ebd96c682ed7@cisco.com> | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org... | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org... |
Refactor to avoid export expression assignment | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
Use `make_admin_app`, document why `admin_app` is still needed | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
API-specific fixtures
"""
import pytest
from tests.base import create_admin_app
from tests.conftest import CONFIG_PATH_DATA_KEY
from .helpers import assemble_authorization_header
API_TOKEN = 'just-say-PLEASE!'
@pytes... | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
API-specific fixtures
"""
import pytest
from tests.base import create_admin_app
from tests.conftest import CONFIG_PATH_DATA_KEY
from .helpers import assemble_authorization_header
API_TOKEN = 'just-say-PLEASE!'
@pytes... |
Increase TAC maxteamsize to 3 (from 1)
- Fixes #343
- Opens #346, since the user cannot select the teamsize | /**
* TAC Presets: TAC rankings, followed by wins and numgames
*
* @return Presets
* @author Erik E. Lorenz <erik@tuvero.de>
* @license MIT License
* @see LICENSE
*/
define(function () {
var Presets;
Presets = {
target: 'tac',
systems: {
swiss: {
ranking: ['tac', 'numgames', 'wins', '... | /**
* TAC Presets: TAC rankings, followed by wins and numgames
*
* @return Presets
* @author Erik E. Lorenz <erik@tuvero.de>
* @license MIT License
* @see LICENSE
*/
define(function () {
var Presets;
Presets = {
target: 'tac',
systems: {
swiss: {
ranking: ['tac', 'numgames', 'wins', '... |
[BugFix] Disable remember me on auto login | <?php namespace Wells\L4LdapNtlm;
use Illuminate\Auth\Guard;
/**
* An LDAP/NTLM authentication driver for Laravel 4.
*
* @author Brian Wells (https://github.com/wells/)
*
*/
class L4LdapNtlmGuard extends Guard
{
public function admin()
{
// Check if user is logged in
if ($this->check() && $this->user())
... | <?php namespace Wells\L4LdapNtlm;
use Illuminate\Auth\Guard;
/**
* An LDAP/NTLM authentication driver for Laravel 4.
*
* @author Brian Wells (https://github.com/wells/)
*
*/
class L4LdapNtlmGuard extends Guard
{
public function admin()
{
// Check if user is logged in
if ($this->check() && $this->user())
... |
Fix static url path error. | """
hello/__init__.py
------------------
Initializes Flask application and brings all components together.
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_misaka import Misaka
# Create application object
app = Flask(__name__, instance_relative_config=True,
static... | """
hello/__init__.py
------------------
Initializes Flask application and brings all components together.
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_misaka import Misaka
# Create application object
app = Flask(__name__, instance_relative_config=True,
static... |
Add queries.rate to the 'autoscaling' consumer. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Metrics used for autoscaling
*
* @author bratseth
*/
publi... | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Metrics used for autoscaling
*
* @author bratseth
*/
publi... |
:art: Throw TypeError instead of Error | import find from 'lodash.find';
import composedFetch from '../composedFetch.js';
export const sourcePostalPoint = id => composedFetch(id)
.then(data => {
const result = find(data.events, { key: `received.domestic-corner` });
return result.location.en;
})
.catch(e => console.error(e));
export const desti... | import find from 'lodash.find';
import composedFetch from '../composedFetch.js';
export const sourcePostalPoint = id => composedFetch(id)
.then(data => {
const result = find(data.events, { key: `received.domestic-corner` });
return result.location.en;
})
.catch(e => console.error(e));
export const desti... |
Add fields to Special model | from django.db import models
MAX_PRICE_FORMAT = {
'max_digits': 5,
'decimal_places': 2
}
SPECIAL_TYPES = (
('LU', 'Lunch'),
('BR', 'Breakfast'),
('DI', 'Dinner'),
)
MAX_RESTAURANT_NAME_LENGTH = 50
MAX_DESCRIPTION_LENGTH = 500
class Restaurant(models.Model):
name = models.Ch... | from django.db import models
MAX_PRICE_FORMAT = {
'max_digits': 5,
'decimal_places': 2
}
SPECIAL_TYPES = (
('LU', 'Lunch'),
('BR', 'Breakfast'),
('DI', 'Dinner'),
)
MAX_RESTAURANT_NAME_LENGTH = 50
MAX_DESCRIPTION_LENGTH = 500
class Restaurant(models.Model):
name = models.Ch... |
Switch phone number to Environment Variable (instead of const) | // Sample Lambda Function to send notifications via text when an AWS Health event happens
var AWS = require('aws-sdk');
var sns = new AWS.SNS();
//main function which gets AWS Health data from Cloudwatch event
exports.handler = (event, context, callback) => {
//get phone number from Env Variable
var phoneNumb... | // Sample Lambda Function to send notifications via text when an AWS Health event happens
var AWS = require('aws-sdk');
var sns = new AWS.SNS();
// define configuration
const phoneNumber =''; // Insert phone number here. For example, a U.S. phone number in E.164 format would appear as +1XXX5550100
//main function wh... |
Remove unique_together on the model; the key length was too long on wide-character MySQL installs. | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app... | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migrat... |
Update "A Plea for Colour Analysis Tools in DCC Applications" blog post div height. | <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<title>A Plea for Colour Analysis Tools in DCC Applications</title>
<?php include ("common_header_attributes.php"); ?>
</head>
<body>
<?php include_once("analytics_tracking.php") ?>
<?php include ("navigat... | <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<title>A Plea for Colour Analysis Tools in DCC Applications</title>
<?php include ("common_header_attributes.php"); ?>
</head>
<body>
<?php include_once("analytics_tracking.php") ?>
<?php include ("navigat... |
Move oparl api from /api/v1/ to /api/oparl/v1 | <?php
/* @var Illuminate\Routing\Router $router */
$router->get('/', ['uses' => 'RootController@index', 'as' => 'api.index']);
$router->group([
'as' => 'api.v1.',
'domain' => 'dev.'.config('app.url'),
'prefix' => 'api/oparl/v1/',
'middleware' => ['track', 'bindings'],
], function () us... | <?php
/* @var Illuminate\Routing\Router $router */
$router->get('/', ['uses' => 'RootController@index', 'as' => 'api.index']);
$router->group([
'as' => 'api.v1.',
'domain' => 'dev.'.config('app.url'),
'prefix' => 'api/v1/',
'middleware' => ['track', 'bindings'],
], function () use ($ro... |
Allow servers command to work without a password. | from BaseController import BaseController
from api.util import settings
class ServerListController(BaseController):
def get(self):
servers = {"servers": self.read_server_config()}
self.write(servers)
def read_server_config(self):
"""Returns a list of servers with the 'id' field added.... | from BaseController import BaseController
from api.util import settings
class ServerListController(BaseController):
def get(self):
servers = {"servers": self.read_server_config()}
self.write(servers)
def read_server_config(self):
"""Returns a list of servers with the 'id' field added.... |
Update exmple for node position in new RGG interface. | import networkx as nx
import matplotlib.pyplot as plt
G=nx.random_geometric_graph(200,0.125)
# position is stored as node attribute data for random_geometric_graph
pos=nx.get_node_attributes(G,'pos')
# find node near center (0.5,0.5)
dmin=1
ncenter=0
for n in pos:
x,y=pos[n]
d=(x-0.5)**2+(y-0.5)**2
if d<d... | import networkx as nx
import matplotlib.pyplot as plt
G=nx.random_geometric_graph(200,0.125)
pos=G.pos # position is stored as member data for random_geometric_graph
# find node near center (0.5,0.5)
dmin=1
ncenter=0
for n in pos:
x,y=pos[n]
d=(x-0.5)**2+(y-0.5)**2
if d<dmin:
ncenter=n
dmi... |
Change ConcreteCard test class params. | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._c... | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._c... |
Change managerarea header app name to tenant name | <header class="main-header">
<!-- Logo -->
<a href="#" class="logo" data-toggle="push-menu" role="button">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><i class="fa fa-home"></i></span>
<!-- logo for regular state and mobile devices -->
<span class="lo... | <header class="main-header">
<!-- Logo -->
<a href="#" class="logo" data-toggle="push-menu" role="button">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><i class="fa fa-home"></i></span>
<!-- logo for regular state and mobile devices -->
<span class="lo... |
Add auto detedt url from model scenario | <?php
/*
* X-editable extension for Yii2
*
* @link https://github.com/hiqdev/yii2-x-editable
* @package yii2-x-editable
* @license BSD-3-Clause
* @copyright Copyright (c) 2015, HiQDev (https://hiqdev.com/)
*/
namespace hiqdev\xeditable\widgets;
use hiqdev\xeditable\traits\XEditableTrait;
use yii\base... | <?php
/*
* X-editable extension for Yii2
*
* @link https://github.com/hiqdev/yii2-x-editable
* @package yii2-x-editable
* @license BSD-3-Clause
* @copyright Copyright (c) 2015, HiQDev (https://hiqdev.com/)
*/
namespace hiqdev\xeditable\widgets;
use hiqdev\xeditable\traits\XEditableTrait;
use yii\base... |
Check for the existence of the resource cache key before attempting to make dirty | import {
SET_RESOURCE,
MARK_DASHBOARD_DIRTY,
RESET_RESOURCE_CACHE
} from './actions';
const markAllDirty = (keys, state) => {
const dirty = {};
keys.forEach((key) => {
if (state[key]) {
dirty[key] = { ...state[key], dirty: true };
}
});
return dirty;
};
const ... | import {
SET_RESOURCE,
MARK_DASHBOARD_DIRTY,
RESET_RESOURCE_CACHE
} from './actions';
const markAllDirty = (keys, state) => {
const dirty = {};
keys.forEach((key) => {
dirty[key] = { ...state[key], dirty: true };
});
return dirty;
};
const resourceReducer = (state = {}, action) =... |
Update typo references in table name var | <?php
/**
* Feed
*
* Class for handle feed operations.
*
* @author Ángel Guzmán Maeso <shakaran@gmail.com>
* @since 0.1
*/
class Feed
{
private static $table_name = 'ttrss_feeds';
public function __construct()
{
}
/**
* Check if the feeds table exist and it is available.
*
* It uses a legacy... | <?php
/**
* Feed
*
* Class for handle feed operations.
*
* @author Ángel Guzmán Maeso <shakaran@gmail.com>
* @since 0.1
*/
class Feed
{
private static $table_name = 'ttrss_feeds';
public function __construct()
{
}
/**
* Check if the feeds table exist and it is available.
*
* It uses a legacy... |
Update build.gradle and fix compilation
Signed-off-by: Steven Downer <e51bce9123e792aec8a98724fb48684dc936521f@outlook.com> | /**
* This file is part of AlmuraSDK, All Rights Reserved.
*
* Copyright (c) 2015 AlmuraDev <http://github.com/AlmuraDev/>
*/
package com.almuradev.almurasdk.permissions;
import java.util.HashSet;
import java.util.Set;
public class PermissibleAllMods implements Permissible {
private Set<Permissible> permissi... | /**
* This file is part of AlmuraSDK, All Rights Reserved.
*
* Copyright (c) 2015 AlmuraDev <http://github.com/AlmuraDev/>
*/
package com.almuradev.almurasdk.permissions;
import java.util.HashSet;
import java.util.Set;
public class PermissibleAllMods implements Permissible {
private Set<Permissible> permissi... |
BUG: Remove call of unimplemented method. | # Enthought library imports.
from traits.api import Instance, on_trait_change
from enaml.components.constraints_widget import ConstraintsWidget
# local imports
from pyface.tasks.editor import Editor
class EnamlEditor(Editor):
""" Create an Editor for Enaml Components.
"""
#### EnamlEditor interface ####... | # Enthought library imports.
from traits.api import Instance, on_trait_change
from enaml.components.constraints_widget import ConstraintsWidget
# local imports
from pyface.tasks.editor import Editor
class EnamlEditor(Editor):
""" Create an Editor for Enaml Components.
"""
#### EnamlEditor interface ####... |
Change port to 8080 to match with clevercloud requirement | require('zone.js/dist/zone-node');
require('reflect-metadata');
const express = require('express');
const fs = require('fs');
const { platformServer, renderModuleFactory } = require('@angular/platform-server');
const { ngExpressEngine } = require('@nguniversal/express-engine');
// Import module map for lazy loading
co... | require('zone.js/dist/zone-node');
require('reflect-metadata');
const express = require('express');
const fs = require('fs');
const { platformServer, renderModuleFactory } = require('@angular/platform-server');
const { ngExpressEngine } = require('@nguniversal/express-engine');
// Import module map for lazy loading
co... |
Mark middleware class as nullsafe
Reviewed By: defHLT
Differential Revision: D24256184
fbshipit-source-id: cf0342d0ed800576ce0cad9a37bcd96d8483ae4a | package com.facebook.fresco.middleware;
import android.graphics.PointF;
import android.graphics.Rect;
import android.net.Uri;
import com.facebook.fresco.ui.common.ControllerListener2.Extras;
import com.facebook.infer.annotation.Nullsafe;
import java.util.Map;
import javax.annotation.Nullable;
@Nullsafe(Nullsafe.Mode.... | package com.facebook.fresco.middleware;
import android.graphics.PointF;
import android.graphics.Rect;
import android.net.Uri;
import com.facebook.fresco.ui.common.ControllerListener2.Extras;
import java.util.Map;
import javax.annotation.Nullable;
public class MiddlewareUtils {
public static Extras obtainExtras(
... |
Use bedrock instead of polished andesite | const Vec3 = require('vec3').Vec3
const rand = require('random-seed')
function generation ({ version, seed, level = 50 } = {}) {
const Chunk = require('prismarine-chunk')(version)
const mcData = require('minecraft-data')(version)
function generateChunk (chunkX, chunkZ) {
const seedRand = rand.create(seed + ... | const Vec3 = require('vec3').Vec3
const rand = require('random-seed')
function generation ({ version, seed, level = 50 } = {}) {
const Chunk = require('prismarine-chunk')(version)
const mcData = require('minecraft-data')(version)
function generateChunk (chunkX, chunkZ) {
const seedRand = rand.create(seed + ... |
Update comments on the built-in file types | import build_inputs
from path import Path
class SourceFile(build_inputs.File):
def __init__(self, name, source=Path.srcdir, lang=None):
build_inputs.File.__init__(self, name, source=source)
self.lang = lang
class HeaderFile(build_inputs.File):
install_kind = 'data'
install_root = Path.incl... | import build_inputs
from path import Path
class SourceFile(build_inputs.File):
def __init__(self, name, source=Path.srcdir, lang=None):
build_inputs.File.__init__(self, name, source=source)
self.lang = lang
class HeaderFile(build_inputs.File):
install_kind = 'data'
install_root = Path.incl... |
Use suggestedType instead of value.getClass() | package com.github.ferstl.depgraph.graph.style;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
import com.fasterxml.jackson.databind.t... | package com.github.ferstl.depgraph.graph.style;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
import com.fasterxml.jackson.databind.t... |
Remove incorrect remark about Postgres 9.5 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0005_instance_xml_hash'),
]
# Because some servers already have these modifications applied by Django South migration,
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0005_instance_xml_hash'),
]
# This custom migration must be run on Postgres 9.5+.
# Because some servers already have ... |
Clone repository to playbooks directory | from django.db import models
from django.conf import settings
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = os.path.j... | from django.db import models
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = self.repository
REMOTE_URL = "http... |
Set the coutdown min and sec values to 00 when the deadline time has been reached. | $(document).ready(function(){
$('.log-btn').click(function(){
$('.log-status').addClass('wrong-entry');
$('.alert').fadeIn(500);
setTimeout( "$('.alert').fadeOut(1500);",3000 );
});
$('.form-control').keypress(function(){
$('.log-status').removeClass('wrong-entry');
});
});
function get... | $(document).ready(function(){
$('.log-btn').click(function(){
$('.log-status').addClass('wrong-entry');
$('.alert').fadeIn(500);
setTimeout( "$('.alert').fadeOut(1500);",3000 );
});
$('.form-control').keypress(function(){
$('.log-status').removeClass('wrong-entry');
});
});
function get... |
Fix spelling of my name | # 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... | # 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... |
Add log for force option in buildAddons task | var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var addonsManager = require('../core/cb.addons/manager');
module.exports = function(grunt) {
grunt.registerMultiTask('buildAddons', 'Build default add-ons', function() {
var done = this.async();
_.defaults(this.da... | var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var addonsManager = require('../core/cb.addons/manager');
module.exports = function(grunt) {
grunt.registerMultiTask('buildAddons', 'Build default add-ons', function() {
var done = this.async();
_.defaults(this.da... |
Use analytics name for subreddits if available.
This allows a catch-all for multis to be used. | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
adzerk_srs = g.live_config.get("adzerk_srs")
in_adzerk_sr = a... | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
adzerk_srs = g.live_config.get("adzerk_srs")
in_adzerk_sr = a... |
Make it more robust - don't error if setting is not present. | var config = require('../../util/config').config;
/**
* Return true if key starts with a prefixed defined in prefixes.
*
* @param {String} key Key name.
* @param {Array} prefixes Prefixes.
* @return {Boolean} true if the key starts with a prefix, false otherwise.
*/
function startsWithPrefix(key, prefixes) {
... | var config = require('../../util/config').config;
/**
* Return true if key starts with a prefixed defined in prefixes.
*
* @param {String} key Key name.
* @param {Array} prefixes Prefixes.
* @return {Boolean} true if the key starts with a prefix, false otherwise.
*/
function startsWithPrefix(key, prefixes) {
... |
Handle the case where the bucket already exists | from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket... | from boto.s3.connection import S3Connection
from boto.exception import S3ResponseError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket.endswith('-'):
bucket = bucket[:-1]
t... |
Fix typo in setting up dropbox api | import dropboxFs from 'dropbox-fs'
import fs from 'fs'
import { promisify } from 'util'
import { dropboxApiKey } from '../config'
export const readFile = (...options) => {
return dropboxApiKey ? dropboxReadFile(...options) : fsReadFile(...options)
}
export const writeFile = (...options) => {
return dropboxApiKey... | import dropboxFs from 'dropbox-fs'
import fs from 'fs'
import { promisify } from 'util'
import { dropboxApiKey } from '../config'
export const readFile = (...options) => {
return dropboxApiKey ? dropboxReadFile(...options) : fsReadFile(...options)
}
export const writeFile = (...options) => {
return dropboxApiKey... |
Add required "navigation" module dependency (for ClientIdentifier). | /*
* Copyright (C) 2015 Glyptodon LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publi... | /*
* Copyright (C) 2015 Glyptodon LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publi... |
Add stress test for wrapping stdout | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHE... | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test(... |
Remove unnecessary redirect in NotesController. | (function() {
angular.module('notely.notes', [
'ui.router'
])
.controller('NotesController', NotesController)
.config(notesConfig);
notesConfig['$inject'] = ['$stateProvider'];
function notesConfig($stateProvider) {
$stateProvider
.state('notes', {
url: '/notes',
abstract: tr... | (function() {
angular.module('notely.notes', [
'ui.router'
])
.controller('NotesController', NotesController)
.config(notesConfig);
notesConfig['$inject'] = ['$stateProvider'];
function notesConfig($stateProvider) {
$stateProvider
.state('notes', {
url: '/notes',
abstract: tr... |
Check if hierarchySeparator presents in the options object | import addons from '@storybook/addons';
import { EVENT_ID } from '../shared';
// init function will be executed once when the storybook loads for the
// first time. This is a good place to add global listeners on channel.
export function init() {
// NOTE nothing to do here
}
function regExpStringify(exp) {
if (ty... | import addons from '@storybook/addons';
import { EVENT_ID } from '../shared';
// init function will be executed once when the storybook loads for the
// first time. This is a good place to add global listeners on channel.
export function init() {
// NOTE nothing to do here
}
function regExpStringify(exp) {
if (ty... |
Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocke... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... |
Fix flake8 issue and fix up documentation | #! /usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 the HERA Collaboration
# Licensed under the 2-clause BSD license.
import numpy as np
from astropy.time import Time
from pyuvdata import UVData
from hera_mc import mc
a = mc.get_mc_argument_parser()
a.description = """Read the obsid from a... | #! /usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 the HERA Collaboration
# Licensed under the 2-clause BSD license.
import os
import numpy as np
from astropy.time import Time
from pyuvdata import UVData
from hera_mc import mc
a = mc.get_mc_argument_parser()
a.description = """Read the ob... |
Revert change 00342e052b17 to fix sshlibrary on standalone jar.
Update issue 1311
Status: Done
Revert change 00342e052b17 to fix sshlibrary on standalone jar. | /* Copyright 2008-2012 Nokia Siemens Networks Oyj
*
* 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 l... | /* Copyright 2008-2012 Nokia Siemens Networks Oyj
*
* 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 l... |
Allow the live test wait to be skipped | <?php
require __DIR__ . "/../vendor/autoload.php";
if (in_array("--live-tests", $_SERVER["argv"])) {
echo "\nWARNING: These tests will make changes to the Sonos devices on the network:\n";
$warnings = [
"Queue contents will be changed",
"Music will play",
"Volume will be changed",
... | <?php
require __DIR__ . "/../vendor/autoload.php";
if (in_array("--live-tests", $_SERVER["argv"])) {
echo "\nWARNING: These tests will make changes to the Sonos devices on the network:\n";
$warnings = [
"Queue contents will be changed",
"Music will play",
"Volume will be changed",
... |
Fix for intel routing changes | // ==UserScript==
// @id iitc-plugin-drawtools-sync@hansolo669
// @name IITC plugin: drawtools sync
// @category Tweaks
// @version 0.1.1
// @namespace https://github.com/hansolo669/iitc-tweaks
// @updateURL https://iitc.reallyawesomedomain.com/drawtools-sync.meta.js
// @dow... | // ==UserScript==
// @id iitc-plugin-drawtools-sync@hansolo669
// @name IITC plugin: drawtools sync
// @category Tweaks
// @version 0.1.0
// @namespace https://github.com/hansolo669/iitc-tweaks
// @updateURL https://iitc.reallyawesomedomain.com/drawtools-sync.meta.js
// @dow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.