text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add time to debug log format | from flask import Flask
import os
import os.path
__version__ = "0.1.0"
def create_app(config=None):
app = Flask(__name__, instance_relative_config=True)
config_name = "eyeflask.cfg"
# Use user specified config file if provided.
if config:
config_path = os.path.abspath(config)
# Load fr... | from flask import Flask
import os
import os.path
__version__ = "0.1.0"
def create_app(config=None):
app = Flask(__name__, instance_relative_config=True)
config_name = "eyeflask.cfg"
# Use user specified config file if provided.
if config:
config_path = os.path.abspath(config)
# Load fr... |
Switch order of next trip and totals | /* global fetch */
import React from 'react';
import TotalWidget from './TotalWidget';
import NextTripWidget from './NextTripWidget';
import TripTable from './TripTable';
import VisitedMap from './VisitedMap';
import WishlistMap from './WishlistMap';
import './scss/overview.scss';
class Overview extends React.Compone... | /* global fetch */
import React from 'react';
import TotalWidget from './TotalWidget';
import NextTripWidget from './NextTripWidget';
import TripTable from './TripTable';
import VisitedMap from './VisitedMap';
import WishlistMap from './WishlistMap';
import './scss/overview.scss';
class Overview extends React.Compone... |
Create a variable in scope to avoid being override | var mongoose = require('mongoose');
var ShortId = require('./shortid');
var defaultSave = mongoose.Model.prototype.save;
mongoose.Model.prototype.save = function(cb) {
for (key in this.schema.tree) {
var fieldName = key
if (this.isNew && this[fieldName] === undefined) {
var idType = this.schema.tree[... | var mongoose = require('mongoose');
var ShortId = require('./shortid');
var defaultSave = mongoose.Model.prototype.save;
mongoose.Model.prototype.save = function(cb) {
for (fieldName in this.schema.tree) {
if (this.isNew && this[fieldName] === undefined) {
var idType = this.schema.tree[fieldName];
... |
Fix unmerged content from last commit | import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import userReducer from './reducers/userReducer.js';
import applicationReducer from './reducers/applicationReducer.js';
import serverReducer from './reducers/serverReducer.js';
import getDataReducer from './reducers/getDataReducer.js';
impo... | import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import userReducer from './reducers/userReducer.js';
import applicationReducer from './reducers/applicationReducer.js';
import serverReducer from './reducers/serverReducer.js';
import getDataReducer from './reducers/getDataReducer.js';
impo... |
Fix to use correct nicks when showing comments. | "use strict";
var React = require("react");
var PlayerStore = require("../stores/PlayerStore.react");
var moment = require("moment");
var momentLocale = require("moment/locale/nb.js");
moment.locale("nb", momentLocale);
var _ = require("underscore");
var NewsComments = React.createClass({
displayName: "News Commen... | "use strict";
var React = require("react");
var PlayerStore = require("../stores/PlayerStore.react");
var moment = require("moment");
var momentLocale = require("moment/locale/nb.js");
moment.locale("nb", momentLocale);
var _ = require("underscore");
var NewsComments = React.createClass({
displayName: "News Commen... |
Disable user-defined artifacts testing module | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.sleuthkit.autopsy.modules.UserArtifacts;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;... | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.sleuthkit.autopsy.modules.UserArtifacts;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;... |
Add github adapter module dependency | 'use strict';
angular.module('main', [
'ionic',
'ngCordova',
'ui.router',
'pascalprecht.github-adapter'
])
.config(function ($stateProvider, $urlRouterProvider, $githubProvider) {
// ROUTING with ui.router
$urlRouterProvider.otherwise('/main/list');
$stateProvider
// this state is placed in the <ion-... | 'use strict';
angular.module('main', [
'ionic',
'ngCordova',
'ui.router',
// TODO: load other modules selected during generation
])
.config(function ($stateProvider, $urlRouterProvider) {
// ROUTING with ui.router
$urlRouterProvider.otherwise('/main/list');
$stateProvider
// this state is placed in t... |
Upgrade to sendmail 4.3, fixed old bug with transaction | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.1.0"
test_requirements = [
'nose',
'webtest',
]
setup(name='tgext.mailer',
version=versi... | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.1.0"
test_requirements = [
'nose',
'webtest',
]
setup(name='tgext.mailer',
version=versi... |
Read data set up updated
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@11903 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd | import mmcorej.TaggedImage;
import org.json.JSONObject;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.api.MMTags;
import org.micromanager.api.TaggedImageStorage;
public class ReadDataSet {
public static void main(String[] args) {
String rootName = "C:... | import mmcorej.TaggedImage;
import org.json.JSONObject;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.api.TaggedImageStorage;
public class ReadDataSet {
public static void main(String[] args) {
//String rootName = "C:/AcqusitionData/Tests/Test-A_1";
... |
Revert "[twig] make method to be protected."
This reverts commit a677e9f8a3480937f1bdc3b322d978222d4157c1. | <?php
namespace Payum\Core\Bridge\Twig;
class TwigFactory
{
/**
* @return string[]
*/
public static function createGenericPaths()
{
return array_flip(array_filter(array(
'PayumCore' => self::guessViewsPath('Payum\Core\Payment'),
'PayumStripe' => self::guessViewsPat... | <?php
namespace Payum\Core\Bridge\Twig;
class TwigFactory
{
/**
* @return \Twig_Environment
*/
public static function createGeneric()
{
$loader = new \Twig_Loader_Filesystem();
foreach (static::createGenericPaths() as $path => $namespace) {
$loader->addPath($path, $nam... |
Fix deprecated ZipCode validator methods calls | <?php
namespace SLLH\IsoCodesValidator\Constraints;
use IsoCodes;
use SLLH\IsoCodesValidator\IsoCodesConstraintValidator;
use Symfony\Component\Validator\Constraint;
/**
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*/
class ZipCodeValidator extends IsoCodesConstraintValidator
{
/**
* @param mixed ... | <?php
namespace SLLH\IsoCodesValidator\Constraints;
use IsoCodes;
use SLLH\IsoCodesValidator\IsoCodesConstraintValidator;
use Symfony\Component\Validator\Constraint;
/**
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*/
class ZipCodeValidator extends IsoCodesConstraintValidator
{
/**
* @param mixed ... |
Allow changing domain to own | from flask_wtf import Form
from flask_security.core import current_user
from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField
from wtforms.validators import Required, Length, Regexp
from ..core.db import db
from ..core.security import User
from .. import app
class ApplicationForm(Form)... | from flask_wtf import Form
from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField
from wtforms.validators import Required, Length, Regexp
from ..core.db import db
from ..core.security import User
from .. import app
class ApplicationForm(Form):
start = SubmitField('Start')
stop =... |
Fix unknown textDecoration style prop being passed to React Native | // @flow
import React, {Component} from 'react'
import {Box, Text} from './'
import {globalStyles, globalColors} from '../styles/style-guide'
import {isMobile} from '../constants/platform'
import type {Props} from './usernames'
export function usernameText ({type, users, style, inline}: Props) {
return users.map((u... | // @flow
import React, {Component} from 'react'
import {Box, Text} from './'
import {globalStyles, globalColors} from '../styles/style-guide'
import type {Props} from './usernames'
export function usernameText ({type, users, style, inline}: Props) {
return users.map((u, i) => {
const userStyle = {
textDec... |
Check Campaign Existence for Delete/Set/Get Purposes | var configuration = require('../../config/configuration.json')
var utility = require('../../public/method/utility')
module.exports = {
checkCampaignModel: function (redisClient, accountHashID, payload, callback) {
var begTime = utility.getUnixTimeStamp() - configuration.MinimumDelay
var endTime = utility.get... | var configuration = require('../../config/configuration.json')
var utility = require('../../public/method/utility')
module.exports = {
checkCampaignModel: function (redisClient, accountHashID, payload, callback) {
var begTime = utility.getUnixTimeStamp() - configuration.MinimumDelay
var endTime = utility.get... |
Select all on input elements when navigating to them | import React from 'react';
import ImmutableComponent from '../../../ImmutableComponent';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import SuggestionsList from '../suggestions-list';
import { getEditValue, getDefaultValue } from '../format';
export default class InteractiveEditable extend... | import { List as list } from 'immutable';
import React from 'react';
import ImmutableComponent from '../../../ImmutableComponent';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import SuggestionsList from '../suggestions-list';
import { getEditValue, getDefaultValue } from '../format';
expor... |
Fix overflowing text bug by replacing the tags.
Fix weird text overflowing bug/glitch by replacing <pre> tags with <div>. This should fix the overflowing/xyz bug/glitch thing since <div> is block-shaped. Not sure about <pre> but I think it's not block-shaped.. Maybe this might be the problem. More about <pre>'s: http:... | <!DOCTYPE html>
<html>
<head>
<title>OpenSprites Blog</title>
<?php include("header.php"); ?>
</head>
<body>
<!-- This is slightly inspired by andrewjcole's blog, those who haven't should
check it out at blog.opensprites.x10.mx/andrewjcole/ -->
<?php include("includes... | <!DOCTYPE html>
<html>
<head>
<title>OpenSprites Blog</title>
<?php include("header.php"); ?>
</head>
<body>
<!-- This is slightly inspired by andrewjcole's blog, those who haven't should
check it out at blog.opensprites.x10.mx/andrewjcole/ -->
<?php include("includes... |
Add default fallback to mapping logic. | (function () {
'use strict';
define(
[
'lodash',
'knockout'
],
function (_, ko) {
return function (selectedSearchTypeObservable, resultFieldsObservable, detailUrlTemplate) {
return {
mapType: function (searchType) {... | (function () {
'use strict';
define(
[
'lodash',
'knockout'
],
function (_, ko) {
return function (selectedSearchTypeObservable, resultFieldsObservable, detailUrlTemplate) {
return {
mapType: function (searchType) {... |
Use TreeBuilder constructor, deprecated using RootNode | <?php
namespace Bookboon\ApiBundle\DependencyInjection;
use Bookboon\Api\Cache\RedisCache;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* Generates the configuration tr... | <?php
namespace Bookboon\ApiBundle\DependencyInjection;
use Bookboon\Api\Cache\RedisCache;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* Generates the configuration tr... |
Set better description to superhelio:reload | <?php
namespace Superhelio\Commands\Commands;
use Illuminate\Console\Command;
class Reload extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'superhelio:reload';
/**
* The console command description.
*
* @... | <?php
namespace Superhelio\Commands\Commands;
use Illuminate\Console\Command;
class Reload extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'superhelio:reload';
/**
* The console command description.
*
* @... |
Add 'treq' as a requirement for GitHubStatusPush. | from setuptools import setup, find_packages
setup(
name='autobuilder',
version='1.0.3',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
entry_points={
'console_scripts': [
'update-sstate-mirror = autobuilder.scripts.up... | from setuptools import setup, find_packages
setup(
name='autobuilder',
version='1.0.2',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
entry_points={
'console_scripts': [
'update-sstate-mirror = autobuilder.scripts.up... |
Fix jslint warning in null checks | /*!
* Wef
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
/**
* wef module
*/
(function(global) {
var wef = function() {
return new wef.prototype.init();
};
wef.prototype = {
constructor:wef,
version: "0.0.1",
init: function() {
return this;
}... | /*!
* Wef
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
/**
* wef module
*/
(function(global) {
var wef = function() {
return new wef.prototype.init();
};
wef.prototype = {
constructor:wef,
version: "0.0.1",
init: function() {
return this;
}... |
Add LOGIN_URL setting for Oauth2 |
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.Django... |
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.Django... |
Create helpers to create a raven instance | package net.kencochrane.raven;
import java.util.ServiceLoader;
/**
* Factory in charge of creating {@link Raven} instances.
* <p>
* The factories register themselves through the {@link ServiceLoader} system.
* </p>
*/
public abstract class RavenFactory {
private static final ServiceLoader<RavenFactory> RAVEN... | package net.kencochrane.raven;
import java.util.ServiceLoader;
/**
* Factory in charge of creating {@link Raven} instances.
* <p>
* The factories register themselves through the {@link ServiceLoader} system.
* </p>
*/
public abstract class RavenFactory {
private static final ServiceLoader<RavenFactory> RAVEN... |
Remove unused imports to fix Travis | package seedu.taskmanager.ui;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.taskmanager.commons.util.FxViewUtil;
import seedu.taskmanager.model.task.ReadOnlyTask;
/**
* The Browser Panel of the App.
*/
public class BrowserP... | package seedu.taskmanager.ui;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.scene.web.WebView;
import seedu.taskmanager.commons.util.FxViewUtil;
import seedu.taskmanager.model.task.ReadOnlyTask;
/**
* The Browser Panel of t... |
Add some javadoc. Detect if the limit is a negative number. Extract method for processing the limit value as a numeric. | package uk.ac.ebi.quickgo.ontology.coterms;
/**
* Logic for determining the limit to use for retrieving co-occurring terms
*
* @author Tony Wardell
* Date: 29/09/2016
* Time: 16:08
* Created with IntelliJ IDEA.
*/
public class CoTermLimit {
int defaultLimit;
/**
*
* @param defaultLimit The ... | package uk.ac.ebi.quickgo.ontology.coterms;
/**
* @author Tony Wardell
* Date: 29/09/2016
* Time: 16:08
* Created with IntelliJ IDEA.
*/
public class CoTermLimit {
int defaultLimit;
public CoTermLimit(int defaultLimit) {
this.defaultLimit = defaultLimit;
}
public int workoutLimit(String... |
:lipstick: Fix coding style - lowercase keywords | <?php
namespace Clippings\Freezable;
/**
* @author Haralan Dobrev <hkdobrev@gmail.com>
* @copyright 2014, Clippings Ltd.
* @license http://spdx.org/licenses/BSD-3-Clause
*/
trait FreezableCollectionTrait
{
use FreezableTrait;
private static function ensureItemsAreTraversable($items)
{
if... | <?php
namespace Clippings\Freezable;
/**
* @author Haralan Dobrev <hkdobrev@gmail.com>
* @copyright 2014, Clippings Ltd.
* @license http://spdx.org/licenses/BSD-3-Clause
*/
trait FreezableCollectionTrait
{
use FreezableTrait;
private static function ensureItemsAreTraversable($items)
{
if... |
Allow Local LAN devices to access the livereload machine | const rewrite = require('connect-modrewrite');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
module.exports = function (grunt) {
return {
livereload: {
options: {
hostname : '0.0.0.0',
port : 443,
... | const rewrite = require('connect-modrewrite');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
module.exports = function (grunt) {
return {
livereload: {
options: {
hostname : '127.0.0.1',
port : 443,
... |
Include an uglified version when compiling | module.exports = function(grunt) {
var requirejsOptions = require('./config');
requirejsOptions.optimize = 'none';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: ['Gruntfile.js', 'js/**/*.js', 'tests/*.js']
},
karma: {
options... | module.exports = function(grunt) {
var requirejsOptions = require('./config');
requirejsOptions.optimize = 'none';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: ['Gruntfile.js', 'js/**/*.js', 'tests/*.js']
},
karma: {
options... |
Change path to site no requested authorization. | package bj.pranie.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.bui... | package bj.pranie.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.bui... |
Declare wizard abstract factory in service manager | <?php
return array(
'wizard' => array(
'default_layout_template' => 'wizard/layout',
'default_class' => 'Wizard\Wizard',
),
'service_manager' => array(
'invokables' => array(
'Wizard\Form\Element\Button\Cancel' => 'Wizard\Form\Element\Button\Cancel',
... | <?php
return array(
'wizard' => array(
'default_layout_template' => 'wizard/layout',
'default_class' => 'Wizard\Wizard',
),
'service_manager' => array(
'factories' => array(
'Wizard\Config' => 'Wizard\Factory\ConfigFactory',
'Wizard\Factory' ... |
Reduce visibility from public to package | package org.gdg.frisbee.android.about;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import org.gdg.frisbee.android.R;
class AboutPagerAdapter extends FragmentStatePagerAdapter {
priv... | package org.gdg.frisbee.android.about;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import org.gdg.frisbee.android.R;
public class AboutPagerAdapter extends FragmentStatePagerAdapter {
... |
Add file dimensions when we read in images | import { Meteor } from 'meteor/meteor';
import { ImageFiles } from '/imports/api/imageFiles/imageFiles';
import fs from 'fs';
import _ from 'lodash';
import sizeOf from 'image-size';
import mime from 'mime';
// Path to our images folder
const collectionImages = `${process.env.PWD}/public/images/collection/`;
// Read ... | import { Meteor } from 'meteor/meteor';
import { ImageFiles } from '/imports/api/imageFiles/imageFiles';
import fs from 'fs';
import _ from 'lodash';
import sizeOf from 'image-size';
import mime from 'mime';
// Path to our images folder
const collectionImages = `${process.env.PWD}/public/images/collection/`;
// Read ... |
Use 'include' to check for file existance.
As it uses the include path. | <?php
// Load console class for autoloader?
$use_console = false;
// Optional mapping of Namespace to directories.
$namespace_mapping = array(
'NigeLib' => 'src',
);
if( $use_console ) {
require( 'src/Console.php' );
}
function PSR0_autoload($className)
{
global $use_console;
global $namespace_map... | <?php
// Load console class for autoloader?
$use_console = true;
// Optional mapping of Namespace to directories.
$namespace_mapping = array(
'NigeLib' => 'src',
);
if( $use_console ) {
require( 'src/Console.php' );
}
function PSR0_autoload($className)
{
global $use_console;
global $namespace_mapp... |
Make test Callback a little more reusable | <?php
namespace Respect\Validation\Rules;
class CallbackTest extends \PHPUnit_Framework_TestCase
{
private $truthy, $falsy;
function setUp() {
$this->truthy = new Callback(function() {
return true;
});
$this->falsy = new Callback(function() {
return false;
... | <?php
namespace Respect\Validation\Rules;
class CallbackTest extends \PHPUnit_Framework_TestCase
{
public function thisIsASampleCallbackUsedInsideThisTest()
{
return true;
}
public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue()
{
$v = new Callback(function() ... |
Throw the right error from failing second request
Fixes #4. | // @flow
type Configuration = {
refreshToken: () => Promise<void>,
shouldRefreshToken: (error: any) => boolean,
fetch: (url: any, options: Object) => Promise<any>
}
function configureRefreshFetch (configuration: Configuration) {
const { refreshToken, shouldRefreshToken, fetch } = configuration
let refreshi... | // @flow
type Configuration = {
refreshToken: () => Promise<void>,
shouldRefreshToken: (error: any) => boolean,
fetch: (url: any, options: Object) => Promise<any>
}
function configureRefreshFetch (configuration: Configuration) {
const { refreshToken, shouldRefreshToken, fetch } = configuration
let refreshi... |
Return the data not gzip decoded
Requests does that by default so you need to use the underlying raw data and
let webtest decode it itself instead. | # -*- coding: utf-8 -*-
import requests
from functools import partial
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_option... | # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.updat... |
Include analysis detail view URL in message | from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView
from .forms import AbstractAnalysisCreateForm
from .pipelines i... | from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView
from .forms import AbstractAnalysisCreateForm
from .pipelines i... |
Use maximum instead of if-statement | import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class BinaryAccuracy(function.Function):
ignore_label = -1
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
x_type, t_type = in_types
type_check.ex... | import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class BinaryAccuracy(function.Function):
ignore_label = -1
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
x_type, t_type = in_types
type_check.ex... |
Use xdg-screensaver instead of xset | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super... | # pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xset
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super(Module, s... |
Fix weird bug when creating new exhibition | @extends('layouts.app')
@section('sidemenu')
@include('layouts.menu')
@endsection
@section('content')
<div class="panel panel-default">
<div class="panel-heading">
Exhibitions
</div>
<div class="panel-body">
@foreach($exhibitions as $exhibition)
... | @extends('layouts.app')
@section('sidemenu')
@include('layouts.menu')
@endsection
@section('content')
<div class="panel panel-default">
<div class="panel-heading">
Exhibitions
</div>
<div class="panel-body">
@foreach($exhibitions as $exhibition)
... |
Add icon information for views | angular.module('Mccy.routes', [
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/view', {
templateUrl: 'views/view-containers.html',
controller: 'ViewContainersCtrl'
})
.when('/new-server', {
... | angular.module('Mccy.routes', [
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/view', {
templateUrl: 'views/view-containers.html',
controller: 'ViewContainersCtrl'
})
.when('/new-server', {
... |
Fix typo in debugging comment | // namespace
var App = App || {};
App.WebSocketState = (function () {
"use strict";
console.log("WebSocketState Compiling ...");
var fn = function (game) {
console.log("WebSocketState.constructor Running...");
Phaser.State.call(this, game);
};
fn.prototype = Object.create(Phaser.S... | // namespace
var App = App || {};
App.WebSocketState = (function () {
"use strict";
console.log("WebSocketState.create Compiling ...");
var fn = function (game) {
Phaser.State.call(this, game);
console.log("WebSocketState.constructor Running...");
};
fn.prototype = Object.create(P... |
Make it possible to pass in null as the logger, if you don't want to login exceptions when closing a resource. Not really advisable, but useful when testing and should only really be used for that. | package org.carlspring.strongbox.resource;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import java.io.Closeable;
import java.io.IOException;
import org.slf4j.Logger;
/**
* A utility class for safely closing resources and logging eventual errors.
* The purpose of this class is to avoid boile... | package org.carlspring.strongbox.resource;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import java.io.Closeable;
import java.io.IOException;
import org.slf4j.Logger;
/**
* A utility class for safely closing resources and logging eventual errors.
* The purpose of this class is to avoid boile... |
Make the last function also a generator, so that the explanation flows better | #!/usr/bin/env python
import sys, operator, string
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_char = True
for c in characters(filename):
if start_char == True:
word = ""
if c.isalnum():
... | #!/usr/bin/env python
import sys, operator, string
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_char = True
for c in characters(filename):
if start_char == True:
word = ""
if c.isalnum():
... |
Add error handling to Read book page | // @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2017 GDL
*
* See LICENSE
*/
import * as React from 'react';
import { fetchBook } from '../../fetch';
import type { BookDetails, Context } from '../../types';
import defaultPage from '../../hocs/defaultPage';
import errorPage from '../../hocs/errorPage';
im... | // @flow
/**
* Part of GDL gdl-frontend.
* Copyright (C) 2017 GDL
*
* See LICENSE
*/
import * as React from 'react';
import { fetchBook } from '../../fetch';
import type { BookDetails, Context } from '../../types';
import defaultPage from '../../hocs/defaultPage';
import Head from '../../components/Head';
import... |
Add default values to posts table migration
Add default values to all new columns in the posts table restructuring
migration so that these migrations can be run on an sqlite database.
Fixes #22 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RestructurePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$t... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RestructurePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$t... |
Improve status display for reports. | from pyramid.renderers import get_renderer
from pyramid.view import view_config
from . import get_report_info
from . import list_employees
from . import list_reports
def get_main_template(request):
main_template = get_renderer('templates/main.pt')
return main_template.implementation()
@view_config(route_nam... | from pyramid.renderers import get_renderer
from pyramid.view import view_config
from . import get_report_info
from . import list_employees
from . import list_reports
def get_main_template(request):
main_template = get_renderer('templates/main.pt')
return main_template.implementation()
@view_config(route_nam... |
:bug: Make sure to filter any classification associated with affiliations when the curator is NOT curating as part of an affiliation | 'use strict';
import { userMatch, affiliationMatch } from '../components/globals';
/**
* Traverse the GDM object tree to find the embedded provisionalClassification object
* @param {object} gdm - GDM object prop
* @param {object} affiliation - Affiliation object prop
* @param {object} session - User session objec... | 'use strict';
import { userMatch, affiliationMatch } from '../components/globals';
/**
* Traverse the GDM object tree to find the embedded provisionalClassification object
* @param {object} gdm - GDM object prop
* @param {object} affiliation - Affiliation object prop
* @param {object} session - User session objec... |
Fix missing request body in API client | import fetch from 'unfetch'
const apiBase = 'https://api.hackclub.com/'
const methods = ['get', 'put', 'post', 'patch']
const generateMethod = method => (path, options) => {
// authToken is shorthand for Authorization: Bearer `authtoken`
let filteredOptions = {}
for (let [key, value] of Object.entries(options))... | import fetch from 'unfetch'
const apiBase = 'https://api.hackclub.com/'
const methods = ['get', 'put', 'post', 'patch']
const generateMethod = method => (path, options) => {
// authToken is shorthand for Authorization: Bearer `authtoken`
let filteredOptions = {}
for (let [key, value] of Object.entries(options))... |
docs: Fix incorrect text for MQTT publish
Fixes #262 | const apiPutMqttMessage = {
schema: {
summary: 'Publish a message to a MQTT topic.',
description: '',
body: {
type: 'object',
properties: {
topic: {
type: 'string',
description: 'Topic to which message should be ... | const apiPutMqttMessage = {
schema: {
summary: 'Retrieve a list of all keys present in the specified namespace.',
description: '',
body: {
type: 'object',
properties: {
topic: {
type: 'string',
description: 'Name... |
Remove sdbus++ template search workaround
sdbus++ was fixed upstream to find its templates automatically.
Change-Id: I29020b9d1ea4ae8baaca5fe869625a3d96cd6eaf
Signed-off-by: Brad Bishop <713d098c0be4c8fd2bf36a94cd08699466677ecd@fuzziesquirrel.com> | #!/usr/bin/env python
import os
import sys
import yaml
import subprocess
if __name__ == '__main__':
genfiles = {
'server-cpp': lambda x: '%s.cpp' % x,
'server-header': lambda x: os.path.join(
os.path.join(*x.split('.')), 'server.hpp')
}
with open(os.path.join('example', 'inter... | #!/usr/bin/env python
import os
import sys
import yaml
import subprocess
class SDBUSPlus(object):
def __init__(self, path):
self.path = path
def __call__(self, *a, **kw):
args = [
os.path.join(self.path, 'sdbus++'),
'-t',
os.path.join(self.path, 'template... |
Fix CI to ignore system install of asn1crypto | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import site
import sys
from . import build_root, requires_oscrypto
from ._import import _preload
deps_dir = os.path.join(build_root, 'modularcrypto-deps')
if os.path.exists(deps_dir):
site.addsitedir(dep... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import site
import sys
from . import build_root, requires_oscrypto
from ._import import _preload
deps_dir = os.path.join(build_root, 'modularcrypto-deps')
if os.path.exists(deps_dir):
site.addsitedir(dep... |
tools: Store the depth (d) on the stack and restore when backtracking | # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
try:
from cStringIO import StringIO
except ImportE... | # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
try:
from cStringIO import StringIO
except ImportE... |
Move extension requirement logic into PHPUnit phpDoc annotation | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ... | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ... |
Test for new twig function | <?php
namespace Tests\Becklyn\AssetsBundle\Twig;
use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\Loader\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;
class AssetsTwigExtensionTest extends TestCase
{
... | <?php
namespace Tests\Becklyn\AssetsBundle\Twig;
use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\Loader\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;
class AssetsTwigExtensionTest extends TestCase
{
... |
Replace usage of magic class constant with FQCN string | <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->createMock('Liip\RMT\Information\InformationCollector');
... | <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->createMock('Liip\RMT\Information\InformationCollector');
... |
Add MIDDLEWARE_CLASSES to settings, remove warnings | import sys
try:
from django.conf import settings
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="holonet.urls",
INSTALLED_APPS=[
... | import sys
try:
from django.conf import settings
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="holonet.urls",
INSTALLED_APPS=[
... |
Update function help interact with User | (function () {
var User = require('../database/mongodb').Users,
jwt = require('jwt-simple'),
async = require('async'),
crypto = require('crypto');
function _getUserInfo(userId, callback) {
User.findById(userId, function (err, resp) {
callback(err, resp);
})
... | (function () {
var User = require('../database/mongodb').Users,
jwt = require('jwt-simple'),
async = require('async'),
crypto = require('crypto');
function _getUserInfo(userId, callback) {
User.findById(userId, function (err, resp) {
callback(err, resp);
})
... |
Fix the bootstrap js path | const minimist = require("minimist");
const options = minimist(process.argv.slice(2));
const isProduction = options.env === 'production';
config = {
console_options: options,
isProduction: isProduction,
src: {
js: "./sec/js/**/*.js",
vue: "./src/js/app.js",
vue_watch: "./src/js/**/... | const minimist = require("minimist");
const options = minimist(process.argv.slice(2));
const isProduction = options.env === 'production';
config = {
console_options: options,
isProduction: isProduction,
src: {
js: "./sec/js/**/*.js",
vue: "./src/js/app.js",
vue_watch: "./src/js/**/... |
Add the heyu-notifier command line script. | #!/usr/bin/env python
from setuptools import setup
def readreq(filename):
result = []
with open(filename) as f:
for req in f:
req = req.partition('#')[0].strip()
if not req:
continue
result.append(req)
return result
def readfile(filename):
... | #!/usr/bin/env python
from setuptools import setup
def readreq(filename):
result = []
with open(filename) as f:
for req in f:
req = req.partition('#')[0].strip()
if not req:
continue
result.append(req)
return result
def readfile(filename):
... |
[minor] Correct link in code comment | var util = require('util');
var log = require('minilog')('http');
module.exports = function requestLogger(req, res, next) {
//
// Pretty much copypasta from
// https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L135-L158
//
// Monkey punching res.end. It's dirty but, maan I wanna lo... | var util = require('util');
var log = require('minilog')('http');
module.exports = function requestLogger(req, res, next) {
//
// Pretty much copypasta from
// https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L168-L174
//
// Monkey punching res.end. It's dirty but, maan I wanna lo... |
Fix Salmon Run tweet mystery weapon detection | const TwitterPostBase = require('./TwitterPostBase');
const { captureSalmonRunScreenshot } = require('../screenshots');
const { readData } = require('../utilities');
class SalmonRunTweet extends TwitterPostBase {
getKey() { return 'salmonrun'; }
getName() { return 'Salmon Run'; }
getSalmonRunSchedules() {... | const TwitterPostBase = require('./TwitterPostBase');
const { captureSalmonRunScreenshot } = require('../screenshots');
const { readData } = require('../utilities');
class SalmonRunTweet extends TwitterPostBase {
getKey() { return 'salmonrun'; }
getName() { return 'Salmon Run'; }
getSalmonRunSchedules() {... |
Fix moveForward() not checking environment range when the bot falls. | package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
/**
* Lua API function to move one block forwar... | package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
/**
* Lua API function to move one block forwar... |
Allow entry of generic protocols too without forcing a search
E.g. if you try to open ftp:.... we should actually try to open that
instead of searching (in future we will try to search for apps that actually
support ftp, followed by falling back to the unsupported protocol error
page). | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.utils;
i... | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.utils;
i... |
chore(Desktop): Fix resolution of native Node modules
See https://github.com/electron-userland/electron-forge/pull/2449 | const plugins = require('./webpack.plugins')
const webpack = require('webpack')
module.exports = {
/**
* This is the main entry point for your application, it's the first file
* that runs in the main process.
*/
entry: './src/index.ts',
plugins: [
...plugins,
new webpack.DefinePlugin({
'pr... | const plugins = require('./webpack.plugins')
const webpack = require('webpack')
module.exports = {
/**
* This is the main entry point for your application, it's the first file
* that runs in the main process.
*/
entry: './src/index.ts',
plugins: [
...plugins,
new webpack.DefinePlugin({
'pr... |
Include locale in package hash | # -*- coding: utf-8 -*-
import os
import waptpackage
from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey
def download(remote, path, pkg):
"""Downloads package"""
if not pkg.package:
return False
res = remote.download_packages(pkg, path)
if res['errors']:
return False
... | # -*- coding: utf-8 -*-
import os
import waptpackage
from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey
def download(remote, path, pkg):
"""Downloads package"""
if not pkg.package:
return False
res = remote.download_packages(pkg, path)
if res['errors']:
return False
... |
Convert all the ids to strings | # -*- coding: utf-8 -*-
"""A Flask app to visualize the infection algorithm."""
from flask import Flask, request, abort, jsonify
from werkzeug.exceptions import BadRequest
from infection import User, total_infection, limited_infection
app = Flask(__name__)
def load_user_graph():
"""Get the JSON-encoded user gr... | # -*- coding: utf-8 -*-
"""A Flask app to visualize the infection algorithm."""
from flask import Flask, request, abort, jsonify
from werkzeug.exceptions import BadRequest
from infection import User, total_infection, limited_infection
app = Flask(__name__)
def load_user_graph():
"""Get the JSON-encoded user gr... |
Update translate plugin to new message format | """
Yandex Translation API
"""
import logging
from urllib.parse import quote
from telegram import Bot, Update
from telegram.ext import Updater
from requests import post
import constants # pylint: disable=E0401
import settings
import octeon
LOGGER = logging.getLogger("YTranslate")
YAURL = "https://translate.yandex.ne... | """
Yandex Translation API
"""
import logging
from urllib.parse import quote
from telegram import Bot, Update
from telegram.ext import Updater
from requests import post
import constants # pylint: disable=E0401
import settings
LOGGER = logging.getLogger("YTranslate")
YAURL = "https://translate.yandex.net/api/v1.5/tr.... |
Test even more PHP decoding cases | <?php
use Gettext\Utils\Strings;
class StringsTest extends PHPUnit_Framework_TestCase
{
public function stringFromPhpProvider()
{
return array(
array('"test"', 'test'),
array("'test'", 'test'),
array("'DATE \a\\t TIME'", 'DATE \a\t TIME'),
array("'DATE \... | <?php
use Gettext\Utils\Strings;
class StringsTest extends PHPUnit_Framework_TestCase
{
public function stringFromPhpProvider()
{
return array(
array('"test"', 'test'),
array("'test'", 'test'),
array("'DATE \a\\t TIME'", 'DATE \a\t TIME'),
array("'DATE \a... |
Remove file extension from default file
This will allow it to import scss or css files. | var findup = require('findup'),
path = require('path');
function find(dir, file, callback) {
var name = file.split('/')[0],
modulePath = './node_modules/' + name + '/package.json';
findup(dir, modulePath, function (err, moduleDir) {
if (err) { return callback(err); }
var root = pa... | var findup = require('findup'),
path = require('path');
function find(dir, file, callback) {
var name = file.split('/')[0],
modulePath = './node_modules/' + name + '/package.json';
findup(dir, modulePath, function (err, moduleDir) {
if (err) { return callback(err); }
var root = pa... |
Use interface in main to access SmlForwarder | package de.diesner.ehzlogger;
import java.io.IOException;
import java.util.List;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import org.openmuc.jsml.structures.*;
import org.openmuc.jsml.tl.SML_SerialReceiver;
public class EhzLogger {
public static void main(String[] args)... | package de.diesner.ehzlogger;
import java.io.IOException;
import java.util.List;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import org.openmuc.jsml.structures.*;
import org.openmuc.jsml.tl.SML_SerialReceiver;
public class EhzLogger {
public static void main(String[] args)... |
Move locus tag attribute key name into the function that uses it | #!/usr/bin/env python
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
locusTagAttributeKey = 'locus_tag'
components =... | #!/usr/bin/env python
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
locusTagAttributeKey = 'locus_tag'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
components = reco... |
Write exceptions to jobs logger | import logging
from datetime import datetime
from flask import current_app
from changes.backends.jenkins.builder import JenkinsBuilder
from changes.config import db, queue
from changes.constants import Status, Result
from changes.models import Build, RemoteEntity
logger = logging.getLogger('jobs')
def sync_build(b... | from datetime import datetime
from flask import current_app
from changes.backends.jenkins.builder import JenkinsBuilder
from changes.config import db, queue
from changes.constants import Status, Result
from changes.models import Build, RemoteEntity
def sync_build(build_id):
try:
build = Build.query.get(b... |
Increase page size to 100 on getAllPrograms to minimize number of requests required | <?php
namespace AppBundle\WebService\SR;
use AppBundle\WebService\SR\Responses\AllProgramsResponse;
use Ci\RestClientBundle\Services\RestClient;
use JMS\Serializer\Serializer;
/**
* Class SrWebServiceClient
*/
class SrWebServiceClient
{
/** @var RestClient */
protected $client;
/** @var Serializer */
... | <?php
namespace AppBundle\WebService\SR;
use AppBundle\WebService\SR\Responses\AllProgramsResponse;
use Ci\RestClientBundle\Services\RestClient;
use JMS\Serializer\Serializer;
/**
* Class SrWebServiceClient
*/
class SrWebServiceClient
{
/** @var RestClient */
protected $client;
/** @var Serializer */
... |
Handle GFM line break by default in MD transformer | <?php
namespace Code16\Sharp\Utils\Transformers\Attributes;
use Code16\Sharp\Utils\Transformers\SharpAttributeTransformer;
class MarkdownAttributeTransformer implements SharpAttributeTransformer
{
/** @var bool */
protected $handleImages = false;
/** @var int */
protected $imageWidth;
/** @var ... | <?php
namespace Code16\Sharp\Utils\Transformers\Attributes;
use Code16\Sharp\Utils\Transformers\SharpAttributeTransformer;
class MarkdownAttributeTransformer implements SharpAttributeTransformer
{
/** @var bool */
protected $handleImages = false;
/** @var int */
protected $imageWidth;
/** @var ... |
Make search a search input instead of text | <?php namespace ProcessWire; ?>
<header class="stripe stripe--fluid header header--reduced">
<div layout="column" layout-gt-sm="row" layout-align="start stretch">
<a class="site__logo site__logo--reduced" href="<?=$homepage->httpUrl?>">
<img srcset="<?=$homepage->image->get('name%=light')->size(... | <?php namespace ProcessWire; ?>
<header class="stripe stripe--fluid header header--reduced">
<div layout="column" layout-gt-sm="row" layout-align="start stretch">
<a class="site__logo site__logo--reduced" href="<?=$homepage->httpUrl?>">
<img srcset="<?=$homepage->image->get('name%=light')->size(... |
[Customer][Core] Rename DashboardStatistic customers count() method to countCustomers() | <?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.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Dashboard;
use Sylius\Component\Core\Model\... | <?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.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Dashboard;
use Sylius\Component\Core\Model\... |
Add a missing field to the fetch list of deny rule | Meteor.methods({
storeEncryptedPrivateKey: function (encryptedKey) {
Meteor.users.update({
_id: this.userId
}, {
$set: {
'profile.privateKey': encryptedKey
}
});
},
initEncryptionSchema: function (collectionName, fieldKey) {
... | Meteor.methods({
storeEncryptedPrivateKey: function (encryptedKey) {
Meteor.users.update({
_id: this.userId
}, {
$set: {
'profile.privateKey': encryptedKey
}
});
},
initEncryptionSchema: function (collectionName, fieldKey) {
... |
Add missing comma to requirements. | import os
from setuptools import setup
version = '0.9.2.dev0'
def read_file(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as fp:
return fp.read()
setup(name='django-ogmios',
version=version,
author="Fusionbox, Inc.",
author_email="programmers@fusionbox.com",
... | import os
from setuptools import setup
version = '0.9.2.dev0'
def read_file(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as fp:
return fp.read()
setup(name='django-ogmios',
version=version,
author="Fusionbox, Inc.",
author_email="programmers@fusionbox.com",
... |
Handle UTF errors with invalid bytes. | import logging
import requests
def scrape(url, extractor):
"""
Function to request and parse a given URL. Returns only the "relevant"
text.
Parameters
----------
url : String.
URL to request and parse.
extractor : Goose class instance.
An instance of Goose th... | import logging
import requests
def scrape(url, extractor):
"""
Function to request and parse a given URL. Returns only the "relevant"
text.
Parameters
----------
url : String.
URL to request and parse.
extractor : Goose class instance.
An instance of Goose th... |
Include answer count in stored data. |
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, nam... |
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, nam... |
Fix handling of URLs, that result in no actual model
Add $callback to scope of Closure. | <?php namespace Felixkiss\SlugRoutes;
use Illuminate\Routing\Router;
class SlugRouter extends Router
{
public function model($key, $class, Closure $callback = null)
{
return $this->bind($key, function($value) use ($class, $callback)
{
if (is_null($value)) return null;
... | <?php namespace Felixkiss\SlugRoutes;
use Illuminate\Routing\Router;
class SlugRouter extends Router
{
public function model($key, $class, Closure $callback = null)
{
return $this->bind($key, function($value) use ($class)
{
if (is_null($value)) return null;
// For mode... |
Add links to fixture and casedb specs | from casexml.apps.case.xml.generator import safe_element
from casexml.apps.phone.xml import get_casedb_element
class CaseDBFixture(object):
"""Used to provide a casedb-like structure as a fixture
Does not follow the standard FixtureGenerator pattern since it is currently
not used during a regular sync op... | from casexml.apps.case.xml.generator import safe_element
from casexml.apps.phone.xml import get_casedb_element
class CaseDBFixture(object):
"""Used to provide a casedb-like structure as a fixture
Does not follow the standard FixtureGenerator pattern since it is currently
not used during a regular sync op... |
Add Python 3.5 to PyPI classifiers | #!/usr/bin/env python3
from setuptools import setup
from doxhooks import __version__
with open("README.rst") as readme:
lines = list(readme)
for line_no, line in enumerate(lines):
if line.startswith("Doxhooks helps you"):
long_description = "".join(lines[line_no:])
break
else:
raise Runt... | #!/usr/bin/env python3
from setuptools import setup
from doxhooks import __version__
with open("README.rst") as readme:
lines = list(readme)
for line_no, line in enumerate(lines):
if line.startswith("Doxhooks helps you"):
long_description = "".join(lines[line_no:])
break
else:
raise Runt... |
Remove layout dependency in candlestick visual | define(function (require) {
var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
var positiveColorQuery = ['itemStyle', 'normal', 'color'];
var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
return f... | define(function (require) {
var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
var positiveColorQuery = ['itemStyle', 'normal', 'color'];
var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
return f... |
Fix tests when Pushover is not configured | from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
from hc.api.models import Channel
class AddChannelTestCase(TestCase):
def setUp(self):
self.alice = User(username="alice")
self.alice.set_password("password")
self.alice.save()
... | from django.contrib.auth.models import User
from django.test import TestCase
from hc.api.models import Channel
class AddChannelTestCase(TestCase):
def setUp(self):
self.alice = User(username="alice")
self.alice.set_password("password")
self.alice.save()
def test_it_works(self):
... |
Change instaflights name in flights_to tests | import unittest
import datetime
import json
import sys
sys.path.append('..')
import sabre_dev_studio
import sabre_dev_studio.sabre_exceptions as sabre_exceptions
'''
requires config.json in the same directory for api authentication
{
"sabre_client_id": -----,
"sabre_client_secret": -----
}
'''
class TestBasicFlig... | import unittest
import datetime
import json
import sys
sys.path.append('..')
import sabre_dev_studio
import sabre_dev_studio.sabre_exceptions as sabre_exceptions
'''
requires config.json in the same directory for api authentication
{
"sabre_client_id": -----,
"sabre_client_secret": -----
}
'''
class TestBasicInst... |
:bug: Fix a dead lock in App.lock | (function(target) {
'use strict'
function ajax(Url, Method, Contents) {
return new Promise(function(resolve, reject) {
const XHR = new XMLHttpRequest()
XHR.open(Method, Url, true)
XHR.addEventListener('load', () => {
resolve(XHR.responseText)
})
XHR.addEventListener('error'... | (function(target) {
'use strict'
function ajax(Url, Method, Contents) {
return new Promise(function(resolve, reject) {
const XHR = new XMLHttpRequest()
XHR.open(Method, Url, true)
XHR.addEventListener('load', () => {
resolve(XHR.responseText)
})
XHR.addEventListener('error'... |
DIsable dimmer for question files modal | import React from 'react'
import PropTypes from 'prop-types'
import { Card, Image, Modal } from 'semantic-ui-react'
const propTypes = {
files: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
})
),
}
const defaultProps = {
files: [],
}
c... | import React from 'react'
import PropTypes from 'prop-types'
import { Card, Image, Modal } from 'semantic-ui-react'
const propTypes = {
files: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
})
),
}
const defaultProps = {
files: [],
}
c... |
Remove React from bundle. Declared as peer dependency. 📦 | const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
mode: 'production',
entry: path.resolve(__dirname, 'lib/in... | const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
mode: 'production',
entry: path.resolve(__dirname, 'lib/in... |
Remove continuous test grunt task in favor of single-run test | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'Gruntfile.js',
'public/js/**/*.js',
'test/client/**/*.js',
'lib/**/*.js',
'app.js'
],
options: {
expr: true,
browser: tru... | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'Gruntfile.js',
'public/js/**/*.js',
'test/client/**/*.js',
'lib/**/*.js',
'app.js'
],
options: {
expr: true,
browser: tru... |
Create a collection for Forms | define(
['data/data', 'collections/v3/interactions', 'collections/v3/datasuitcases', 'models/v3/DataSuitcase', 'collections/v3/forms', 'models/v3/form'],
function (Backbone, InteractionCollection, DataSuitcaseCollection, DataSuitcase, FormCollection, Form) {
"use strict";
var Application = Backbone.Model.ex... | define(
['data/data', 'collections/v3/interactions', 'collections/v3/datasuitcases', 'models/v3/DataSuitcase', 'collections/v3/forms', 'models/v3/form'],
function (Backbone, InteractionCollection, DataSuitcaseCollection, DataSuitcase, FormCollection, Form) {
"use strict";
var Application = Backbone.Model.ex... |
Improve check for single by only issuing search once | <?php
class AlgorithmConnectedComponents extends Algorithm{
/**
*
* @var Graph
*/
private $graph;
/**
*
* @param Graph $graph
*/
public function __construct(Graph $graph){
$this->graph = $graph;
}
/**
* check whether this graph consist... | <?php
class AlgorithmConnectedComponents extends Algorithm{
/**
*
* @var Graph
*/
private $graph;
/**
*
* @param Graph $graph
*/
public function __construct(Graph $graph){
$this->graph = $graph;
}
/**
* check whether this graph consist... |
[FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date)) | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models
class StockMove(models.Model):... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models
class StockMove(models.Model):... |
Fix Config loading in DownloadCsv | <?php
namespace NemC\IP2LocLite\Commands;
use Illuminate\Console\Config,
Illuminate\Console\Command,
NemC\IP2LocLite\Services\IP2LocLiteService,
NemC\IP2LocLite\Exceptions\NotLoggedInResponseException,
NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException;
class DownloadCsvCommand extends Co... | <?php
namespace NemC\IP2LocLite\Commands;
use Illuminate\Console\Command,
NemC\IP2LocLite\Services\IP2LocLiteService,
NemC\IP2LocLite\Exceptions\NotLoggedInResponseException,
NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException;
class DownloadCsvCommand extends Command
{
protected $name = '... |
Change lint errors to warnings | module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {
'no-console': 'warn'
},
overrides: [
// node files
... | module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {
},
overrides: [
// node files
{
files: [
... |
Update closest match adapter docstring. | # -*- coding: utf-8 -*-
from fuzzywuzzy import fuzz
from .base_match import BaseMatchAdapter
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter logic adapter selects a known response
to an input by searching for a known statement that most closely
matches the input based on the L... | # -*- coding: utf-8 -*-
from fuzzywuzzy import fuzz
from .base_match import BaseMatchAdapter
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter logic adapter creates a response by
using fuzzywuzzy's process class to extract the most similar
response to the input. This adapter s... |
Add email field to subscription db model. | 'use strict';
const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository');
class SubscriptionRepository extends BaseRepository {
getSchemaDefinition() {
return {
subscriberId: {
type: String,
required: true,
index: true,
},
releaseNotesId: {
t... | 'use strict';
const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository');
class SubscriptionRepository extends BaseRepository {
getSchemaDefinition() {
return {
subscriberId: {
type: String,
required: true,
index: true,
},
releaseNotesId: {
t... |
Replace uneccessary .replace syntax in aria-labelledby attribute | // @flow
import React from 'react';
import type { Node } from 'react';
import classNames from 'classnames';
import { inject, observer } from 'mobx-react';
import { type Store } from '../accordionStore/accordionStore';
const defaultProps = {
className: 'accordion__body',
hideBodyClassName: 'accordion__body--hi... | // @flow
import React from 'react';
import type { Node } from 'react';
import classNames from 'classnames';
import { inject, observer } from 'mobx-react';
import { type Store } from '../accordionStore/accordionStore';
const defaultProps = {
className: 'accordion__body',
hideBodyClassName: 'accordion__body--hi... |
Use the env prefix setting | import os
import pydot
from kitchen.settings import STATIC_ROOT, REPO
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='digraph')
graph_nodes = {}
for node in nodes:
label = node['name'] + "\n" + "\n".join(
[role for role in node['role'... | import os
import pydot
from kitchen.settings import STATIC_ROOT
def generate_node_map(nodes):
"""Generates a graphviz nodemap"""
graph = pydot.Dot(graph_type='digraph')
graph_nodes = {}
for node in nodes:
label = node['name'] + "\n" + "\n".join(
[role for role in node['role'] if n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.