text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Move to hash history to allow refresh when on java server
// @flow import 'bootstrap/dist/css/bootstrap.css'; import createHistory from 'history/createHashHistory' import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import { createPersistor, getStoredState } from 'redux-pers...
// @flow import 'bootstrap/dist/css/bootstrap.css'; import createBrowserHistory from 'history/createBrowserHistory' import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import { createPersistor, getStoredState } from '...
Feature: Update request logger middleware implementation
<?php namespace PhalconUtils\Middleware; use Phalcon\Logger\Adapter\File; use Phalcon\Mvc\Micro; use PhalconUtils\Constants\Services; use PhalconUtils\Util\Logger; /** * Class LoggerMiddleware * @author Adeyemi Olaoye <yemi@cottacush.com> * @package App\Middleware */ class RequestLoggerMiddleware extends BaseMid...
<?php namespace PhalconUtils\Middleware; use Phalcon\Mvc\Micro; use PhalconUtils\Constants\Services; use PhalconUtils\Util\Logger; /** * Class LoggerMiddleware * @author Adeyemi Olaoye <yemi@cottacush.com> * @package App\Middleware */ class RequestLoggerMiddleware extends BaseMiddleware { public function bef...
Add tests requirements, fix console scripts definitions
from setuptools import find_packages, setup setup( name='ngx-task', version='0.2', description='Testimonial for candidates to show up their code-foo', author='Dmitry Shulyak', author_email='dmitri.shulyak@gmail.com', url='https://github.com/shudmi/ngx-task', classifiers=[ 'License :...
from setuptools import find_packages, setup setup( name='ngx-task', version='0.1', description='Testimonial for candidates to show up their code-foo', author='Dmitry Shulyak', author_email='dmitri.shulyak@gmail.com', url='https://github.com/shudmi/ngx-task', classifiers=[ 'License :...
Throw APIErrorException if there's a gametime endpoint error
<?php namespace TruckersMP\Models; use Carbon\Carbon; use TruckersMP\Exceptions\APIErrorException; class GameTimeModel { /** * @var Carbon */ public $time; /** * GameTimeModel constructor. * * @param array $response * @throws \Exception */ public function __constru...
<?php namespace TruckersMP\Models; use Carbon\Carbon; class GameTimeModel { /** * @var Carbon */ public $time; /** * GameTimeModel constructor. * * @param array $response * @throws \Exception */ public function __construct(array $response) { if ($respon...
Bump version for tag and release
# -*- coding: utf-8 -*- from setuptools import setup, find_packages install_requires = ( 'parsimonious', ) description = "Connexions project search query parsing library." with open('README.rst', 'r') as fb: readme = fb.read() long_description = readme setup( name='cnx-query-grammar', version='0...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages install_requires = ( 'parsimonious', ) description = "Connexions project search query parsing library." with open('README.rst', 'r') as fb: readme = fb.read() long_description = readme setup( name='cnx-query-grammar', version='0...
Fix comments in horizontal boxplot example
""" Horizontal boxplot with observations ==================================== _thumb: .7, .37 """ import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure with a logarithmic x axis f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the exa...
""" Horizontal boxplot with observations ==================================== _thumb: .7, .37 """ import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the example planets dataset planet...
Use immutable arg rather mutable arg Passing mutable objects as default args is a known Python pitfall. We'd better avoid this. This commit changes mutable default args with None, then use 'arg = arg or []'. Change-Id: If3a10d58e6cd792a2011c177c49d3b865a7421ff
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Use the right object for ACL validation
<?php /* * This file is part of the Sonata project. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\Security\Handler; use Symfony\Component\Se...
<?php /* * This file is part of the Sonata project. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\Security\Handler; use Symfony\Component\Se...
Use complete iri for annotation property declaration
package de.linkvt.bachelor.features.annotations.ontology.owl; import de.linkvt.bachelor.features.Feature; import de.linkvt.bachelor.features.FeatureCategory; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import or...
package de.linkvt.bachelor.features.annotations.ontology.owl; import de.linkvt.bachelor.features.Feature; import de.linkvt.bachelor.features.FeatureCategory; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import or...
Fix WOFF2 font so it passes OTS in Firefox
var supportsWoff2 = (function( win ){ if( !( "FontFace" in win ) ) { return false; } var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADwAAoAAAAAAiQAAACoAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAALAogOAE2AiQDBgsGAAQgBSAHIBuDAciO1EZ3I/mL5/+5/rfPnTt9/9Qa8H4cUUZxaRbh36LiKJoVh61XGzw6ufkp...
var supportsWoff2 = (function( win ){ if( !( "FontFace" in win ) ) { return false; } var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADcAAoAAAAAAggAAACWAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABk4ALAoUNAE2AiQDCAsGAAQgBSAHIBtvAcieB3aD8wURQ+TZazbRE9HvF5vde4KCYGhiCgq/NKPF0i6UIsZynbP+Xi9Ng+XLb...
Fix Fetch util reject case
var Promise = require('es6-promise').Promise; function fetch(options) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onload = function() { if(xhr.getResponseHeader('content-type').search('application/json') >= 0) { try { var response = JSON.par...
var Promise = require('es6-promise').Promise; function fetch(options) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onload = function() { if(xhr.getResponseHeader('content-type').search('application/json') >= 0) { try { var response = JSON.par...
Update tests and fix the failing test
from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() ...
from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() ...
Add JSON content type to authenticate headers
import Ember from 'ember'; import Base from 'ember-simple-auth/authenticators/base'; import Configuration from '../configuration'; const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember; export default Base.extend({ ajax: service(), init() { this._super(...arguments); this.serverT...
import Ember from 'ember'; import Base from 'ember-simple-auth/authenticators/base'; import Configuration from '../configuration'; const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember; export default Base.extend({ ajax: service(), init() { this._super(...arguments); this.serverT...
Improve error is API is dead
import fetch from 'isomorphic-fetch' import config from './config' async function fetchJson(url, options) { const response = await fetch(url, options) .catch(() => { throw new Error(`Could not fetch '${url}'.`)}) if (response.status < 200 || response.status >= 300) { throw new Error(`'${url}' returned th...
import fetch from 'isomorphic-fetch' import config from './config' async function fetchJson(url, options) { const response = await fetch(url, options) if (response.status < 200 || response.status >= 300) { throw new Error(`'${url}' returned the unexpected return code: '${response.status}'.`) } const data...
Add gcc 11.3 released on April 21, 2022
const ALL_COMPILERS = ['clang-3.8', 'clang-3.9', 'clang-4.0', 'clang-5.0', 'clang-6.0', 'clang-7.0', 'clang-7.1', 'clang-8.0', 'clang-9.0', 'clang-10.0', 'clang-11.0', 'clang-11.1', 'clang-12.0', 'clang-13.0', 'gcc-5.5', 'gcc-6.4', 'gcc-6.5', 'gcc-7.2', 'gcc-7.3', 'gcc-7.4', 'gcc-7.5', 'gcc-8.1', 'gcc-8...
const ALL_COMPILERS = ['clang-3.8', 'clang-3.9', 'clang-4.0', 'clang-5.0', 'clang-6.0', 'clang-7.0', 'clang-7.1', 'clang-8.0', 'clang-9.0', 'clang-10.0', 'clang-11.0', 'clang-11.1', 'clang-12.0', 'clang-13.0', 'gcc-5.5', 'gcc-6.4', 'gcc-6.5', 'gcc-7.2', 'gcc-7.3', 'gcc-7.4', 'gcc-7.5', 'gcc-8.1', 'gcc-8...
CLOUDSTACK-9266: Make deleting static routes in private gw work
# -- coding: utf-8 -- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "Li...
# -- coding: utf-8 -- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "Li...
Return image type of file in api
from rest_framework import serializers from grandchallenge.cases.models import Image, ImageFile class ImageFileSerializer(serializers.ModelSerializer): class Meta: model = ImageFile fields = ("pk", "image", "file", "image_type") class ImageSerializer(serializers.ModelSerializer): files = Im...
from rest_framework import serializers from grandchallenge.cases.models import Image, ImageFile class ImageFileSerializer(serializers.ModelSerializer): class Meta: model = ImageFile fields = ("pk", "image", "file") class ImageSerializer(serializers.ModelSerializer): files = ImageFileSeriali...
Remove spaces in user names. - Also ensure multiple consecutive dashes are replaced by just one.
package com.uwetrottmann.trakt.v2.entities; public class Username { /** * Special user name for the current user (determined by auth data). */ public static final Username ME = new Username("me"); private String encodedUsername; /** * Encodes the username returned from trakt so it is ...
package com.uwetrottmann.trakt.v2.entities; public class Username { /** * Special user name for the current user (determined by auth data). */ public static final Username ME = new Username("me"); private String encodedUsername; /** * Encodes the username returned from trakt so it is ...
Allow filtering for tasks without due date
<?php namespace Kanboard\Filter; use Kanboard\Core\Filter\FilterInterface; use Kanboard\Model\TaskModel; /** * Filter tasks by due date * * @package filter * @author Frederic Guillot */ class TaskDueDateFilter extends BaseDateFilter implements FilterInterface { /** * Get search attribute * *...
<?php namespace Kanboard\Filter; use Kanboard\Core\Filter\FilterInterface; use Kanboard\Model\TaskModel; /** * Filter tasks by due date * * @package filter * @author Frederic Guillot */ class TaskDueDateFilter extends BaseDateFilter implements FilterInterface { /** * Get search attribute * *...
Fix flake8 E113 unexpected indentation
import pickle from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Pickle instances ######################################## class TestPickle(SQLObject): question = StringCol() answer = IntCol() test_question = 'The Ulimate Question of Life, the Universe an...
import pickle from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Pickle instances ######################################## class TestPickle(SQLObject): question = StringCol() answer = IntCol() test_question = 'The Ulimate Question of Life, the Universe an...
Increase keepalive timeout to 5 minutes.
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
Fix usage of fs-extra (should've been fs-extra-promise)
import fs from 'fs-extra-promise'; import path from 'path'; import app from 'app'; import BaseAutoLauncher from 'browser/components/auto-launcher/base'; import files from 'common/utils/files'; const autoStartDir = path.join(app.getPath('home'), '.config', 'autostart'); const desktopFilePath = path.join(autoStartDir, ...
import fs from 'fs-extra'; import path from 'path'; import app from 'app'; import BaseAutoLauncher from 'browser/components/auto-launcher/base'; import files from 'common/utils/files'; const autoStartDir = path.join(app.getPath('home'), '.config', 'autostart'); const desktopFilePath = path.join(autoStartDir, global.m...
Add as a dependency (minification)
(function () { 'use strict'; /*global angular, Blob, URL */ angular.module('angular.img', [ ]).directive('httpSrc', ['$http', function ($http) { return { link: function ($scope, elem, attrs) { function revokeObjectURL() { if ($scope.objectURL) { URL.revokeObjectURL($scope.objectURL); } ...
(function () { 'use strict'; /*global angular, Blob, URL */ angular.module('angular.img', [ ]).directive('httpSrc', function ($http) { return { link: function ($scope, elem, attrs) { function revokeObjectURL() { if ($scope.objectURL) { URL.revokeObjectURL($scope.objectURL); } } $...
Make the id argument optional
// Creates an HD canvas element on page and // returns a reference to the element var createCanvasElement = function (width, height, id, insertAfter) { // Creates a scaled-up canvas based on the device's // resolution, then displays it properly using styles function createHDCanvas (ratio) { var canvas = docum...
// Creates an HD canvas element on page and // returns a reference to the element var createCanvasElement = function (width, height, id, insertAfter) { // Creates a scaled-up canvas based on the device's // resolution, then displays it properly using styles function createHDCanvas (ratio) { var canvas = docum...
Change testing database to sqlite
import os class Config(object): """Parent configuration class.""" DEBUG = False CSRF_ENABLED = True SECRET_KEY = os.getenv('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') class DevelopmentConfig(Config): """Configurations for Development.""" DEBUG = True SQLALCHEMY_...
import os class Config(object): """Parent configuration class.""" DEBUG = False CSRF_ENABLED = True SECRET_KEY = os.getenv('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') class DevelopmentConfig(Config): """Configurations for Development.""" DEBUG = True SQLALCHEMY_...
Use some Guava .net classes to clean up code a little
/* * Copyright Myrrix 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 wr...
/* * Copyright Myrrix 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 wr...
Mark Equal function as lazy
package builtins import "github.com/coel-lang/coel/src/lib/core" // Equal checks if all arguments are equal or not, and returns true if so or false otherwise. var Equal = core.NewLazyFunction( core.NewSignature(nil, nil, "args", nil, nil, ""), func(ts ...*core.Thunk) core.Value { l := ts[0] if v := checkEmptyL...
package builtins import "github.com/coel-lang/coel/src/lib/core" // Equal checks if all arguments are equal or not, and returns true if so or false otherwise. var Equal = core.NewStrictFunction( core.NewSignature(nil, nil, "args", nil, nil, ""), func(ts ...*core.Thunk) core.Value { l := ts[0] if v := checkEmpt...
Use workshopper commands to run server mode
#!/usr/bin/env node import path from 'path'; import workshopper from 'workshopper'; import updateNotifier from 'update-notifier'; import Server from './lib/Server'; import pkg from '../package.json'; updateNotifier({pkg: pkg}).notify(); workshopper({ name: 'testdrived3', appDir: __dirname, languages: ['e...
#!/usr/bin/env node import path from 'path'; import workshopper from 'workshopper'; import updateNotifier from 'update-notifier'; import Server from './lib/Server'; import pkg from '../package.json'; updateNotifier({pkg: pkg}).notify(); const serverMode = process.argv[2] === 'server'; if (serverMode) { const su...
Add status back to my reports
import React from 'react' import Page from 'components/Page' import Breadcrumbs from 'components/Breadcrumbs' import ReportTable from 'components/ReportTable' import API from 'api' import {Report} from 'models' export default class ReportsIndex extends Page { constructor(props) { super(props) this.state = {repo...
import React from 'react' import Page from 'components/Page' import Breadcrumbs from 'components/Breadcrumbs' import ReportTable from 'components/ReportTable' import API from 'api' import {Report} from 'models' export default class ReportsIndex extends Page { constructor(props) { super(props) this.state = {repo...
Fix how we are reading user name
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.F...
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.F...
Fix escaping for stricter php7.3.
<?php declare(strict_types = 1); namespace Soliant\SimpleFM\Client\ResultSet\Transformer; use Litipk\BigNumbers\Decimal; final class NumberTransformer { public function __invoke(string $value) { $cleanedValue = preg_replace_callback( '(^[^\d-\.]*(-?)([^.]*)(.?)(.*)$)', functio...
<?php declare(strict_types = 1); namespace Soliant\SimpleFM\Client\ResultSet\Transformer; use Litipk\BigNumbers\Decimal; final class NumberTransformer { public function __invoke(string $value) { $cleanedValue = preg_replace_callback( '(^[^\d-.]*(-?)([^.]*)(.?)(.*)$)', function...
Add simple endpoint for form submission
import flask import config app = flask.Flask(__name__) @app.route('/') @app.route('/dashboard') def render_dashboard(): return flask.render_template('dashboard.html') @app.route('/new') def render_new_procedure_form(): return flask.render_template('new_procedure.html') # Endpoint for new opportunity form...
import flask import config app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('dashboard.html') @app.route('/new') def new(): return flask.render_template('new_procedure.html') @app.route('/sms', methods=['POST']) def receive_sms(): print(str.format("Received SMS: \...
Set Texture minification/magnification filters to Linear This improves the quality of textures that need to be rendered at a smaller size.
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtGui import QOpenGLTexture, QImage from UM.View.GL.Texture import Texture from UM.View.GL.OpenGL import OpenGL ## Texture subclass using PyQt for the OpenGL implementation. class QtTexture(Texture): de...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtGui import QOpenGLTexture, QImage from UM.View.GL.Texture import Texture from UM.View.GL.OpenGL import OpenGL ## Texture subclass using PyQt for the OpenGL implementation. class QtTexture(Texture): de...
Add comment to send func
import { HUB } from './hub'; import config from './config'; export function post (apiUrl, data) { const payload = JSON.stringify(data); const url = config.API_ROOT + apiUrl; GM_xmlhttpRequest({ method: 'POST', url: url, headers: { 'Content-Type': 'application/json', ...
import { HUB } from './hub'; import config from './config'; export function post (apiUrl, data) { const payload = JSON.stringify(data); const url = config.API_ROOT + apiUrl; GM_xmlhttpRequest({ method: 'POST', url: url, headers: { 'Content-Type': 'application/json', ...
Remove class namespace prefix and declare on top
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use App\Business; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In additio...
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as th...
Add a bit of logging
/* eslint-env mocha */ const assert = require('assert') const cm = require('cucumber-messages').io.cucumber.messages const Gherkin = require('../src/Gherkin') describe('Gherkin', () => { it('parses gherkin from the file system', async () => { const messages = await streamToArray( Gherkin.fromPaths(['testda...
/* eslint-env mocha */ const assert = require('assert') const cm = require('cucumber-messages').io.cucumber.messages const Gherkin = require('../src/Gherkin') describe('Gherkin', () => { it('parses gherkin from the file system', async () => { const messages = await streamToArray( Gherkin.fromPaths(['testda...
Add unit test for LoginToken model
"""accounts app unittests """ from django.test import TestCase from django.contrib.auth import get_user_model from accounts.models import LoginToken TEST_EMAIL = 'newvisitor@example.com' class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(se...
"""accounts app unittests """ from django.test import TestCase from django.contrib.auth import get_user_model class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should response with the welcome page template. ...
Swap find_packages for a manual list This is required to support PEP420 namespace packages.
"""Setuptools configuration for engine.""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='asyncdef.engine', version='0.1.0', url='https://github.com/asyncdef/engine', description='Core event l...
"""Setuptools configuration for engine.""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='asyncdef.engine', version='0.1.0', url='https://github.com/asyncdef/engine', description='Core event l...
Make csv reader binary safe
<?php declare(strict_types=1); namespace Phpml\Dataset; use Phpml\Exception\DatasetException; class CsvDataset extends ArrayDataset { /** * @param string $filepath * @param int $features * @param bool $headingRow * * @throws DatasetException */ public function __construct(...
<?php declare(strict_types=1); namespace Phpml\Dataset; use Phpml\Exception\DatasetException; class CsvDataset extends ArrayDataset { /** * @param string $filepath * @param int $features * @param bool $headingRow * * @throws DatasetException */ public function __construct(...
Add a constructor of component
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may...
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may...
Write to png file in binary mode
import os import base64 import tempfile import subprocess def convert_to_pdf(post): path = tempfile.mkdtemp() pagenr = 1 while True: data = post.get('page_%s' % pagenr) if data is None: break if not data.startswith('data:image/png;base64,'): continue ...
import os import base64 import tempfile import subprocess def convert_to_pdf(post): path = tempfile.mkdtemp() pagenr = 1 while True: data = post.get('page_%s' % pagenr) if data is None: break if not data.startswith('data:image/png;base64,'): continue ...
Move message interval into a global constant
/** * lib/app.js: main module for `bonta` CLI utility * * Copyright 2015, Sudaraka Wijesinghe <sudaraka@sudaraka.org> * * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it and/or modify * it under the terms of the BSD 2-clause License. See the LICENSE...
/** * lib/app.js: main module for `bonta` CLI utility * * Copyright 2015, Sudaraka Wijesinghe <sudaraka@sudaraka.org> * * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it and/or modify * it under the terms of the BSD 2-clause License. See the LICENSE...
lisa: Remove Python < 3.6 version check Since Python >= 3.6 is now mandatory, remove the check and the warning.
#! /usr/bin/env python3 import warnings import os import sys from lisa.version import __version__ # Raise an exception when a deprecated API is used from within a lisa.* # submodule. This ensures that we don't use any deprecated APIs internally, so # they are only kept for external backward compatibility purposes. ...
#! /usr/bin/env python3 import warnings import os import sys from lisa.version import __version__ # Raise an exception when a deprecated API is used from within a lisa.* # submodule. This ensures that we don't use any deprecated APIs internally, so # they are only kept for external backward compatibility purposes. ...
Connect person to user account
# Django # Third-Party from django.db.models.signals import pre_delete from django.db.models.signals import pre_save from django.dispatch import receiver from django.conf import settings # Local from .models import User from .tasks import activate_user from .tasks import delete_account @receiver(pre_delete, sender=U...
# Django # Third-Party from django.db.models.signals import pre_delete from django.db.models.signals import pre_save from django.dispatch import receiver from django.conf import settings # Local from .models import User from .tasks import delete_account @receiver(pre_delete, sender=User) def user_pre_delete(sender, ...
Comment out the SemesterDetail log
import * as React from 'react' import * as Immutable from 'immutable' import {State} from 'react-router' import {isCurrentSemester} from 'app/helpers/isCurrent' let SemesterDetail = React.createClass({ mixins: [State], propTypes: { student: React.PropTypes.object.isRequired, }, getInitialState() { return { ...
import * as React from 'react' import * as Immutable from 'immutable' import {State} from 'react-router' import {isCurrentSemester} from 'app/helpers/isCurrent' let SemesterDetail = React.createClass({ mixins: [State], propTypes: { student: React.PropTypes.object.isRequired, }, getInitialState() { return { ...
Make sure components receive all children properly
import Component from '../Component'; export default function patchMithril(global) { const mo = global.m; const m = function(comp, ...args) { if (comp.prototype && comp.prototype instanceof Component) { return comp.component(args[0], args.slice(1)); } const node = mo.apply(this, arguments); ...
import Component from '../Component'; export default function patchMithril(global) { const mo = global.m; const m = function(comp, ...args) { if (comp.prototype && comp.prototype instanceof Component) { return comp.component(...args); } const node = mo.apply(this, arguments); if (node.attr...
Fix TimedEvent sets GUID twice TBR=nduca@chromium.org BUG= Review URL: https://codereview.appspot.com/12746044 git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@896 0e6d7f2b-9903-5b78-7403-59d27f066143
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; base.require('base.guid'); base.require('tracing.trace_model.event'); /** * @fileoverview Provides the TimedEvent class. */ base.exp...
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; base.require('base.guid'); base.require('tracing.trace_model.event'); /** * @fileoverview Provides the TimedEvent class. */ base.exp...
Add internal implementation to increase performance
'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var replace = require( '@stdlib/string/replace' ); // VARIABLES // // The following regular expression should suffice to polyfill (most?) all environments. var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029...
'use strict'; // MODULES // var ltrim = require( '@stdlib/string/left-trim' ); var rtrim = require( '@stdlib/string/right-trim' ); // MAIN // /** * Trim whitespace characters from beginning and end of a string. * * @param {string} str - input string * @throws {TypeError} must provide a string primitive * @returns ...
Comment out python3 classifier for now.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='slugger', version='0.2dev', description=('Slugging done right. Tries to support close to 300' 'languages.'), long_descriptio...
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='slugger', version='0.2dev', description=('Slugging done right. Tries to support close to 300' 'languages.'), long_descriptio...
Fix travis error with SQLITE_LIMIT_VARIABLE_NUMBER
import sqlite3 def max_sql_variables(): """Get the maximum number of arguments allowed in a query by the current sqlite3 implementation. Returns: int: SQLITE_MAX_VARIABLE_NUMBER """ db = sqlite3.connect(':memory:') cur = db.cursor() cur.execute('CREATE TABLE t (test)') low, h...
import sqlite3 def max_sql_variables(): """Get the maximum number of arguments allowed in a query by the current sqlite3 implementation. Returns: int: SQLITE_MAX_VARIABLE_NUMBER """ db = sqlite3.connect(':memory:') cur = db.cursor() cur.execute('CREATE TABLE t (test)') low, h...
Handle bad image files in example
import face_recognition # Load the jpg files into numpy arrays biden_image = face_recognition.load_image_file("biden.jpg") obama_image = face_recognition.load_image_file("obama.jpg") unknown_image = face_recognition.load_image_file("obama2.jpg") # Get the face encodings for each face in each image file # Since there ...
import face_recognition # Load the jpg files into numpy arrays biden_image = face_recognition.load_image_file("biden.jpg") obama_image = face_recognition.load_image_file("obama.jpg") unknown_image = face_recognition.load_image_file("obama2.jpg") # Get the face encodings for each face in each image file # Since there ...
Add missing semicolon for ES7
'use strict'; import React, { Platform, StyleSheet, View, } from 'react-native'; import Layout from './Layout'; export default class TabBar extends React.Component { static propTypes = { ...View.propTypes, shadowStyle: View.propTypes.style, }; render() { return ( <View {...this.props} ...
'use strict'; import React, { Platform, StyleSheet, View, } from 'react-native'; import Layout from './Layout'; export default class TabBar extends React.Component { static propTypes = { ...View.propTypes, shadowStyle: View.propTypes.style, } render() { return ( <View {...this.props} s...
Use module aifc instead of module aiff.
import sys import readcd import aifc import AL import CD Error = 'cdaiff.Error' def writeaudio(a, type, data): a.writeframesraw(data) def main(): if len(sys.argv) > 1: a = aifc.open(sys.argv[1], 'w') else: a = aifc.open('@', 'w') a.setsampwidth(AL.SAMPLE_16) a.setnchannels(AL.STEREO) a.setframerate(AL.RATE...
import sys import readcd import aiff import AL import CD Error = 'cdaiff.Error' def writeaudio(a, type, data): a.writesampsraw(data) def main(): if len(sys.argv) > 1: a = aiff.Aiff().init(sys.argv[1], 'w') else: a = aiff.Aiff().init('@', 'w') a.sampwidth = AL.SAMPLE_16 a.nchannels = AL.STEREO a.samprate = ...
Simplify with forEach instead of for..in
"use strict"; var forge = require("node-forge"); var APNCertificate = require("./APNCertificate"); function apnCertificateFromPem(certData) { if (!certData) { return null; } var pemMessages; try { pemMessages = forge.pem.decode(certData); } catch (e) { if (e.message.match("Invalid PEM formatted message....
"use strict"; var forge = require("node-forge"); var APNCertificate = require("./APNCertificate"); function apnCertificateFromPem(certData) { if (!certData) { return null; } var pemMessages; try { pemMessages = forge.pem.decode(certData); } catch (e) { if (e.message.match("Invalid PEM formatted message....
Fix relative path for plugin system
export default { data () { return { plugins: { list: ['Invoice'], loaded: [] } } }, methods: { loadPlugin (name) { if (this.plugins.loaded.indexOf(name) > -1) { return true } if (this.plugins.list.indexOf(name) < 0) { return false } ...
export default { data () { return { plugins: { list: ['Invoice'], loaded: [] } } }, methods: { loadPlugin (name) { if (this.plugins.loaded.indexOf(name) > -1) { return true } if (this.plugins.list.indexOf(name) < 0) { return false } ...
Apply YQL change from GF-9695 and GF-9700 to JSONP sample too Enyo-DCO-1.1-Signed-Off-By: Ben Combee (ben.combee@lge.com)
enyo.kind({ name: "enyo.sample.JsonpSample", kind: "FittableRows", classes: "enyo-fit jsonp-sample", components: [ {kind: "FittableColumns", classes:"onyx-toolbar-inline", components: [ {content: "YQL: "}, {kind: "onyx.Input", name:"query", fit:true, value:'select * from weather.forecast where woeid in (sel...
enyo.kind({ name: "enyo.sample.JsonpSample", kind: "FittableRows", classes: "enyo-fit jsonp-sample", components: [ {kind: "FittableColumns", classes:"onyx-toolbar-inline", components: [ {content: "YQL: "}, {kind: "onyx.Input", name:"query", fit:true, value:'select * from upcoming.events where woeid in (sele...
Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- savin...
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == ...
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == ...
Increment route count on route
module.exports = (function() { function chimneypot(opts) { if (!opts || !isOptionsValid(opts)) { throw new Error("Required options: port, path, secret"); } this.options = { port: opts.port, path: opts.path, secret: opts.secret }; this.routeCount = 0; } function isOpt...
module.exports = (function() { function chimneypot(opts) { if (!opts || !isOptionsValid(opts)) { throw new Error("Required options: port, path, secret"); } this.options = { port: opts.port, path: opts.path, secret: opts.secret }; this.routeCount = 0; } function isOpt...
Add test for null date.
package uk.ac.ebi.quickgo.annotation.download.converter.helpers; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.function.Function; /** * A home for the logic to format dates into Strings. * * @author Tony Wardell * Date: 09/04/2018 * Time: 14:54 * Cre...
package uk.ac.ebi.quickgo.annotation.download.converter.helpers; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.function.Function; /** * A home for the logic to format dates into Strings. * * @author Tony Wardell * Date: 09/04/2018 * Time: 14:54 * Cre...
refactor(app-tests): Merge fixture tests to reduce live servers and time
""" Test fixtures. :copyright: (c) 2017 Derek M. Frank :license: MPL-2.0 """ from flask import Flask # type: ignore def test_simple_app(app): """Verify basic application.""" assert isinstance(app, Flask) def test_simple_config(config): """Verify basic application configuration.""" assert isinstan...
""" Test fixtures. :copyright: (c) 2017 Derek M. Frank :license: MPL-2.0 """ from flask import Flask # type: ignore def test_simple_app(app): """Verify basic application.""" assert isinstance(app, Flask) def test_simple_config(config): """Verify basic application configuration.""" assert isinstan...
Remove 'public' for interface methods + fix formatting issues
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.log; import java.util.logging.Level; /** * This is the interface for controlling the log level of a * component logger. This hides the actual controlling * mechanism. * * @aut...
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. /** * This is the interface for controlling the log level of a * component logger. This hides the actual controlling * mechanism. * * @author arnej27959 * */ /** * @author arnej27959 **/ pac...
Set default component group view to 1
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Sup...
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Sup...
Simplify CORS model and improve wording
# coding: utf-8 from django.db import models from django.utils.translation import ugettext_lazy as _ class CorsModel(models.Model): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match `request.META.get('HTTP_ORIGIN')` """ cors = models.CharField( ...
# coding: utf-8 from django.db import models from django.utils.translation import ugettext_lazy as _ def _set_cors_field_options(name, bases, attrs): cls = type(name, bases, attrs) # The `cors` field is already defined by `AbstractCorsModel`, but let's # help folks out by giving it a more descriptive name...
Add result catch, better logging
'use strict' const _ = require('lodash') const Promise = require('bluebird') var arr = [] module.exports = function loadAllPages (callFx, opts) { opts['page'] = opts.page || 1 return Promise .resolve(callFx(opts)) .then((result) => { arr.push(result) if (result && _.isFunction(result.nextPage)...
'use strict' const _ = require('lodash') const Promise = require('bluebird') var arr = [] module.exports = function loadAllPages (callFx, opts) { opts['page'] = opts.page || 1 return Promise .resolve(callFx(opts)) .then((result) => { arr.push(result) if (_.isFunction(result.nextPage)) { ...
Reset values of external link add-on to default when deleted.
# -*- coding: utf-8 -*- from modularodm import fields from modularodm.validators import ( URLValidator, MinValueValidator, MaxValueValidator ) from modularodm.exceptions import ValidationValueError from framework.mongo.utils import sanitized from website.addons.base import AddonNodeSettingsBase class ForwardNo...
# -*- coding: utf-8 -*- from modularodm import fields from modularodm.validators import ( URLValidator, MinValueValidator, MaxValueValidator ) from modularodm.exceptions import ValidationValueError from framework.mongo.utils import sanitized from website.addons.base import AddonNodeSettingsBase class ForwardNo...
Fix a few unlikely issues with empty trade iterations (Binance)
const moment = require('moment'); const util = require('../../core/util.js'); const _ = require('lodash'); const log = require('../../core/log'); var config = util.getConfig(); var dirs = util.dirs(); var Fetcher = require(dirs.exchanges + 'binance'); util.makeEventEmitter(Fetcher); var end = false; var done = fals...
const moment = require('moment'); const util = require('../../core/util.js'); const _ = require('lodash'); const log = require('../../core/log'); var config = util.getConfig(); var dirs = util.dirs(); var Fetcher = require(dirs.exchanges + 'binance'); util.makeEventEmitter(Fetcher); var end = false; var done = fals...
Use class instead of helper. Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Database\Console\Migrations; use Illuminate\Support\Collection; trait Packages { /** * The path to the packages directory (vendor). * * @var string */ protected $packagePath; /** * Set package path. * * @param string $packagePath * ...
<?php namespace Orchestra\Database\Console\Migrations; trait Packages { /** * The path to the packages directory (vendor). * * @var string */ protected $packagePath; /** * Set package path. * * @param string $packagePath * * @return $this */ public ...
Throw exception when trying to access undefined property
<?php namespace Fathomminds\Rest; use Fathomminds\Rest\Contracts\ISchema; use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory; use Fathomminds\Rest\Exceptions\RestException; abstract class Schema implements ISchema { public function __construct($object = null) { if ($object === null) { ...
<?php namespace Fathomminds\Rest; use Fathomminds\Rest\Contracts\ISchema; use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory; use Fathomminds\Rest\Exceptions\RestException; abstract class Schema implements ISchema { public function __construct($object = null) { if ($object === null) { ...
Remove as fetch ones for now
const fs = require('fs') const path = require('path') const promisify = require('util').promisify const writeFile = promisify(fs.writeFile) const globby = require('globby') ;(async () => { const files = await globby('./dist/**/*.{css,mjs}') const headers = [] for (const file of files) { const relative = pat...
const fs = require('fs') const path = require('path') const promisify = require('util').promisify const writeFile = promisify(fs.writeFile) const globby = require('globby') ;(async () => { const files = await globby('./dist/**/*.{css,mjs}') const headers = [' Link: </content/posts/index.json>; rel=preload; as=fet...
Correct handling of broken references
var escape = require('escape-latex'); var quotes = require('../replace-quotes'); var preprocess = function(input) { return escape(quotes(input)); }; var blankLine = '{\\leavevmode \\vbox{\\hrule width5\\parindent}}'; module.exports = function run(element, numberStyle, conspicuous) { if (typeof element === 'strin...
var escape = require('escape-latex'); var quotes = require('../replace-quotes'); var preprocess = function(input) { return escape(quotes(input)); }; var blankLine = '{\\leavevmode \\vbox{\\hrule width5\\parindent}}'; module.exports = function run(element, numberStyle, conspicuous) { if (typeof element === 'strin...
Remove diacritics from search terms
import React from 'react'; import { Query } from 'react-apollo'; import { Switch, Route } from 'react-router-dom'; import { remove as removeDiacritics } from 'diacritics'; import parseRoute from 'react/util/parseRoute'; import searchUiStateQuery from 'apps/search/queries/searchUiState'; import SearchPage from 'react/...
import React from 'react'; import { Query } from 'react-apollo'; import { Switch, Route } from 'react-router-dom'; import parseRoute from 'react/util/parseRoute'; import searchUiStateQuery from 'apps/search/queries/searchUiState'; import SearchPage from 'react/pages/search/SearchPage'; export default () => ( <Swit...
Fix the build: latest bnd includes the most recent repoindex Signed-off-by: Ferry Huberts <66e11f9f5d965b69497c7e73d5e808f8b13c1218@pelagic.nl>
package bndtools; import java.io.File; import java.io.OutputStream; import java.io.Writer; import java.util.Map; import java.util.Set; import org.osgi.framework.BundleContext; import org.osgi.service.indexer.ResourceIndexer; import org.osgi.util.tracker.ServiceTracker; public class ResourceIndexerTracker extends Ser...
package bndtools; import java.io.File; import java.io.OutputStream; import java.io.Writer; import java.util.Map; import java.util.Set; import org.osgi.framework.BundleContext; import org.osgi.service.indexer.ResourceIndexer; import org.osgi.util.tracker.ServiceTracker; public class ResourceIndexerTracker extends Ser...
:bug: Fix SSR when importing svg Babel-register & Node doesn’t know how to handle `.svg` files
import path from 'path'; import Express from 'express'; import compression from 'compression'; import bodyParser from 'body-parser'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import webpackConfig from '../webpack....
import path from 'path'; import Express from 'express'; import compression from 'compression'; import bodyParser from 'body-parser'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import webpackConfig from '../webpack....
Fix incorrect require() path in Marked renderer
var escape = require('./util/escape') var format = require('string-template'); var hljs = require('highlight.js'); var heading = require('./util/writeHeading'); var marked = require('marked'); var multiline = require('multiline'); var mdRenderer = new marked.Renderer(); var HTML_EXAMPLE_TEMPLATE = mul...
var escape = require('./util/escape') var format = require('string-template'); var hljs = require('highlight.js'); var heading = require('./util/writeHeading'); var marked = require('marked'); var multiline = require('multiline'); var mdRenderer = new marked.Renderer(); var HTML_EXAMPLE_TEMPLATE = mul...
Allow circular references in dust templates.
var dust = require('dustjs-linkedin'); var _ = require('lodash'); dust.compiled = function(template) { return this.template(template).compiled; }; dust.src = function(template) { return this.template(template).src; }; dust.dependencies = function(template) { var all = [], check = [ dust.template(template).depen...
var dust = require('dustjs-linkedin'); var _ = require('lodash'); dust.compiled = function(template) { return this.template(template).compiled; }; dust.src = function(template) { return this.template(template).src; }; dust.dependencies = function(template) { var all = [], check = [ dust.template(template).depen...
Fix docstring, remove unused import
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFac...
# -*- coding: utf-8 -*- """Factory boy factories for the Box addon.""" import mock from datetime import datetime from dateutil.relativedelta import relativedelta from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.add...
Make sure all fit feedmes get made
#!/usr/bin/env python from glob import glob import os import re def make_feedmes(): # One-time script # Used to convert all the fit*.galfit files to fit*.diff ids = glob('*/') for id in ids: os.chdir(id) feedmes = glob('fit*diff') # output starting models for f in feedm...
#!/usr/bin/env python from glob import glob import os import re def make_feedmes(): # One-time script # Used to convert all the fit*.galfit files to fit*.diff ids = glob('*/') for id in ids: os.chdir(id) feedmes = glob('fit*diff') # output starting models for f in feedm...
Fix URLs for login/logout, and password changes.
import django.contrib.auth.views as auth_views from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles import views admin.autodiscover() urlpatterns = [ url(r'^login/*$', auth_views.Login...
import django.contrib.auth.views as auth_views from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles import views admin.autodiscover() urlpatterns = [ url(r'^login/*$', auth_views.Login...
Move process scheduling out of main.
# -*- coding: utf-8 -*- import schedule from feed import load_feed from twitter import send_queued_tweet import time import os RSS_FEED_LIST = os.environ['RSS_FEED_LIST'] LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS']) SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS']) def parse_feed...
# -*- coding: utf-8 -*- import schedule from feed import load_feed from twitter import send_queued_tweet import time import os RSS_FEED_LIST = os.environ['RSS_FEED_LIST'] LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS']) SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS']) def parse_feed...
Revert last commit and tiggers _count_attended_registration method when one registrations.state changes
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api class ResPartn...
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api class ResPartn...
Fix non-visible CREATOR in sample app
package nz.bradcampbell.paperparcel.java7example; import nz.bradcampbell.paperparcel.AccessorName; import nz.bradcampbell.paperparcel.PaperParcel; import nz.bradcampbell.paperparcel.PaperParcelable; import nz.bradcampbell.paperparcel.TypeAdapters; import java.util.Date; @PaperParcel @TypeAdapters(DateTypeAdapter.cla...
package nz.bradcampbell.paperparcel.java7example; import nz.bradcampbell.paperparcel.AccessorName; import nz.bradcampbell.paperparcel.PaperParcel; import nz.bradcampbell.paperparcel.PaperParcelable; import nz.bradcampbell.paperparcel.TypeAdapters; import java.util.Date; @PaperParcel @TypeAdapters(DateTypeAdapter.cla...
Improve JSON Tree directive code
(function(kopf, JSONTree) { "use strict"; kopf.directive('kopfJsonTree',function($sce) { var directive = { restrict: 'E', template:'<div class="json-tree" ng-bind-html="result"></div>', scope: { kopfBind: '=' }, link: function(scope, element, attrs, requires){ sco...
(function(kopf, JSONTree) { "use strict"; kopf.directive('kopfJsonTree',function() { var directive = { restrict: 'E', template:'<div class="json-tree"></div>', link: function(scope, element, attrs, requires){ var scopeAttr = attrs.kopfBind; if(scopeAttr) { scope.$watc...
Fix the encode url for the browser in InfoPackage
import got from 'got' import semver from 'semver' import validate from 'validate-npm-package-name' const exp = /^((@[^@\/]+)\/)?([^@\/]+)(@([^@\/]+))?$/ // Rename for PackageInfo export default class InfoPackage { constructor(info) { const match = exp.exec(info) if (!info || !match) { this.isValid = f...
import got from 'got' import semver from 'semver' import querystring from 'querystring' import validate from 'validate-npm-package-name' const exp = /^((@[^@\/]+)\/)?([^@\/]+)(@([^@\/]+))?$/ // Rename for PackageInfo export default class InfoPackage { constructor(info) { const match = exp.exec(info) if (!in...
Add channel root on set context data, sent to template
# -*- coding: utf-8 -*- from django.utils import timezone from opps.articles.models import ArticleBox, Article def set_context_data(self, SUPER, **kwargs): context = super(SUPER, self).get_context_data(**kwargs) article = Article.objects.filter( site=self.site, channel_long_slug__in=self.cha...
# -*- coding: utf-8 -*- from django.utils import timezone from opps.articles.models import ArticleBox, Article def set_context_data(self, SUPER, **kwargs): context = super(SUPER, self).get_context_data(**kwargs) article = Article.objects.filter( site=self.site, channel_long_slug__in=self.cha...
Rename task. Add templates folder to watch
var gulp = require('gulp'), scssLint = require('sass-lint'), sass = require('gulp-sass'), sassdoc = require('sassdoc'); gulp.task('watch', function() { gulp.watch(['tests/*.scss', 'sass/**/*.scss', 'templates/project/*.scss'], ['_build']); }); gulp.task('doc', function() { return gulp.src('sass/**...
var gulp = require('gulp'), scssLint = require('sass-lint'), sass = require('gulp-sass'), sassdoc = require('sassdoc'); gulp.task('watch', function() { gulp.watch(['tests/*.scss', 'sass/**/*.scss'], ['_build']); }); gulp.task('sassdoc', function() { return gulp.src('sass/**/*.scss') .pipe(...
Use jQuery nomenclature (event => eventType)
/** * Events. * * @mixin * @namespace Bolt.events * * @param {Object} bolt - The Bolt module. */ (function (bolt) { 'use strict'; /* * Bolt.events mixin container. * * @private * @type {Object} */ var events = {}; /* * Event broker object. * * @private ...
/** * Events. * * @mixin * @namespace Bolt.events * * @param {Object} bolt - The Bolt module. */ (function (bolt) { 'use strict'; /* * Bolt.events mixin container. * * @private * @type {Object} */ var events = {}; /* * Event broker object. * * @private ...
Test fix for db.blob.dir changes
_test = { setup: function() { app.log("Application Config Setup"); }, teardown: function() { app.log("Application Config Teardown"); }, app_settings_suite: { setup: function() { app.log("app_settings_suite setup"); }, teardown: function() { app.log("app_settings_suite teardown"); }, ...
_test = { setup: function() { app.log("Application Config Setup"); }, teardown: function() { app.log("Application Config Teardown"); }, app_settings_suite: { setup: function() { app.log("app_settings_suite setup"); }, teardown: function() { app.log("app_settings_suite teardown"); }, ...
Remove @abstracmethod from archive method as well
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 # # Un...
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 # # Un...
Configure to run tests under pytest runner
import sys import setuptools py26_reqs = ['argparse', 'importlib'] if sys.version_info < (2,7) else [] setuptools.setup( name='librarypaste', use_hg_version=dict(increment='0.1'), author='Jamie Turner', author_email='jamie@jamwt.com', url='http://bitbucket.org/chmullig/librarypaste/', descrip...
import sys import setuptools py26_reqs = ['argparse', 'importlib'] if sys.version_info < (2,7) else [] setuptools.setup( name='librarypaste', use_hg_version=dict(increment='0.1'), author='Jamie Turner', author_email='jamie@jamwt.com', url='http://bitbucket.org/chmullig/librarypaste/', descrip...
Remove unnecessary Gingerbread check around strict mode
package com.wkovacs64.mtorch; import android.app.Application; import android.os.StrictMode; import timber.log.Timber; public final class CustomApplication extends Application { @Override public void onCreate() { if (BuildConfig.DEBUG) { // Initialize Timber logging library Ti...
package com.wkovacs64.mtorch; import android.app.Application; import android.os.Build; import android.os.StrictMode; import timber.log.Timber; public final class CustomApplication extends Application { @Override public void onCreate() { if (BuildConfig.DEBUG) { // Initialize Timber loggi...
Update the next version to 4.4.0
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '4.4.0' __requires__ = [ 'apptools', 'traits', 'traitsui',...
# Author: Prabhu Ramachandran, Gael Varoquaux # Copyright (c) 2004-2014, Enthought, Inc. # License: BSD Style. """ A tool for easy and interactive visualization of data. Part of the Mayavi project of the Enthought Tool Suite. """ __version__ = '5.0.0' __requires__ = [ 'apptools', 'traits', 'traitsui',...
Replace requestNamespace by xmlNamespace method
<?php /** * This file is part of the Zimbra API in PHP library. * * © Nguyen Van Nguyen <nguyennv1981@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Zimbra\Mail\Request; use Zimbra\Soap\Request; /** * Base...
<?php /** * This file is part of the Zimbra API in PHP library. * * © Nguyen Van Nguyen <nguyennv1981@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Zimbra\Mail\Request; use Zimbra\Soap\Request; /** * Base...
Use the smart JSON serializer for BadRequest
package org.openstack.client.internals; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.module.SimpleModule; import org.openstack.model.compute.Addresses; import org.openstack.model.compute.BadRequest; import org.openstack.model.compute.SecurityGroup; import org.openstack.model.compute.SecurityGro...
package org.openstack.client.internals; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.module.SimpleModule; import org.openstack.model.compute.Addresses; import org.openstack.model.compute.SecurityGroup; import org.openstack.model.compute.SecurityGroupList; import org.openstack.model.compute.Serv...
Remove y-axis ticks and top x-axis ticks
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
Correct wrong constructor in test
<?php namespace spec\Swarrot\Processor\Stack; use Swarrot\Processor\InitializableInterface; use Swarrot\Processor\TerminableInterface; use Swarrot\Processor\ProcessorInterface; use Swarrot\ParameterBag; use Swarrot\AMQP\Message; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class StackedProcessorSpec extends Ob...
<?php namespace spec\Swarrot\Processor\Stack; use Swarrot\Processor\InitializableInterface; use Swarrot\Processor\TerminableInterface; use Swarrot\Processor\ProcessorInterface; use Swarrot\ParameterBag; use Swarrot\AMQP\Message; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class StackedProcessorSpec extends Ob...
Add mobile app menu to Project Lists Summary: Using Project lists on mobile is missing the query menu, this adds it. Test Plan: test mobile layout, click menu, see query list Reviewers: btrahan, epriestley Reviewed By: epriestley Subscribers: Korvin, epriestley Differential Revision: https://secure.phabricator.co...
<?php final class PhabricatorProjectListController extends PhabricatorProjectController { private $queryKey; public function shouldAllowPublic() { return true; } public function willProcessRequest(array $data) { $this->queryKey = idx($data, 'queryKey'); } public function processRequest() { ...
<?php final class PhabricatorProjectListController extends PhabricatorProjectController { private $queryKey; public function shouldAllowPublic() { return true; } public function willProcessRequest(array $data) { $this->queryKey = idx($data, 'queryKey'); } public function processRequest() { ...
Complete a bit the application helpers tests
require('../test_helper'); require('../../app/helpers'); describe('Application helpers', () => { before(() => { I18n.load('en') }) describe('#g', () => { it('should generate a Glyphicon span', () => { var output = Handlebars.helpers.g('foo'); assert(output instanceof Handlebars.SafeString);...
require('../test_helper'); require('../../app/helpers'); describe('Application helpers', () => { describe('#g', () => { it('should generate a Glyphicon span', () => { var output = Handlebars.helpers.g('foo'); assert(output instanceof Handlebars.SafeString); assert.equal(output.string, '<span c...
LIBRA-235: Add html and htm to list of acceptable files
(function() { "use strict"; function initPage() { var fileTypes = [ "csv", "gif", "htm", "html", "jpeg", "jpg", "mp3", "mp4", "pdf", "png", "tif", "tiff", "txt", "xml" ]; var list = fileTypes.join(", ").toUpperCase(); var filter = fileTypes.join("|"); // Match an...
(function() { "use strict"; function initPage() { var fileTypes = [ "csv", "gif", "jpeg", "jpg", "mp3", "mp4", "pdf", "png", "tif", "tiff", "txt", "xml" ]; var list = fileTypes.join(", ").toUpperCase(); var filter = fileTypes.join("|"); // Match any file that doesn't c...
Drop messages instead of buffering
"use strict"; var stream = require("stream"), util = require("util"); // TODO write this up as "how to merge readable streams" var InfinitePassThrough = function() { stream.Transform.call(this); this._transform = function(chunk, encoding, callback) { // only pass data on if something's listening and we'r...
"use strict"; var stream = require("stream"), util = require("util"); // TODO write this up as "how to merge readable streams" var InfinitePassThrough = function() { stream.Transform.call(this); this._transform = function(chunk, encoding, callback) { // only pass data on if something's listening if (...
[BPK-1053] Add elevation tokens under shadows
/* * Backpack - Skyscanner's Design System * * Copyright 2017 Skyscanner 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 * * Un...
/* * Backpack - Skyscanner's Design System * * Copyright 2017 Skyscanner 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 * * Un...