text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Fix admin page permitted user logic | <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/... | <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/... |
Replace double quotes with single quotes | /*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.model.course.SectionTermData', {
extend: 'Ext.data.Model',
requires: [
'SlateAdmin.proxy.Records',
'Ext.data.identifier.Negative'
],
// model config
idProperty: 'ID',
identifier: 'negative',
fields... | /*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.model.course.SectionTermData', {
extend: 'Ext.data.Model',
requires: [
'SlateAdmin.proxy.Records',
'Ext.data.identifier.Negative'
],
// model config
idProperty: 'ID',
identifier: 'negative',
fields... |
Use anchorscroll to hopefully make sure modals appear within view on mobile. | /**
* Copyright 2015 Ian Davies
*
* 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... | /**
* Copyright 2015 Ian Davies
*
* 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... |
chore(ipc): Add extra debug and read DoForcePingTimeout in the
constructor
Signed-off-by: Francisco Miguel Biete <f1d806242fc0bb697f053bcdfc66a36bc885611e@gmail.com>
<fbiete@gmail.com> | <?php
class PingTrackingRedis extends InterProcessRedis {
const TTL = 3600;
private $key;
public function __construct() {
parent::__construct();
$this->key = "ZP-PING|" . Request::GetDeviceID() . '|' . Request::GetAuthUser() . '|' . Request::GetAuthDomain();
$this->DoForcePingTimeout();
... | <?php
class PingTrackingRedis extends InterProcessRedis {
const TTL = 3600;
private $key;
public function __construct() {
parent::__construct();
$this->key = "ZP-PING|" . Request::GetDeviceID() . '|' . Request::GetAuthUser() . '|' . Request::GetAuthDomain();
}
/**
* Checks if... |
Replace array access to slims's container with a call to 'get'. | <?php
/**
* PHP version 7.0
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace Ewallet\Slim\Providers;
use Pimple\{Container, ServiceProviderInterface};
use Slim\App;
use Slim\Http\{Request, Response};
class EwalletControllerProvider implements Servi... | <?php
/**
* PHP version 7.0
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace Ewallet\Slim\Providers;
use Pimple\{Container, ServiceProviderInterface};
use Slim\App;
use Slim\Http\{Request, Response};
class EwalletControllerProvider implements Servi... |
Set default state property values to `null` | /* eslint-disable */
// export default function detailReducer(state = {}, action) {
/* istanbul ignore next */
window.reducers = window.reducers || {};
window.reducers.detailReducer = (state = {}, action) => {
switch (action.type) {
case 'FETCH_DETAIL':
return {
...state,
dataSelection: null... | /* eslint-disable */
// export default function detailReducer(state = {}, action) {
/* istanbul ignore next */
window.reducers = window.reducers || {};
window.reducers.detailReducer = (state = {}, action) => {
switch (action.type) {
case 'FETCH_DETAIL':
return {
...state,
dataSelection: null... |
Remove self.debug as LoggerMixin was removed from new versions of rapidsms. | import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwarg... | import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwarg... |
Add setDateTime(DateTime) and setPriority(Priority) methods | package tars.testutil;
import tars.model.task.*;
import tars.model.tag.UniqueTagList;
/**
* A mutable task object. For testing only.
*/
public class TestTask implements ReadOnlyTask {
private Name name;
private UniqueTagList tags;
private DateTime dateTime;
private Status status;
private Priori... | package tars.testutil;
import tars.model.task.*;
import tars.model.tag.UniqueTagList;
/**
* A mutable task object. For testing only.
*/
public class TestTask implements ReadOnlyTask {
private Name name;
private UniqueTagList tags;
private DateTime dateTime;
private Status status;
private Priori... |
Remove dependency on unicodecsv module | # I started here: https://www.django-rest-framework.org/api-guide/renderers/#example
import csv
import io
import logging
from rest_framework import renderers
logger = logging.getLogger(__name__)
class SimpleCSVRenderer(renderers.BaseRenderer):
"""Renders simple 1-level-deep data as csv"""
media_type = "te... | # I started here: https://www.django-rest-framework.org/api-guide/renderers/#example
from rest_framework import renderers
import unicodecsv as csv
import io
import logging
logger = logging.getLogger(__name__)
class SimpleCSVRenderer(renderers.BaseRenderer):
"""Renders simple 1-level-deep data as csv"""
med... |
Change timeout type, increase to 2s | <?php
namespace App;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;
class Node extends Model
{
function online()
{
try {
$client = new Client(['exceptions' => false]);
$res = $client->request('GET', $this->url.'/ping',
['timeo... | <?php
namespace App;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;
class Node extends Model
{
function online()
{
try {
$client = new Client(['exceptions' => false]);
$res = $client->request('GET', $this->url.'/ping',
['conne... |
Update onEvents schema to allow array of signal/scale listeners. | export default {
"defs": {
"listener": {
"oneOf": [
{"$ref": "#/refs/signal"},
{
"type": "object",
"properties": {
"scale": {"type": "string"}
},
"required": ["scale"]
},
{"$ref": "#/defs/stream"}
]
},
"onEven... | export default {
"defs": {
"onEvents": {
"type": "array",
"items": {
"allOf": [
{
"type": "object",
"properties": {
"events": {
"oneOf": [
{"$ref": "#/refs/selector"},
{"$ref": "#/refs/signal"},... |
Fix checking of limit parameter | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
try:
intParam = int(param)
except ValueError:
return [False, param]
if str(intParam) != param:
return [False, param]
... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
intParam = int(param)
if str(intParam) != param:
return [False, param]
return [(intParam >= 0), param]
def checkPermission(self, user,... |
Rename „lint“ mode to „validate“ | const minimist = require('minimist');
// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
boolean: ["dev", "debug", "d", "v", "validate", "help", "version"],
string: ["init"],
});
const cwd = process.cwd();
module.exports = {
runnerPath: `${cwd}/kabafile.js`,
modulePath: `${cwd}/... | const minimist = require('minimist');
// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
boolean: ["dev", "debug", "d", "v", "lint", "help", "version"],
string: ["init"],
});
const cwd = process.cwd();
module.exports = {
runnerPath: `${cwd}/kabafile.js`,
modulePath: `${cwd}/node... |
Use style loader instead of raw loader for css and get rid of html-raw loader | const path = require('path');
var webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: {
'main': './main.ts'
},
module: {
loaders: [
{test: /\.ts$/, exclude: /node_modules/, loader: 'ts-loade... | const path = require('path');
var webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: {
'main': './main.ts'
},
module: {
loaders: [
{test: /\.css$/, loader: 'raw-loader'},
{test:... |
Fix typo in dependency-injected property name. | <?php
namespace Northstar\Http\Controllers;
use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;
class AvatarController extends Controller
{
/**
* Amazon Web Services API wrapper.
* @var AWS
*/
protected $aws;
public function __construct(AWS $aws)
{
... | <?php
namespace Northstar\Http\Controllers;
use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;
class AvatarController extends Controller
{
/**
* Amazon Web Services API wrapper.
* @var AWS
*/
protected $phoenix;
public function __construct(AWS $aws)
{
... |
Add now navigates to Lists page | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNewList } from '../actions';
class ListEdit extends Component {
constructor(props) {
super(props);
this.state = {listName: ''};
}
saveClickHandler(e) {... | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNewList } from '../actions';
class ListEdit extends Component {
constructor(props) {
super(props);
this.state = {listName: ''};
}
saveClickHandler(e) {... |
Return user after oauth login | <?php
namespace Facilis\Users\OAuth2;
use League\OAuth2\Client\Exception\IDPException;
use League\OAuth2\Client\Provider\ProviderInterface;
use Nette\Object;
class LoginService extends Object
{
/**
* @var IStateStorage
*/
private $stateStorage;
function __construct(IStateStorage $stateStora... | <?php
namespace Facilis\Users\OAuth2;
use League\OAuth2\Client\Exception\IDPException;
use League\OAuth2\Client\Provider\ProviderInterface;
use Nette\Object;
class LoginService extends Object
{
/**
* @var IStateStorage
*/
private $stateStorage;
function __construct(IStateStorage $stateStora... |
Upgrade nose to 1.3.1 for Travis | #!/usr/bin/env python2
import os
from setuptools import setup, find_packages
from plugins import __version__
repo_directory = os.path.dirname(__file__)
try:
long_description = open(os.path.join(repo_directory, 'README.rst')).read()
except:
long_description = None
setup(
name='gds-nagios-plugins',
ve... | #!/usr/bin/env python2
import os
from setuptools import setup, find_packages
from plugins import __version__
repo_directory = os.path.dirname(__file__)
try:
long_description = open(os.path.join(repo_directory, 'README.rst')).read()
except:
long_description = None
setup(
name='gds-nagios-plugins',
ve... |
Fix "bin/cm migration add" again | <?php
class CM_Migration_Manager implements CM_Service_ManagerAwareInterface {
use CM_Service_ManagerAwareTrait;
/** @var string[] */
private $_modules;
/**
* @param CM_Service_Manager $serviceManager
* @param string[] $modules
*/
public function __construct(CM_Service_M... | <?php
class CM_Migration_Manager implements CM_Service_ManagerAwareInterface {
use CM_Service_ManagerAwareTrait;
/** @var string[] */
private $_modules;
/**
* @param CM_Service_Manager $serviceManager
* @param string[] $modules
*/
public function __construct(CM_Service_M... |
Allow PHP response to send MultipleHeaders safely
- Detect MultipleHeaderDescription
- when found, pass boolean false as second argument to header() | <?php
namespace Zend\Http\PhpEnvironment;
use Zend\Http\Header\MultipleHeaderDescription,
Zend\Http\Response as HttpResponse,
Zend\Stdlib\Parameters;
class Response extends HttpResponse
{
protected $headersSent = false;
protected $contentSent = false;
public function __construct()
{
}
... | <?php
namespace Zend\Http\PhpEnvironment;
use Zend\Http\Response as HttpResponse,
Zend\Stdlib\Parameters;
class Response extends HttpResponse
{
protected $headersSent = false;
protected $contentSent = false;
public function __construct()
{
}
public function headersSent()
{
... |
Fix the gift certificate module so that an invalid code won't throw an exception. | """
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
... | """
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
... |
Add guard for orphaned references | <?php
namespace TeiEditionBundle\Entity;
/**
*
*
*/
trait ArticleReferencesTrait
{
/* Currently simple sort by article title */
protected function sortArticleReferences($articleReferences)
{
usort($articleReferences, function ($a, $b) {
return strcmp(mb_strtolower($a->getArticle()->... | <?php
namespace TeiEditionBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
*
*/
trait ArticleReferencesTrait
{
/* Currently simple sort by article title */
protected function sortArticleReferences($articleReferences)
{
usort($articleReferences, function ($a, $b) {
return strcm... |
Call parent with last set to True
This way we get __parent__.site set to a valid site, or it raises an
error.
We may want to change this in the future... | import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'e... | import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'e... |
Adjust --dump-config color theme for better readability
Add jinja highlighting to --dump-config | from argparse import SUPPRESS
import yaml
from loguru import logger
from rich.syntax import Syntax
from flexget import options, plugin
from flexget.event import event
from flexget.terminal import console
logger = logger.bind(name='dump_config')
class OutputDumpConfig:
"""
Dumps task config in STDOUT in yam... | from argparse import SUPPRESS
from loguru import logger
from rich.syntax import Syntax
from flexget import options, plugin
from flexget.event import event
from flexget.terminal import console
logger = logger.bind(name='dump_config')
class OutputDumpConfig:
"""
Dumps task config in STDOUT in yaml at exit or... |
Fix typo in DataStore test | 'use strict';
var test = require('tape');
var DataStore = require('../../lib/data-store/data-store');
test('----- DataStore', function(t) {
t.plan(3);
t.test('Registers/Retrieves modules', function(st){
st.plan(1);
var name = 'test:module';
var tag = 'HEAD';
var definition = {... | 'use strict';
var test = require('tape');
var DataStore = require('../../lib/data-store/data-store');
test('----- DataStore', function(t) {
t.plan(3);
t.test('Saves/Retrieves modules', function(st){
st.plan(1);
var name = 'test:module';
var tag = 'HEAD';
var definition = {a: 1... |
Fix a bug when the list name was not visible | import _ from 'lodash'
import {
COMPANY_LISTS__LISTS_LOADED,
COMPANY_LISTS__SELECT,
COMPANY_LISTS__COMPANIES_LOADED,
COMPANY_LISTS__FILTER,
COMPANY_LISTS__ORDER,
} from '../../actions'
import { RECENT } from './Filters'
const initialState = {
orderBy: RECENT,
}
export default (
state = initialState,
... | import _ from 'lodash'
import {
COMPANY_LISTS__LISTS_LOADED,
COMPANY_LISTS__SELECT,
COMPANY_LISTS__COMPANIES_LOADED,
COMPANY_LISTS__FILTER,
COMPANY_LISTS__ORDER,
} from '../../actions'
import { RECENT } from './Filters'
const initialState = {
orderBy: RECENT,
}
export default (
state = initialState,
... |
Convert to base 64 using standard library | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.handler;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Base64;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
i... | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.handler;
import org.json.JSONException;
import org.json.JSONObject;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.IOException;
import java.n... |
Clean up input tables class and instance declarations | from utils import write_csv_rows, read_csv_rows
class input_table:
def __init__(self, filename, name, headers, content=[]):
self.filename = filename
self.name = name
self.headers = headers
self.content = content
connect_filename = 'connectivity.csv'
connect_name = ['Connectivity Ta... | from utils import write_csv_rows, read_csv_rows
class input_table:
def __init__(self, filename, content):
self.filename = filename
self.content = content
connect_tbl=input_table('connectivity.csv',
[['Connectivity Table'],
['x1','y1','x2','y2','E','... |
feature: Allow use of snap-opt-* attrs for opts | angular.module('snap')
.directive('snapContent', ['SnapConstructor', 'snapRemote', function (SnapConstructor, snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = angular.extend({}... | angular.module('snap')
.directive('snapContent', ['SnapConstructor', 'snapRemote', function (SnapConstructor, snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = {
eleme... |
Add current pot and cards to client table representation | //J-
package com.whippy.poker.common.beans;
import java.util.List;
public class ClientTable {
private ClientSeat[] seats;
private int id;
private TableState state;
private int dealerPosition;
private int currentPot;
private List<Card> currentCards;
public Clie... | //J-
package com.whippy.poker.common.beans;
public class ClientTable {
private ClientSeat[] seats;
private int id;
private TableState state;
private int dealerPosition;
private int currentPot;
public ClientTable(ClientSeat[] seats, int id, TableState state, int dealer... |
Fix query for chat messages | /* @flow */
import React, { Component, PropTypes } from 'react';
import Connect from '../../../modules/store/Connect';
import ChatMessages from '../views/ChatMessages';
import type { SubscriptionRange } from '../../../modules/store/ConnectTypes';
export default class ChatMessagesContainer extends Component<void, any,... | /* @flow */
import React, { Component, PropTypes } from 'react';
import Connect from '../../../modules/store/Connect';
import ChatMessages from '../views/ChatMessages';
import type { SubscriptionRange } from '../../../modules/store/ConnectTypes';
export default class ChatMessagesContainer extends Component<void, any,... |
[Core] Implement twig function for variants prices map | <?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\Core\Provider;
use Sylius\Component\Core\Model\ProductInterface;
use Syliu... | <?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\Core\Provider;
use Sylius\Component\Core\Model\ProductInterface;
use Syliu... |
Remove php 5.4 array tags | <?php
namespace Payum\Core\Tests\Mocks\Model;
use Payum\Core\Exception\LogicException;
class Propel2ModelQuery
{
const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";
protected $filters = array();
protected $modelReflection;
public function __construct()
{
$this->modelRe... | <?php
namespace Payum\Core\Tests\Mocks\Model;
use Payum\Core\Exception\LogicException;
class Propel2ModelQuery
{
const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";
protected $filters = array();
protected $modelReflection;
public function __construct()
{
$this->modelRe... |
Fix return code when running unittests. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test runner for sqlparse."""
import optparse
import os
import sys
import unittest
test_mod = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
if test_mod not in sys.path:
sys.path.insert(1, test_mod)
parser = optparse.OptionParser()
parser.add_opt... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test runner for sqlparse."""
import optparse
import os
import sys
import unittest
test_mod = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
if test_mod not in sys.path:
sys.path.insert(1, test_mod)
parser = optparse.OptionParser()
parser.add_opt... |
Change display of returned time | var Reader = (function () {
/*
* Gets an DOM element and anaylzes it's textual reading content.
* Returns the estimated time to read in seconds.
*/
function calculateTimeToRead(element) {
var content = jQuery(element).text(),
sentences = content.split('. '),
i... | var Reader = (function () {
/*
* Gets an DOM element and anaylzes it's textual reading content.
* Returns the estimated time to read in seconds.
*/
function calculateTimeToRead(element) {
var content = jQuery(element).text(),
sentences = content.split('. '),
i... |
Add utf decode for reading data | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import threading
import websocket
from polyaxon_client.logger import logger
from polyaxon_client.workers.socket_worker import SocketWorker
class SocketTransportMixin(object):
"""Socket operations transport."""
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import websocket
from polyaxon_client.logger import logger
class SocketTransportMixin(object):
"""Socket operations transport."""
def socket(self, url, message_handler, headers=None):
webs = websocke... |
Change "Unread messages." to "Jump to first unread message."
Also get rid of the "up" arrow so as not to indiciate direction. This is important because in future the RM will not be based on what has been paginated into the client (but instead RM will be handled server-side) and thus we cannot assert any kind of direct... | /*
Copyright 2016 OpenMarket Ltd
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
... | /*
Copyright 2016 OpenMarket Ltd
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
... |
Extend mocking to run validation | from django.conf import settings
from mock import Mock, patch
from unittest2 import TestCase
settings.configure()
# Need to import this after configure()
from django.db.models import ForeignKey
class TestPreference(object):
_meta = Mock(fields=[ForeignKey('user', name='user')])
objects = Mock()
def __... | from django.conf import settings
from mock import Mock, patch
from unittest2 import TestCase
settings.configure()
# Need to import this after configure()
from django.db.models import ForeignKey
class TestPreference(object):
_meta = Mock(fields=[ForeignKey('user', name='user')])
objects = Mock()
def __... |
Use secure url for cloudinary | var path = require('path'),
config;
config = {
production: {
url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/',
mail: {},
database: {
client: 'postgres',
connection: process.env.DATABASE_URL,
pool: { min: 0, max: 5 }
},
serve... | var path = require('path'),
config;
config = {
production: {
url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/',
mail: {},
database: {
client: 'postgres',
connection: process.env.DATABASE_URL,
pool: { min: 0, max: 5 }
},
serve... |
Fix plural form of todo when there are no todos | import React from 'react';
import TodoItem from './TodoItem';
export default class extends React.Component {
render() {
return (
<div>
<button onClick={this.props.onAddTodo}>Add Todo</button>
<ul>
<For each="item" of={this.props.todos}>
<TodoItem
key={ite... | import React from 'react';
import TodoItem from './TodoItem';
export default class extends React.Component {
render() {
return (
<div>
<button onClick={this.props.onAddTodo}>Add Todo</button>
<ul>
<For each="item" of={this.props.todos}>
<TodoItem
key={ite... |
Handle None axis_labels in ToBytes. | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['flo... | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['flo... |
Fix OpenFlow packets getting stuffed with \0 bytes. | package eu.netide.lib.netip;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Class representing a message of type OPENFLOW.
* Note that this only serves as a convenience class - if the MessageType is manipulat... | package eu.netide.lib.netip;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Class representing a message of type OPENFLOW.
* Note that this only serves as a convenience class - if the MessageType is manipulat... |
Update phpdoc constructor parameter can't be null | <?php
namespace SumoCoders\FrameworkMultiUserBundle\Security;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordResetTokenException;
use SumoCoders\FrameworkMultiUserBundle\User\UserInterface;
class PasswordResetToken
{
/**
* @var string
*/
private $token;
/**
* PasswordRes... | <?php
namespace SumoCoders\FrameworkMultiUserBundle\Security;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordResetTokenException;
use SumoCoders\FrameworkMultiUserBundle\User\UserInterface;
class PasswordResetToken
{
/**
* @var string
*/
private $token;
/**
* PasswordRes... |
Add some detail text to assertion. | import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version, "A valid version string is required"
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epil... | import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog)
self.parser.add_argument(
... |
Add error callback to geoloc | class HomeCtrl {
constructor(AppConstants, NetworkRequests, $localStorage, $timeout) {
'ngInject';
this._NetworkRequests = NetworkRequests;
this._storage = $localStorage;
this.appName = AppConstants.appName;
// Detect recommended browsers
let isChrome = /Chrome/.te... | class HomeCtrl {
constructor(AppConstants, NetworkRequests, $localStorage) {
'ngInject';
this._NetworkRequests = NetworkRequests;
this._storage = $localStorage;
this.appName = AppConstants.appName;
// Detect recommended browsers
let isChrome = /Chrome/.test(navigat... |
Remove specific SASS cache directory | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
options: {
style: 'expanded',
sourcemap: 'auto'
},
files: {
'assets/css/boostrap.css': 'assets/sass/boostrap.... | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
options: {
style: 'expanded',
sourcemap: 'auto',
cacheLocation: 'sass/.sass-cache'
},
files: {
'ass... |
Handle error responses as well
Does require including $q to do the promise rejection. | (function() {
'use strict';
var handle_phpdebugbar_response = function(response) {
if (phpdebugbar && phpdebugbar.ajaxHandler) {
// We have a debugbar and an ajaxHandler
// Dig through response to look for the
// debugbar id.
var headers = response && res... | (function() {
'use strict';
var getDebugBarID = function(response) {
var headers = response && response.headers && response.headers();
if (!headers) {
// Something terrible happened. Bail.
return;
}
// Not very elegant, but this is how the debugbar.js defi... |
Disable REST Upload by default | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healt... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healt... |
Use \Page instead of Concrete\Core\Page\Page
Former-commit-id: 5f27527c65b9ed3815ca1a37eef8d3e6dccee225
Former-commit-id: 5b239b1afa020bcaebcb90fa58cc461a91098c82 | <?php
namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty;
use Core;
use UserInfo;
use Page;
class UserCorePageProperty extends CorePageProperty
{
public function __construct()
{
$this->setCorePagePropertyHandle('user');
$this->setPageTypeComposerControlName(tc('PageTypeCompos... | <?php
namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty;
use Core;
use UserInfo;
use Concrete\Core\Page\Page;
class UserCorePageProperty extends CorePageProperty
{
public function __construct()
{
$this->setCorePagePropertyHandle('user');
$this->setPageTypeComposerControlName... |
Move DB Str import to single line so it can be completely cleaned up on site generation | <?php
return [
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of co... | <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
... |
Save buffered image as bmp | // Get JAFFE database from http://www.kasrl.org/jaffe_info.html
// Extract pics in folder named "jaffe"
// package image_test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
... | // Get JAFFE database from http://www.kasrl.org/jaffe_info.html
// Extract pics in folder named "jaffe"
// package image_test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
... |
Replace thriftpy dependency with thriftpy2 | """setup.py - build script for parquet-python."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='parquet',
version='1.2',
description='Python support for Parquet file format',
author='Joe Crobak',
author_email='joecrow@gmail.com',
ur... | """setup.py - build script for parquet-python."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='parquet',
version='1.2',
description='Python support for Parquet file format',
author='Joe Crobak',
author_email='joecrow@gmail.com',
ur... |
Add DRF as a dev dependency | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU... | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU... |
Correct path in South triple definition. | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
... | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
... |
Make the envelope stripping in wrap smarter | <?php namespace Purplapp\Adn;
use stdClass;
use GuzzleHttp\Message\Response;
trait DataContainerTrait
{
private $data = [];
private $dataEnvelope = [];
public static function wrap($data)
{
if ($data instanceof stdClass) {
return static::wrapObject($data);
} elseif ($data ... | <?php namespace Purplapp\Adn;
use stdClass;
use GuzzleHttp\Message\Response;
trait DataContainerTrait
{
private $data = [];
private $dataEnvelope = [];
public static function wrap($data)
{
if ($data instanceof stdClass) {
return static::wrapObject($data);
} elseif ($data ... |
Allow null dates to be formatted... | <?php
namespace Code16\Sharp\Form\Fields\Formatters;
use Carbon\Carbon;
use Code16\Sharp\Form\Fields\SharpFormDateField;
use Code16\Sharp\Form\Fields\SharpFormField;
class DateFormatter extends SharpFieldFormatter
{
/**
* @param SharpFormField $field
* @param $value
* @return mixed
*/
fu... | <?php
namespace Code16\Sharp\Form\Fields\Formatters;
use Carbon\Carbon;
use Code16\Sharp\Form\Fields\SharpFormDateField;
use Code16\Sharp\Form\Fields\SharpFormField;
class DateFormatter extends SharpFieldFormatter
{
/**
* @param SharpFormField $field
* @param $value
* @return mixed
*/
fu... |
Allow override on toolbar items through attribute
Use can add "toolbar" attribute in directive to override toolbar items.
e.g.
<div simditor name="content" ng-model="content" toolbar="['title', 'bold', 'italic', 'underline', 'strikethrough', '|', 'ol', 'ul', 'blockquote', 'table']" form-required="true"></div> | /*global window,location*/
(function (window) {
'use strict';
var Simditor = window.Simditor;
var directives = angular.module('simditor',[]);
directives.directive('simditor', function () {
var TOOLBAR_DEFAULT = ['title', 'bold', 'italic', 'underline', 'strikethrough', '|', 'ol', 'ul', 'blockquote', '... | /*global window,location*/
(function (window) {
'use strict';
var Simditor = window.Simditor;
var directives = angular.module('simditor',[]);
directives.directive('simditor', function () {
return {
require: "?^ngModel",
link: function (scope, element, attrs, ngModel) {
element.append("... |
Complete a sentence in a comment | import angr
from .shellcode_manager import ShellcodeManager
from rex.exploit import CannotExploit
import logging
l = logging.getLogger("rex.exploit.Exploit")
class Exploit(object):
'''
Exploit object which can leak flags or set registers
'''
def __init__(self, crash):
'''
:param crash... | import angr
from .shellcode_manager import ShellcodeManager
from rex.exploit import CannotExploit
import logging
l = logging.getLogger("rex.exploit.Exploit")
class Exploit(object):
'''
Exploit object which can leak flags or set registers
'''
def __init__(self, crash):
'''
:param crash... |
Add splix to spam watcher | import BaseWatcher from './BaseWatcher';
/**
* This checks for people spamming links.
*/
class LinkSpamWatcher extends BaseWatcher {
constructor(bot) {
super(bot);
}
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string}
*/
method ... | import BaseWatcher from './BaseWatcher';
/**
* This checks for people spamming links.
*/
class LinkSpamWatcher extends BaseWatcher {
constructor(bot) {
super(bot);
}
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string}
*/
method ... |
Fix globals case in UMD | /*globals define */
'use strict';
var root = this; // jshint ignore:line
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['es6-promise'], function (es6Promise) {
return (root.httppleasepromises = factory(es6Promise.Promise));
});
} else if (typeof exp... | /*globals define */
'use strict';
var root = this; // jshint ignore:line
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['es6-promise'], function (es6Promise) {
return (root.httppleasepromises = factory(es6Promise));
});
} else if (typeof exports ===... |
Use manual route definition over the route resource shortcut | <?php
use Illuminate\Routing\Router;
$router->model('menus', 'Modules\Menu\Entities\Menu');
$router->model('menuitem', 'Modules\Menu\Entities\Menuitem');
$router->group(['prefix' => '/menu'], function () {
get('menus', ['as' => 'admin.menu.menu.index', 'uses' => 'MenuController@index']);
get('menus/create', ... | <?php
use Illuminate\Routing\Router;
$router->model('menus', 'Modules\Menu\Entities\Menu');
$router->model('menuitem', 'Modules\Menu\Entities\Menuitem');
$router->group(['prefix' => '/menu'], function (Router $router) {
$router->resource('menus', 'MenuController', [
'except' => ['show'],
'names' ... |
Migrate API call to use fetch | const fetch = require('isomorphic-unfetch');
const streamify = require('into-stream');
module.exports = async options => {
if (!options.key) {
throw new Error('Error: key needed to use FEC API,' +
'specify using options.key, ' +
'or get one at https://api.data.gov/signup/');
}
... | const axios = require('axios');
const through2 = require('through2');
const JSONStream = require('JSONStream');
function processRow(filing, enc, next) {
if (filing.fec_file_id) {
filing.fec_file_id = parseInt(
filing.fec_file_id
.replace('FEC-', '')
.replace('SEN... |
Allow passing engine arguments to connect(). | import pkg_resources
from sqlalchemy import MetaData, Table, create_engine, orm
from .tables import metadata
def connect(uri=None, session_args={}, engine_args={}):
"""Connects to the requested URI. Returns a session object.
With the URI omitted, attempts to connect to a default SQLite database
contain... | import pkg_resources
from sqlalchemy import MetaData, Table, create_engine, orm
from .tables import metadata
def connect(uri=None, **kwargs):
"""Connects to the requested URI. Returns a session object.
With the URI omitted, attempts to connect to a default SQLite database
contained within the package d... |
Check for the binary option being passed to the md5 hasher. If so, always use default encoding. | var crypto = require('crypto')
, fs = require('fs');
(function(undefined) {
'use strict';
module.exports = {
sha256: function(key, data) {
return crypto.createHmac('sha256', key).update(data, 'utf8').digest('hex');
},
md5: function(buffer, callback, options) {
... | var crypto = require('crypto')
, fs = require('fs');
(function(undefined) {
'use strict';
module.exports = {
sha256: function(key, data) {
return crypto.createHmac('sha256', key).update(data, 'utf8').digest('hex');
},
md5: function(buffer, callback, options) {
... |
Check for wrong or non-existing stop or trip id | <?php
namespace GtfsMerger\Merger;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
use Nette\Caching\Cache;
use Nette\InvalidStateException;
class StopTimeLimitations implements MergerInterface
{
/** @var Cache */
private $tripsIdsCache;
/** @var Cache */
private $stopsIdsCache;
function __c... | <?php
namespace GtfsMerger\Merger;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
use Nette\Caching\Cache;
use Nette\InvalidStateException;
class StopTimeLimitations implements MergerInterface
{
/** @var Cache */
private $tripsIdsCache;
/** @var Cache */
private $stopsIdsCache;
function __c... |
Use chunkhash instead of hash for filenames | var path = require('path');
var ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: {
search: './resources/assets/js/search.js',
episode: './resources/assets/js/episode.js',
index: './resources/assets/js/index.js',
app: './resources/assets/js/app.js',
... | var path = require('path');
var ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: {
search: './resources/assets/js/search.js',
episode: './resources/assets/js/episode.js',
index: './resources/assets/js/index.js',
app: './resources/assets/js/app.js',
... |
Allow formatter to be overridden. | (function() {
'use strict';
var _ = require('lodash');
function format(pkg) {
var name = pkg.id;
var version = pkg.doc['dist-tags'].latest;
var link = 'https://www.npmjs.org/package/' + name;
return 'Package <' + link + '|' + name + '@' + version + '> published';
};
var NpmSlack = function... | (function() {
'use strict';
var _ = require('lodash');
var NpmSlack = function(opts) {
this._npm = opts.npm;
this._slack = opts.slack;
this._npmPackages = opts.npmPackages;
this._slackParams = opts.slackParams;
this._addNpmHandlers();
};
NpmSlack.prototype._addNpmHandlers = function() ... |
Make sure config returns proper value. | <?php
/**
* File: Config.php
* User: zacharydubois
* Date: 2015-12-30
* Time: 20:33
* Project: Digital-Footprint-Profile
*/
namespace dfp;
class Config {
private
$config,
$DataStore;
/**
* Config constructor.
*
* Sets the file to the configuration and grabs the current c... | <?php
/**
* File: Config.php
* User: zacharydubois
* Date: 2015-12-30
* Time: 20:33
* Project: Digital-Footprint-Profile
*/
namespace dfp;
class Config {
private
$config,
$DataStore;
/**
* Config constructor.
*
* Sets the file to the configuration and grabs the current c... |
Remove authed state on logout success | import {
LOGIN_USER_REQUEST, LOGIN_USER_SUCCESS, LOGIN_USER_FAILURE,
AUTH_USER_REQUEST, AUTH_USER_SUCCESS, AUTH_USER_FAILURE,
LOGOUT_USER_REQUEST, LOGOUT_USER_SUCCESS
} from '../constants/ActionTypes'
const initialState = {
user: null,
isAuthenticated: false,
isAuthenticating: false,
error: null,
token... | import {
LOGIN_USER_REQUEST, LOGIN_USER_SUCCESS, LOGIN_USER_FAILURE,
AUTH_USER_REQUEST, AUTH_USER_SUCCESS, AUTH_USER_FAILURE,
LOGOUT_USER_REQUEST
} from '../constants/ActionTypes'
const initialState = {
user: null,
isAuthenticated: false,
isAuthenticating: false,
error: null,
token: null
}
export defa... |
Make sure protobuf comes from pypi
Without this, it gets the outdated zip package from googlecode and fail. | #!/usr/bin/env python
import glob
import os
import subprocess
import platform
from setuptools import setup, find_packages
def make_docs():
if not os.path.exists('docs'):
os.mkdir('docs')
subprocess.call(['pydoc', '-w', 'riak'])
for name in glob.glob('*.html'):
os.rename(name, 'docs/%s' % na... | #!/usr/bin/env python
import glob
import os
import subprocess
import platform
from setuptools import setup, find_packages
def make_docs():
if not os.path.exists('docs'):
os.mkdir('docs')
subprocess.call(['pydoc', '-w', 'riak'])
for name in glob.glob('*.html'):
os.rename(name, 'docs/%s' % na... |
Check configuration file rather than env variable | import os
import logging
import json
from logging.config import dictConfig
from gluon.storage import Storage
from gluon.contrib.appconfig import AppConfig
# app_config use to cache values in production
app_config = AppConfig(reload=True)
# settings is used to avoid cached values in production
settings = Storage()
#... | import os
import logging
import json
from logging.config import dictConfig
from gluon.storage import Storage
from gluon.contrib.appconfig import AppConfig
# app_config use to cache values in production
app_config = AppConfig(reload=True)
# settings is used to avoid cached values in production
settings = Storage()
#... |
Add the 3.2 trove classifier since it's technically supported for now. | import os
from setuptools import setup
setup(name='django-contact-form',
version='1.2',
zip_safe=False, # eggs are the devil.
description='Generic contact-form application for Django',
long_description=open(os.path.join(os.path.dirname(__file__),
'READ... | import os
from setuptools import setup
setup(name='django-contact-form',
version='1.2',
zip_safe=False, # eggs are the devil.
description='Generic contact-form application for Django',
long_description=open(os.path.join(os.path.dirname(__file__),
'READ... |
Use the default file upload max memory size | """
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.conf import settings
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=None):
self.allowedEx... | """
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or [... |
Check python version and possibly only import some things |
########################################################################
# #
# This script was written by Thomas Heavey in 2017. #
# theavey@bu.edu thomasjheavey@gmail.com #
# ... |
########################################################################
# #
# This script was written by Thomas Heavey in 2017. #
# theavey@bu.edu thomasjheavey@gmail.com #
# ... |
Test for new comment property. | package com.uwetrottmann.getglue.services;
import com.uwetrottmann.getglue.BaseTestCase;
import com.uwetrottmann.getglue.entities.GetGlueInteraction;
import com.uwetrottmann.getglue.entities.GetGlueInteractionResource;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
public class ... | package com.uwetrottmann.getglue.services;
import com.uwetrottmann.getglue.BaseTestCase;
import com.uwetrottmann.getglue.entities.GetGlueInteraction;
import com.uwetrottmann.getglue.entities.GetGlueInteractionResource;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
public class ... |
example: Add example of removing physics force | FamousFramework.scene('famous-tests:physics:basic:particle', {
behaviors: {
'.particle': {
'size': [200, 200],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'style': {
'background': 'whitesmoke',
'border-radius': '50%'
... | FamousFramework.scene('famous-tests:physics:basic:particle', {
behaviors: {
'.particle': {
'size': [200, 200],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'style': {
'background': 'whitesmoke',
'border-radius': '50%'
... |
Add extra read(...) method for performance | package org.bouncycastle.asn1;
import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
class DefiniteLengthInputStream
extends LimitedInputStream
{
private int _length;
DefiniteLengthInputStream(
InputStream in,
int length)
{
... | package org.bouncycastle.asn1;
import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
class DefiniteLengthInputStream
extends LimitedInputStream
{
private int _length;
DefiniteLengthInputStream(
InputStream in,
int length)
{
... |
Fix for cluster detail page | (function() {
"use strict";
var app = angular.module("TendrlModule");
app.controller("clusterDetailController", clusterDetailController);
/*@ngInject*/
function clusterDetailController($state, $stateParams, utils, $scope, $rootScope) {
var vm = this;
vm.tabList = { "Host": 1 };
... | (function() {
"use strict";
var app = angular.module("TendrlModule");
app.controller("clusterDetailController", clusterDetailController);
/*@ngInject*/
function clusterDetailController($state, $stateParams, utils, $scope, $rootScope) {
var vm = this;
vm.tabList = { "Host": 1 };
... |
Copy over the tracers as well | <?php
namespace Hoopak;
use Hoopak\Annotation;
class Trace
{
/**
* Create a Trace.
*/
public function __construct($name, $traceId=null, $spanId=null, $parentSpanId=null, $tracers=array())
{
$this->name = $name;
if ($traceId) {
$this->traceId = $traceId;
} els... | <?php
namespace Hoopak;
use Hoopak\Annotation;
class Trace
{
/**
* Create a Trace.
*/
public function __construct($name, $traceId=null, $spanId=null, $parentSpanId=null, $tracers=array())
{
$this->name = $name;
if ($traceId) {
$this->traceId = $traceId;
} els... |
Fix AppVeyor build or break it in a different way | from .checks import (check_quantity,
check_relativistic,
_check_quantity,
_check_relativistic)
from .exceptions import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError,
... | from .checks import (check_quantity,
check_relativistic,
_check_quantity,
_check_relativistic)
from .exceptions import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError,
... |
Use $uibModalInstance in login controller | export default /*@ngInject*/class LoginController{
constructor(user,$uibModalInstance){
this.user = user;
this.$uibModalInstance = $uibModalInstance;
this.data = {};
this.loginFields = [{
key: 'email',
type: 'horizontalInput',
templateOptions: {
type: 'email',
label: ... | export default /*@ngInject*/class LoginController{
constructor(user,$modalInstance){
this.user = user;
this.$modalInstance = $modalInstance;
this.data = {};
this.loginFields = [{
key: 'email',
type: 'horizontalInput',
templateOptions: {
type: 'email',
label: 'E-Mail',... |
Update validation check for paper bundles. | #!/usr/bin/python3
from random import randint
class Student:
def __init__(self, id):
self.id = id
self.papers = []
def assign_paper(self, paper):
self.papers.append(paper)
def __str__(self):
return str(self.id) + ": " + str(self.papers)
class Paper:
def __init__(self, ... | #!/usr/bin/python3
from random import randint
class Student:
def __init__(self, id):
self.id = id
self.papers = []
def assign_paper(self, paper):
self.papers.append(paper)
def __str__(self):
return str(self.id) + ": " + str(self.papers)
class Paper:
def __init__(self, ... |
Add a general 'loading script' to ignore list | window._trackJs = {
onError: function(payload, error) {
function itemExistInList(item, list) {
for (var i = 0; i < list.length; i++) {
if (item.indexOf(list[i]) > -1) {
return true;
}
}
return false;
}
... | window._trackJs = {
onError: function(payload, error) {
function itemExistInList(item, list) {
for (var i = 0; i < list.length; i++) {
if (item.indexOf(list[i]) > -1) {
return true;
}
}
return false;
}
... |
Remove scripting for now, just git pull | <?php
require 'core.php';
// No unauthenticated deploys!
protectPage();
// Run relevant deploy.
$hash = $_GET['project'];
$targets = getDeployTargets();
foreach ($targets as $target)
{
if ($target->getIdentifier() == $hash)
{
$result = shell_exec('/usr/bin/git pull 2>&1'); // Execute script.
... | <?php
require 'core.php';
// No unauthenticated deploys!
protectPage();
// Run relevant deploy.
$hash = $_GET['project'];
$targets = getDeployTargets();
foreach ($targets as $target)
{
if ($target->getIdentifier() == $hash)
{
$result = exec($target->getDeployCommand() . ' 2>&1'); // Execute script.
... |
Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack. |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linalg',parent_package,top_path)
config.add_data_dir('tests')
# Configure lapack_lite
lapack_info = get_info('lapack... |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linalg',parent_package,top_path)
config.add_data_dir('tests')
# Configure lapack_lite
lapack_info = get_info('lapack... |
Add TODO about using an enum instead of an unconstrained string
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1519 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
// TODO: This o... | package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
private String ... |
Remove widget specific code from soap data source | <?php
namespace ATPViz\DataSource;
class SOAP extends AbstractDataSource
{
public function getData()
{
$options = $this->getOptions();
$url = $options['url'];
$namespace = $options['namespace'];
$client = new \ATP\Soap\Client($url, $namespace);
$headers = array();
foreach($options['header... | <?php
namespace ATPViz\DataSource;
class SOAP extends AbstractDataSource
{
public function getData()
{
$options = $this->getOptions();
$url = $options['url'];
$namespace = $options['namespace'];
$client = new \ATP\Soap\Client($url, $namespace);
$headers = array();
foreach($options['header... |
Correct dependency to TYPO3 version to ensure that the correct forms are loaded | <?php
/***************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
***************************************************************/
$EM_CONF[$_EXTKEY] = array (
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package del... | <?php
/***************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
***************************************************************/
$EM_CONF[$_EXTKEY] = array (
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package del... |
Refactor file type registry to use services | <?php
namespace Becklyn\AssetsBundle\File;
use Becklyn\AssetsBundle\Asset\Asset;
use Becklyn\AssetsBundle\File\Type\CssFile;
use Becklyn\AssetsBundle\File\Type\FileType;
use Becklyn\AssetsBundle\File\Type\GenericFile;
use Becklyn\AssetsBundle\File\Type\JavaScriptFile;
use Becklyn\AssetsBundle\File\Type\SvgFile;
cla... | <?php
namespace Becklyn\AssetsBundle\File;
use Becklyn\AssetsBundle\Asset\Asset;
use Becklyn\AssetsBundle\File\Type\CssFile;
use Becklyn\AssetsBundle\File\Type\FileType;
use Becklyn\AssetsBundle\File\Type\GenericFile;
use Becklyn\AssetsBundle\File\Type\JavaScriptFile;
use Becklyn\AssetsBundle\File\Type\SvgFile;
cla... |
Add six package version specifier | import os.path
from ez_setup import use_setuptools
use_setuptools(min_version='0.6')
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex'... | import os.path
from ez_setup import use_setuptools
use_setuptools(min_version='0.6')
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex'... |
Add null default to getList options param | <?php
declare(strict_types=1);
/*
* This file is part of the Nexylan packages.
*
* (c) Nexylan SAS <contact@nexylan.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nexy\Gandi\Api;
/**
* @author Jérôme Pogeant <p... | <?php
declare(strict_types=1);
/*
* This file is part of the Nexylan packages.
*
* (c) Nexylan SAS <contact@nexylan.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nexy\Gandi\Api;
/**
* @author Jérôme Pogeant <p... |
Write cluster_tendrl_context to proper location
Currently it is written to clusters/<node-id>/TendrlContext
This is fixed in this PR
tendrl-bug-id: Tendrl/commons#302
Signed-off-by: nnDarshan <d2c6d450ab98b078f2f1942c995e6d92dd504bc8@gmail.com> | import json
import logging
import os
import socket
import uuid
from tendrl.commons.etcdobj import EtcdObj
from tendrl.commons.utils import cmd_utils
from tendrl.commons import objects
LOG = logging.getLogger(__name__)
class ClusterTendrlContext(objects.BaseObject):
def __init__(
self,
integra... | import json
import logging
import os
import socket
import uuid
from tendrl.commons.etcdobj import EtcdObj
from tendrl.commons.utils import cmd_utils
from tendrl.commons import objects
LOG = logging.getLogger(__name__)
class ClusterTendrlContext(objects.BaseObject):
def __init__(
self,
integra... |
Handle select/unselect of a single row | /**
* Handling of BUIC listings.
*
* @mixin
* @namespace Bolt.buic.listing
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic.listing mixin container.
*
* @private
* @type {Object}
*/
var listing ... | /**
* Handling of BUIC listings.
*
* @mixin
* @namespace Bolt.buic.listing
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic.listing mixin container.
*
* @private
* @type {Object}
*/
var listing ... |
Fix SonarQube issues: not all of them. | /**
*
*/
package normalization;
import datastructures.AttributeJoint;
import datastructures.DFJoint;
import dependency.ADependency;
import dependency.FunctionalDependency;
/**
* @author Pavel Nichita
*
*/
public final class Normalization {
private Normalization() {
// Private constructor to hid... | /**
*
*/
package normalization;
import datastructures.AttributeJoint;
import datastructures.DFJoint;
import dependency.ADependency;
import dependency.FunctionalDependency;
/**
* @author Pavel Nichita
*
*/
public final class Normalization {
/**
* Calculates all attributes that are being implied by ... |
Fix bug with Overleaf commits swapping name and email. | package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;
import uk.ac.ic.wlgitbridge.util.Util;
/**
* Created by Winston on 06/11/14.
*/
public class SnapshotInfo implements Comparable<SnapshotInfo> {
private int versionId;
private String comment;
private WLUser user;
private String create... | package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;
import uk.ac.ic.wlgitbridge.util.Util;
/**
* Created by Winston on 06/11/14.
*/
public class SnapshotInfo implements Comparable<SnapshotInfo> {
private int versionId;
private String comment;
private WLUser user;
private String create... |
Add hash and eq methods | """
File: abstract_constraint.py
Purpose: Define a constraint, in an abstract sense, related to a number of actors.
"""
from abc import ABCMeta, abstractmethod
class AbstractConstraint(object):
"""
Class that represents a constraint, a set of actors that define a constraint amongst themselves.
Paramet... | """
File: abstract_constraint.py
Purpose: Define a constraint, in an abstract sense, related to a number of actors.
"""
from abc import ABCMeta, abstractmethod
class AbstractConstraint(object):
"""
Class that represents a constraint, a set of actors that define a constraint amongst themselves.
Paramet... |
Set creationDate and modifiedDate when reading content from external sources to be able to calculate different eTag. | package org.unitedinternet.cosmo.ext;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.unitedinternet.cosmo.model.ICalendarItem;
import org.unitedinternet.cosmo.model.NoteItem;
import org.unitedinternet.cosmo.model.hibernate.EntityConverter;
import org.unitedinternet.cosmo.model.hiber... | package org.unitedinternet.cosmo.ext;
import java.util.HashSet;
import java.util.Set;
import org.unitedinternet.cosmo.model.ICalendarItem;
import org.unitedinternet.cosmo.model.NoteItem;
import org.unitedinternet.cosmo.model.hibernate.EntityConverter;
import net.fortuna.ical4j.model.Calendar;
/**
* Helper class th... |
Update to unexpected v10's addAssertion syntax [ci skip]. | /*global Uint8Array*/
var exifParser = require('exif-parser'),
fs = require('fs');
module.exports = {
name: 'unexpected-exif',
version: require('../package.json').version,
installInto: function (expect) {
expect.installPlugin(require('magicpen-media'));
expect.addAssertion('<string|Buf... | /*global Uint8Array*/
var exifParser = require('exif-parser'),
fs = require('fs');
module.exports = {
name: 'unexpected-exif',
version: require('../package.json').version,
installInto: function (expect) {
expect.installPlugin(require('magicpen-media'));
expect.addAssertion(['string', '... |
Add comments in StripeJS mock | // StripeJS fixture for using Stripe in feature specs. Mimics credit card form and Element objects.
// Based on: https://github.com/thoughtbot/fake_stripe/blob/v0.3.0/lib/fake_stripe/assets/v3.js
// The original has been adapted to work with OFN (see commit history for details).
class Element {
mount(el) {
if (t... | class Element {
mount(el) {
if (typeof el === "string") {
el = document.querySelector(el);
}
el.classList.add('StripeElement');
el.innerHTML = `
<input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text">
<input name="exp-date" placeholder="MM /... |
Make it work with last fman version (0.7) on linux | from fman import DirectoryPaneCommand, show_alert
from urllib.parse import urlparse
import os.path
from shutil import copytree, copyfile
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(sele... | from fman import DirectoryPaneCommand, show_alert
import distutils
from distutils import dir_util, file_util
import os.path
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(selected_files) =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.