text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add option to verify jwt token
from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework_jwt import views as jwt_views from . import views router = DefaultRouter() router.register(r'quotes', views.QuoteViewSet) router.register(r'authors', views.AuthorViewSet) router.register(r'categories', views...
from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework_jwt import views as jwt_views from . import views router = DefaultRouter() router.register(r'quotes', views.QuoteViewSet) router.register(r'authors', views.AuthorViewSet) router.register(r'categories', views...
Remove redundant console message about password prompt
'use strict'; var serialNumber = require('./index'); var fail = function (err) { console.error('Could not read serial number:', err); }; serialNumber(function (err) { if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) { [ '\x1B[7m' + // inverse style 'Your system requires root/...
'use strict'; var serialNumber = require('./index'); var fail = function (err) { console.error('Could not read serial number:', err); }; serialNumber(function (err) { if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) { [ '\x1B[7m' + // inverse style 'Your system requires root/...
Fix prettyTime not being found
var exports = {}; exports.simplePrint = function(video) { return `**${video.title}**`; }; exports.prettyPrint = function(video) { try { viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ','); } catch (e) { viewCount = 'unknown'; } return `**${video.title}** by **${video.author}** *(${vi...
var exports = {}; exports.simplePrint = function(video) { return `**${video.title}**`; }; exports.prettyPrint = function(video) { try { viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ','); } catch (e) { viewCount = 'unknown'; } return `**${video.title}** by **${video.author}** *(${vi...
Move authentication block inside network layer setup
/* Bootstrap components and api on DOM Load */ /* global Turbolinks document */ import Relay from 'react-relay'; import { mountComponents, unmountComponents, } from './utils/componentMounter'; import Authentication from './helpers/authentication.es6'; const setupNetworkLayer = () => { const auth = new Authen...
/* Bootstrap components and api on DOM Load */ /* global Turbolinks document */ import Relay from 'react-relay'; import { mountComponents, unmountComponents, } from './utils/componentMounter'; import Authentication from './helpers/authentication.es6'; const auth = new Authentication(); const setupNetworkLayer ...
Check if PluginExecutionContext was started before shutting it down. If a `PluginExecutionContext().shutdown()` is called _before_ `PluginExecutionContext().start()` was called, this leads to an `AttributeError` exception since finalizer tries to access to attributes which were never defined.
from bonobo.execution.base import LoopingExecutionContext, recoverable class PluginExecutionContext(LoopingExecutionContext): PERIOD = 0.5 def __init__(self, wrapped, parent): # Instanciate plugin. This is not yet considered stable, as at some point we may need a way to configure # plugins, f...
from bonobo.execution.base import LoopingExecutionContext, recoverable class PluginExecutionContext(LoopingExecutionContext): PERIOD = 0.5 def __init__(self, wrapped, parent): # Instanciate plugin. This is not yet considered stable, as at some point we may need a way to configure # plugins, f...
Support layout on template endpoints
from dataclasses import dataclass from datetime import datetime @dataclass class AuthResponse: email: str image_access: bool search_access: bool created: datetime modified: datetime @dataclass class FontResponse: filename: str id: str alias: str _self: str @dataclass class Meme...
from dataclasses import dataclass from datetime import datetime @dataclass class AuthResponse: email: str image_access: bool search_access: bool created: datetime modified: datetime @dataclass class FontResponse: filename: str id: str alias: str _self: str @dataclass class Meme...
Change version format to allow MAJOR.MINOR.PATCH.
#!/usr/bin/env python from setuptools import setup, find_packages version_tuple = __import__('pymysql').VERSION if version_tuple[3] is not None: version = "%d.%d.%d_%s" % version_tuple else: version = "%d.%d.%d" % version_tuple[:3] try: with open('README.rst') as f: readme = f.read() except IOErr...
#!/usr/bin/env python from setuptools import setup, find_packages version_tuple = __import__('pymysql').VERSION if version_tuple[2] is not None: version = "%d.%d_%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] try: with open('README.rst') as f: readme = f.read() except IOError: ...
Add control panel test for update
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.cpanel import ControlPanel class TestPage(BaseTestCase): @httpretty.activate def test_fetch_payment_session_timeout(self): """Method defined to test fetch payment session timeout.""" httpretty.registe...
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.cpanel import ControlPanel class TestPage(BaseTestCase): @httpretty.activate def test_fetch_payment_session_timeout(self): """Method defined to test fetch payment session timeout.""" httpretty.registe...
Fix cardboard items being unrepairable
package net.mcft.copy.betterstorage.item.cardboard; import net.mcft.copy.betterstorage.content.Items; import net.mcft.copy.betterstorage.item.ItemBetterStorage; import net.minecraft.item.EnumArmorMaterial; import net.minecraft.item.EnumToolMaterial; import net.minecraftforge.common.EnumHelper; public class ItemCardbo...
package net.mcft.copy.betterstorage.item.cardboard; import net.mcft.copy.betterstorage.content.Items; import net.mcft.copy.betterstorage.item.ItemBetterStorage; import net.minecraft.item.EnumArmorMaterial; import net.minecraft.item.EnumToolMaterial; import net.minecraftforge.common.EnumHelper; public class ItemCardbo...
Fix resolution of value in composites
'use strict'; var last = require('es5-ext/array/#/last') , noop = require('es5-ext/function/noop') , mapKeys = require('es5-ext/object/map-keys') , callable = require('es5-ext/object/valid-callable') , d = require('d') , splitId = require('dbjs/_setup/unserialize/id') , DOMInput = require(...
'use strict'; var noop = require('es5-ext/function/noop') , callable = require('es5-ext/object/valid-callable') , d = require('d') , DOMInput = require('../_composite') , getPrototypeOf = Object.getPrototypeOf , getInputValue = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'inputValue').get...
Fix missing auth handler when trying to access EC2.
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else ...
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else ...
Normalize variable names, and error check for undefined rather than for falsy
/************************************ * Redis key and channel namespaces * ************************************/ module.exports = { getItemPropertyKey: getItemPropertyKey, getKeyInfo: getKeyInfo, getPropertyChannel: getPropertyChannel, getFocusProperty: getFocusProperty, // The unique ID key is used to consiste...
/************************************ * Redis key and channel namespaces * ************************************/ module.exports = { getItemPropertyKey: getItemPropertyKey, getKeyInfo: getKeyInfo, getPropertyChannel: getPropertyChannel, getFocusProperty: getFocusProperty, // The unique ID key is used to consiste...
Set greeting defaults to null
let userConfig; try { userConfig = require('../config'); } catch (e) { throw new Error(`Config file could not be found or read! The error given was: ${e.message}`); } const defaultConfig = { "token": null, "mailGuildId": null, "mainGuildId": null, "logChannelId": null, "prefix": "!", "snippetPrefix":...
let userConfig; try { userConfig = require('../config'); } catch (e) { throw new Error(`Config file could not be found or read! The error given was: ${e.message}`); } const defaultConfig = { "token": null, "mailGuildId": null, "mainGuildId": null, "logChannelId": null, "prefix": "!", "snippetPrefix":...
Fix return type and set strict
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. declare(strict_types=1); namespace App\Models; /** * @property int $count * @property int $name */ class Count extends Model { ...
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Models; /** * @property int $count * @property int $name */ class Count extends Model { public $incrementing = fal...
Add test to include strings to numbers
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test the command line interface """ import pytest from ..cli import _is_int, _is_float, _resolve_type @pytest.mark.parametrize("test_input,expected", [ ("True", True), ("False", False), ("None", None), (13.3, 13.3), ("12.51", 12.51), (10, 1...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test the command line interface """ import pytest from ..cli import _is_int, _is_float, _resolve_type @pytest.mark.parametrize("test_input,expected", [ ("True", True), ("False", False), ("None", None), (13.3, 13.3), (10, 10), ("hello world"...
Make date and time optional
orion.addEntity('activities', _.extend(_.clone(commonSchema), { location: { type: Object, label: 'Location', optional: true, autoform: { type: 'map', afFieldInput: { searchBox: true } } }, 'location.lat': { type: String }, 'location.lng': { type: String ...
orion.addEntity('activities', _.extend(_.clone(commonSchema), { location: { type: Object, label: 'Location', optional: true, autoform: { type: 'map', afFieldInput: { searchBox: true } } }, 'location.lat': { type: String }, 'location.lng': { type: String ...
Fix for ion-modal spurious blaze errors
IonLoading = { show: function (userOptions) { var userOptions = userOptions || {}; var options = _.extend({ delay: 0, duration: null, customTemplate: null, backdrop: false }, userOptions); if (options.backdrop) { IonBackdrop.retain(); $('.backdrop').addClass('b...
IonLoading = { show: function (userOptions) { var userOptions = userOptions || {}; var options = _.extend({ delay: 0, duration: null, customTemplate: null, backdrop: false }, userOptions); if (options.backdrop) { IonBackdrop.retain(); $('.backdrop').addClass('b...
FIx exception in dialog tab completion
package vg.civcraft.mc.civmodcore.chatDialog; import java.util.Collections; import java.util.List; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.ser...
package vg.civcraft.mc.civmodcore.chatDialog; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.server.TabCompleteEvent; public class ChatListener imple...
Remove custom YesNoEnum and use yesno method from ConsoleUI There is no need to reimplement the yes/no functionality. Change-Id: I0e9050a38b9785e93b6549d27455f356e828d2de Signed-off-by: Edwin Kempin <b444e279ad95fdef4fbdd82c813b624595df204a@sap.com>
// Copyright (C) 2013 The Android Open Source Project // // 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 ...
// Copyright (C) 2013 The Android Open Source Project // // 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 ...
Support Q, use when not static resolve
PromiseAllSync = { extend: function(PromiseClass) { PromiseClass.allSync = function(collection, fn, unfn) { var stack = []; return collection.reduce(function(promise, item) { return promise.then(function() { var nextPromise = fn ? fn(item) : item; return nextPromise.then(fu...
PromiseAllSync = { extend: function(PromiseClass) { PromiseClass.allSync = function(collection, fn, unfn) { var stack = []; return collection.reduce(function(promise, item) { return promise.then(function() { var nextPromise = fn ? fn(item) : item; return nextPromise.then(fu...
Update majors when user is created
<?php declare(strict_types=1); namespace App\Observers; use App\Jobs\PushToJedi; use App\User; use DateTime; class UserObserver { public function created(User $user): void { if ('cas_login' === $user->create_reason) { return; } UpdateMajorsForUser::dispatch($user)->onQue...
<?php declare(strict_types=1); namespace App\Observers; use App\Jobs\PushToJedi; use App\User; use DateTime; class UserObserver { public function saved(User $user): void { PushToJedi::dispatch($user, User::class, $user->id, 'saved')->onQueue('jedi'); } public function updated(User $user): v...
Fix duplicate captcha import check
from django.core.exceptions import ImproperlyConfigured class CaptchaFormMixin(object): def _reorder_fields(self, ordering): """ Test that the 'captcha' field is really present. This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration. """ if 'captcha' not in...
from django.core.exceptions import ImproperlyConfigured try: from captcha.fields import ReCaptchaField as CaptchaField except ImportError: try: from captcha.fields import CaptchaField except ImportError: raise ImportError( "To use the captcha contact form, you need to have " ...
Replace deprecated PyGlove symbols to new ones. PiperOrigin-RevId: 408683720
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
Move fade out animation after finish()
package io.github.droidkaigi.confsched2017.view.activity; import android.app.Activity; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.NonNull; import io.github.droidkaigi.confsched2017.R; import io.github.droidkaigi.confsched2017....
package io.github.droidkaigi.confsched2017.view.activity; import android.app.Activity; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.NonNull; import io.github.droidkaigi.confsched2017.R; import io.github.droidkaigi.confsched2017....
Define our constants FIRST to prevent errors
<?php // Start the session so we can save // query results across pages requests. session_start(); ini_set('display_errors', 0); error_reporting(E_ALL & ~E_NOTICE); define("APPNAME", "CNAM"); define("VERSION", "1.3"); define("APIVersion", "1"); define("DEVGITHUB", "https://www.github.com/cedwardsmedia/cnam"); define...
<?php // Start the session so we can save // query results across pages requests. session_start(); ini_set('display_errors', 1); error_reporting(E_ALL & E_NOTICE); require 'vendor/autoload.php'; require 'APICaller.php'; include 'config.php'; define("APPNAME", "CNAM"); define("VERSION", "1.3"); define("APIVersion",...
Replace windows backslashes in template definition when precompiling
'use strict'; function precompileGlobal(templates, opts) { var out = '', name, template; opts = opts || {}; for ( var i = 0; i < templates.length; i++ ) { // replace all backslashes with forward slashes var normalizedName = templates[i].name.replace(/\\/g, ''); name = JSON.stringif...
'use strict'; function precompileGlobal(templates, opts) { var out = '', name, template; opts = opts || {}; for ( var i = 0; i < templates.length; i++ ) { name = JSON.stringify(templates[i].name); template = templates[i].template; out += '(function() {' + '(window.nunj...
Add additional comments to command for clarity
package useful import ( "fmt" "os" "runtime" ) // GetPwd1 return .go file path, where func really is // // Useful only with .go file // With binary file always return path of source .go file func GetPwd1() string { _, pwd, _, ok := runtime.Caller(0) if !ok { panic("No caller information") } return pwd } // ...
package useful import ( "fmt" "os" "runtime" ) // GetPwd1 return .go file path, where func really is // // Useful only with .go file // With binary file always return path of source .go file func GetPwd1() string { _, pwd, _, ok := runtime.Caller(0) if !ok { panic("No caller information") } return pwd } // ...
Add the creation of the data dir for the sqlite file.
from .base import * DEBUG = False # Make data dir DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'data')) not os.path.isdir(DATA_DIR) and os.mkdir(DATA_DIR, 0o0775) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.abspath(os.path.join( BASE_D...
from .base import * DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.abspath(os.path.join( BASE_DIR, '..', 'data', 'db.sqlite3')), } } ALLOWED_HOSTS = [ '127.0.0.1' ] # email settings EMAIL_HOST = 'localhost' EMAIL_...
Fix non-resolved errors throwing errors on click
package me.coley.recaf.ui.controls.text; import javafx.scene.Node; import javafx.scene.control.ListCell; import javafx.scene.text.Text; import me.coley.recaf.util.struct.Pair; import org.fxmisc.richtext.CodeArea; /** * Cell renderer. * * @author Matt */ public class ErrorCell extends ListCell<Pair<Integer, String...
package me.coley.recaf.ui.controls.text; import javafx.scene.Node; import javafx.scene.control.ListCell; import javafx.scene.text.Text; import me.coley.recaf.util.struct.Pair; import org.fxmisc.richtext.CodeArea; /** * Cell renderer. * * @author Matt */ public class ErrorCell extends ListCell<Pair<Integer, String...
Update to use the spec command in the latest armstrong.dev
from armstrong.dev.tasks import * from fabric.api import task settings = { 'DEBUG': True, 'INSTALLED_APPS': ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'armstrong.core.arm_sec...
from armstrong.dev.tasks import * from d51.django.virtualenv.base import VirtualEnvironment from fabric.api import task settings = { 'DEBUG': True, 'INSTALLED_APPS': ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ...
Add fi:wikivoyage and sort by current article count Fix also pycodestyle (former PEP8) E402 problem Bug: T153470 Change-Id: Id9bc980c7a9cfb21063597a3d5eae11c31d8040c
# -*- coding: utf-8 -*- """Family module for Wikivoyage.""" # # (C) Pywikibot team, 2012-2016 # # Distributed under the terms of the MIT license. # # The new wikivoyage family that is hosted at wikimedia from __future__ import absolute_import, unicode_literals from pywikibot import family __version__ = '$Id$' class...
# -*- coding: utf-8 -*- """Family module for Wikivoyage.""" # # (C) Pywikibot team, 2012-2016 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family clas...
Include parent layers object, to ease update git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@1481 cb33b658-6c9e-41a7-9690-cba343611204
/** * */ package org.mwc.cmap.plotViewer.actions; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.operations.DebriefActionWrapper; import MWC.GUI.PlainChart; import MWC.GUI.Tools.Action; import MWC.GenericData.WorldArea; /** * @author ian.mayo * */ public class FitToWindow extends CoreEditorActi...
/** * */ package org.mwc.cmap.plotViewer.actions; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.operations.DebriefActionWrapper; import MWC.GUI.PlainChart; import MWC.GUI.Tools.Action; import MWC.GenericData.WorldArea; /** * @author ian.mayo * */ public class FitToWindow extends CoreEditorActi...
Set links to open in new tab
import {Observable} from 'rx'; import {div, a, h2, h3, img} from '@cycle/dom'; import projects from '../data/projects'; function renderSidebar () { return ( div('.sidebar', [ h2('Built with Cycle.js'), img({src: 'http://cycle.js.org/img/cyclejs_logo.svg', alt: 'Cycle.js'}) ]) ); } function re...
import {Observable} from 'rx'; import {div, a, h2, h3, img} from '@cycle/dom'; import projects from '../data/projects'; function renderSidebar () { return ( div('.sidebar', [ h2('Built with Cycle.js'), img({src: 'http://cycle.js.org/img/cyclejs_logo.svg', alt: 'Cycle.js'}) ]) ); } function re...
Fix indentation in PHP example template, now uses 4 spaces consistently
```php $client = new \GuzzleHttp\Client(); $response = $client->{{ strtolower($route['methods'][0]) }}( '{{ rtrim($baseUrl, '/') . '/' . ltrim($route['boundUri'], '/') }}', [ @if(!empty($route['headers'])) 'headers' => {!! \Mpociot\ApiDoc\Tools\Utils::printPhpValue($route['headers'], 8) !!}, @endif @if...
```php $client = new \GuzzleHttp\Client(); $response = $client->{{ strtolower($route['methods'][0]) }}( '{{ rtrim($baseUrl, '/') . '/' . ltrim($route['boundUri'], '/') }}', [ @if(!empty($route['headers'])) 'headers' => {!! \Mpociot\ApiDoc\Tools\Utils::printPhpValue($route['headers'], 4) !!}, @endif @if(!empty(...
Send whole location object over websocket
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requ...
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requ...
Fix another use of the rbuilder postgres user
#!/usr/bin/python # # Copyright (c) 2009 rPath, Inc. # # All rights reserved. # import logging from conary import dbstore from mint.scripts.db2db import db2db log = logging.getLogger(__name__) def switchToPostgres(cfg): if cfg.dbDriver in ('postgresql', 'pgpool'): return sourceTuple = (cfg.dbDrive...
#!/usr/bin/python # # Copyright (c) 2009 rPath, Inc. # # All rights reserved. # import logging from conary import dbstore from mint.scripts.db2db import db2db log = logging.getLogger(__name__) def switchToPostgres(cfg): if cfg.dbDriver in ('postgresql', 'pgpool'): return sourceTuple = (cfg.dbDrive...
Add missing host field to Apple TV
"""Discover Apple TV media players.""" import ipaddress from . import MDNSDiscoverable # pylint: disable=too-few-public-methods class Discoverable(MDNSDiscoverable): """Add support for Apple TV devices.""" def __init__(self, nd): super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.') ...
"""Discover Apple TV media players.""" from . import MDNSDiscoverable # pylint: disable=too-few-public-methods class Discoverable(MDNSDiscoverable): """Add support for Apple TV devices.""" def __init__(self, nd): super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.') def info_from_ent...
Complete max subarray sum by DP
"""Leetcode 53. Maximum Subarray Easy Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(...
"""Leetcode 53. Maximum Subarray Easy Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(...
Generalize controllers to abstract one
<?php namespace EdpModuleLayouts; class Module { public function onBootstrap($e) { $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractController', 'dispatch', function($e) { $controller = $e->getTarget(); $controllerClass = get_...
<?php namespace EdpModuleLayouts; class Module { public function onBootstrap($e) { $e->getApplication()->getEventManager()->getSharedManager()->attach(array('Zend\Mvc\Controller\AbstractRestfulController', 'Zend\Mvc\Controller\AbstractActionController'), 'dispatch', function...
Use iOS cache instead of tmp
/** * @title Open - cordova.plugins.bridge.open * @overview Open documents with compatible apps. * @copyright Β© 2014 cordova-bridge * @license GPLv2 * @author Carlos Antonio */ var exec = require('cordova/exec'); /** * open * * @param {String} args File URI * @param {Function} success Success callback * @pa...
/** * @title Open - cordova.plugins.bridge.open * @overview Open documents with compatible apps. * @copyright Β© 2014 cordova-bridge * @license GPLv2 * @author Carlos Antonio */ var exec = require('cordova/exec'); /** * open * * @param {String} args File URI * @param {Function} success Success callback * @pa...
Change i18n angular filter to interpolate strings
/* This file is part of Indico. * Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License...
/* This file is part of Indico. * Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License...
Fix reading field value to model
import $ from 'jquery' import template from '../../lib/environment.html' export default function EnvironmentController(model) { const $element = $(template) $element.find(":input[name='ot_version']").change(toolkitVersionChangeHandler).change() $element.find(":input[name='formatter']").change(formatterHandler)....
import $ from 'jquery' import template from '../../lib/environment.html' export default function EnvironmentController(model) { const $element = $(template) $element.find(":input[name='ot_version']").change(toolkitVersionChangeHandler).change() $element.find(":input[name='formatter']").change(formatterHandler)....
Use placeholder variable to fix error
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; /** * Handles requests through the browser ie at the live site */ class WebController extends Controller { public function viewLinks($teamSlug) { $teamName="HngX"; $teamId="Txjrd24"; //parse $teamId and $t...
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; /** * Handles requests through the browser ie at the live site */ class WebController extends Controller { public function viewLinks($teamSlug) { //parse $teamId and $teamName from $teamSlug if (isset($_GET["query"])) {...
Use correct param for defaultValue
import PreferenceGroup from './PreferenceGroup'; import ChoicePreference from './ChoicePreference'; /** * Preferences for containers * * This will build all the preferences a container can possess e.g lifetime. * Other preferences like icon, color and exit rules are conceivable */ export default class ContainerPr...
import PreferenceGroup from './PreferenceGroup'; import ChoicePreference from './ChoicePreference'; /** * Preferences for containers * * This will build all the preferences a container can possess e.g lifetime. * Other preferences like icon, color and exit rules are conceivable */ export default class ContainerPr...
Add fix for connection errors on localhost. Probably could be fixed by a setting in cURL but this works for now
<?php /** * Do not edit this file. Edit the config files found in the ../config/ dir instead. * This file is required in the root directory so WordPress can find it. * WP is hardcoded to look in its own directory or one directory up for wp-config.php. */ $host_config_dir = dirname(__FILE__) . '/../config/'; $host...
<?php /** * Do not edit this file. Edit the config files found in the ../config/ dir instead. * This file is required in the root directory so WordPress can find it. * WP is hardcoded to look in its own directory or one directory up for wp-config.php. */ $host_config_dir = dirname(__FILE__) . '/../config/'; $host...
Check if mt is None before spliting it
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2020-02-28 17:30 from __future__ import unicode_literals from django.db import migrations import mimetypes def forward(apps, schema_editor): AttachmentModel = apps.get_model('common', 'Attachment') for attachment in AttachmentModel.objects.all(): ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2020-02-28 17:30 from __future__ import unicode_literals from django.db import migrations import mimetypes def forward(apps, schema_editor): AttachmentModel = apps.get_model('common', 'Attachment') for attachment in AttachmentModel.objects.all(): ...
Add authSecret to config vars
var log = require('../lib/logger'); var allTheSettings = { coinbaseApiKey: process.env.COINBASE_API_KEY, coinbaseApiSec: process.env.COINBASE_API_SECRET, coinbaseApiUri: process.env.COINBASE_API_URI, coinbaseApiWallet: process.env.COINBASE_API_WALLET, dbDb: process.env.DATABASE_DB, dbHost: process.env.DATA...
var log = require('../lib/logger'); var allTheSettings = { coinbaseApiKey: process.env.COINBASE_API_KEY, coinbaseApiSec: process.env.COINBASE_API_SECRET, coinbaseApiUri: process.env.COINBASE_API_URI, coinbaseApiWallet: process.env.COINBASE_API_WALLET, dbDb: process.env.DATABASE_DB, dbHost: process.env.DATA...
Fix showing Cluster Template info on Cluster details Cluster details view doesn't show Cluster Template information. This patch fixes it. Change-Id: I4eccda8cdd125f12bd536a3e7af670f1930ca884 Closes-Bug: #1624275
/* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distribute...
/* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distribute...
Add pre-release git paver task
from paver.easy import * @task def release_unix(): sh('python setup.py clean') sh('rm -f h5py_config.pickle') sh('python setup.py build --hdf5-version=1.8.4 --mpi=no') sh('python setup.py test') sh('python setup.py sdist') print("Unix release done. Distribution tar file is in dist/") @task de...
from paver.easy import * @task def release_unix(): sh('python setup.py clean') sh('rm -f h5py_config.pickle') sh('python setup.py build --hdf5-version=1.8.4 --mpi=no') sh('python setup.py test') sh('python setup.py sdist') print("Unix release done. Distribution tar file is in dist/") @task de...
Add trove classifier for license The trove classifiers are listed on PyPI to help users know -- at a glance -- what license the project uses. Helps users decide if the library is appropriate for integration. A full list of available trove classifiers can be found at: https://pypi.org/pypi?%3Aaction=list_classifiers ...
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", aut...
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", aut...
Add processor (copy) implementation for tests
package imageserver import ( "errors" "testing" ) type size struct { width int height int } type providerSize struct{} func (provider *providerSize) Get(source interface{}, parameters Parameters) (*Image, error) { size, ok := source.(size) if !ok { return nil, errors.New("Source is not a size") } return ...
package imageserver import ( "errors" "testing" ) type size struct { width int height int } type providerSize struct{} func (provider *providerSize) Get(source interface{}, parameters Parameters) (*Image, error) { size, ok := source.(size) if !ok { return nil, errors.New("Source is not a size") } return ...
Add json module as fallback for simplejson
import requests try: import simplejson as json except ImportError: import json def getbaseurl(service='search', version='1', method='track', format='json'): """Returns the base URL for a Spotify Web API query""" baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}" return baseurl.forma...
import requests import simplejson as json def getbaseurl(service='search', version='1', method='track', format='json'): """Returns the base URL for a Spotify Web API query""" baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}" return baseurl.format(service, version, method, format) def sea...
Build process now has source maps enabled.
// // Adapted from: // http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle // var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var packageJson = require('./package.json'); var d...
// // Adapted from: // http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle // var gulp = require('gulp'); var browserify = require('browserify'); //var handleErrors = require('../util/handleErrors'); var source = require('vinyl-source-stream'...
Fix date issue and remove lower rule from output.
var content = jQuery('#content'); var grafs = content.text().split('\n\n'); var cx_date = new Date(); var monthNames = ["Jan. ","Feb. ","March ","April ","May ","June ","July ","Aug. ","Sept. ","Oct. ","Nov.","Dec. "]; var cx_month = monthNames[cx_date.getMonth()]; var amPm = ( cx_date.getHours() < 12 ) ? ' a.m.' : ' ...
var content = jQuery('#content'); var grafs = content.text().split('\n\n'); var cx_date = new Date(); var monthNames = ["Jan. ","Feb. ","March ","April ","May ","June ","July ","Aug. ","Sept. ","Oct. ","Nov.","Dec. "]; var cx_month = monthNames[cx_date.getMonth()]; var amPm = ( cx_date.getHours() < 12 ) ? ' a.m.' : ' ...
Use local upload for release
"""Utiltiy functions for workign on the NinaPro Databases (1 & 2).""" from setuptools import setup, find_packages setup(name='nina_helper', version='2.2', description='Utiltiy functions for workign on the NinaPro Databases (1 & 2)', author='Lif3line', author_email='adamhartwell2@gmail.com', ...
"""Utiltiy functions for workign on the NinaPro Databases (1 & 2).""" from setuptools import setup, find_packages setup(name='nina_helper', version='2.1', description='Utiltiy functions for workign on the NinaPro Databases (1 & 2)', author='Lif3line', author_email='adamhartwell2@gmail.com', ...
Handle invalid dates only as well
<?php namespace Speicher210\Fastbill\Api\Serializer\Handler; use JMS\Serializer\Context; use JMS\Serializer\Handler\DateHandler as JMSDateHandler; use JMS\Serializer\JsonDeserializationVisitor; use JMS\Serializer\VisitorInterface; class DateHandler extends JMSDateHandler { /** * {@inheritdoc} */ pu...
<?php namespace Speicher210\Fastbill\Api\Serializer\Handler; use JMS\Serializer\Context; use JMS\Serializer\Handler\DateHandler as JMSDateHandler; use JMS\Serializer\JsonDeserializationVisitor; use JMS\Serializer\VisitorInterface; class DateHandler extends JMSDateHandler { /** * {@inheritdoc} */ pu...
[FIX] event: Set default value for event_count Fixes https://github.com/odoo/odoo/pull/39583 This commit adds a default value for event_count Assigning default value for non-stored compute fields is required in 13.0 closes odoo/odoo#39974 X-original-commit: 9ca72b98f54d7686c0e6019870b40f14dbdd2881 Signed-off-by: Vi...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has partic...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has partic...
Make it compatible with node 4.0
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options) { var options = options || {}; var sdt=options.sdt; var mass=options.mass; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbA...
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options={}) { var { sdt, mass } = options; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbAtoms); for (var i=0; i<nb...
Fix a buggy url conf for heroku.
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.simple import direct_to_template # Enable the django admin admin.autodiscover() urlpatterns = pat...
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.simple import direct_to_template # Enable the django admin admin.autodiscover() urlpatterns = pat...
Switch to store GMT dates.
<?php //This should be run on cron. include_once('config.php'); $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $timeNow = gmdate("Y-m-d H:i:s"); $saved = 0; foreach( ['yes','...
<?php //This should be run on cron. include_once('config.php'); $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $timeNow = date("Y-m-d H:i:s"); $saved = 0; foreach( ['yes','li...
Add a column in the search index for the list of projects.
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() all_public_projects_exact = indexes.MultiValu...
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() def prepare_null_document(self, person_insta...
Fix unicode error in subsection
""" Template tags and helper functions for displaying breadcrumbs in page titles based on the current micro site. """ from django import template from django.conf import settings from microsite_configuration.middleware import MicrositeConfiguration register = template.Library() def page_title_breadcrumbs(*crumbs, **...
""" Template tags and helper functions for displaying breadcrumbs in page titles based on the current micro site. """ from django import template from django.conf import settings from microsite_configuration.middleware import MicrositeConfiguration register = template.Library() def page_title_breadcrumbs(*crumbs, **...
Make the called command to lowercase
package me.duncte123.skybot.utils; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import java.util.Arrays; public class CommandParser { public CommandContainer parse(String rw, MessageReceivedEvent e){ final String[] split = rw.substring(rw.indexOf(Config.prefix) + 1, rw.length()).spl...
package me.duncte123.skybot.utils; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import java.util.Arrays; public class CommandParser { public CommandContainer parse(String rw, MessageReceivedEvent e){ final String[] split = rw.substring(rw.indexOf(Config.prefix) + 1, rw.length()).spl...
Complete a condition curly braces
<?php class ModelPaymentOmiseOffsite extends Model { public function getMethod($address, $total) { if ($this->config->get('omise_status') != 1) { return false; } $this->load->language('payment/omise_offsite'); if ($this->config->get('omise_offsite_payment_title') != "")...
<?php class ModelPaymentOmiseOffsite extends Model { public function getMethod($address, $total) { if ($this->config->get('omise_status') != 1) { return false; } $this->load->language('payment/omise_offsite'); if ($this->config->get('omise_offsite_payment_title') != "")...
Return empty row, fixes bug when there are no skins
(function() { exports.getEmptyRow = function() { var row = Ti.UI.createTableViewRow({ editable: false, isPlaceholder: true, selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY }); var lbl_title = Ti.UI.createLabel({ text: I('main.noContent.title'), font: { fontWeight: 'bold', ...
(function() { exports.getEmptyRow = function() { var row = Ti.UI.createTableViewRow({ editable: false, isPlaceholder: true, selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY }); var lbl_title = Ti.UI.createLabel({ text: I('main.noContent.title'), font: { fontWeight: 'bold', ...
Allow lasers to damage cryopods
package com.ezardlabs.lostsector.objects.projectiles; import com.ezardlabs.dethsquare.Collider; import com.ezardlabs.dethsquare.GameObject; import com.ezardlabs.dethsquare.Script; import com.ezardlabs.lostsector.Game.DamageType; import com.ezardlabs.lostsector.objects.Entity; public class Laser extends Script { pri...
package com.ezardlabs.lostsector.objects.projectiles; import com.ezardlabs.dethsquare.Collider; import com.ezardlabs.dethsquare.GameObject; import com.ezardlabs.dethsquare.Script; import com.ezardlabs.lostsector.Game.DamageType; import com.ezardlabs.lostsector.objects.Entity; public class Laser extends Script { pri...
Refactor change β€˜var’ statement to β€˜const’
import setCurrentScreenAction from "src/actions/ScreenActions.js"; import { SET_CURRENT_SCREEN, MENU_SCREEN, GAME_SCREEN} from "src/actions/ScreenActions.js"; describe("Screen Actions", () => { it("should exist", () => { setCurrentScreenAction.should.exist; }); it("should be a function", () => { ...
import setCurrentScreenAction from "src/actions/ScreenActions.js"; import { SET_CURRENT_SCREEN, MENU_SCREEN, GAME_SCREEN} from "src/actions/ScreenActions.js"; describe("Screen Actions", () => { it("should exist", () => { setCurrentScreenAction.should.exist; }); it("should be a function", () => { ...
Change dummy video in video section
import React from 'react'; import styles from './videosection.css' export default class VideoSection extends React.Component { render() { return ( <div className="wrapper style3 video-section"> <div className="row title"> <h1>About Rojak</h1> </div> <div classN...
import React from 'react'; import styles from './videosection.css' export default class VideoSection extends React.Component { render() { return ( <div className="wrapper style3 video-section"> <div className="row title"> <h1>About Rojak</h1> </div> <div classN...
Remove requirement on python > 2.7
#!/usr/bin/python # -*- coding: utf8 -*- """ The MIT License (MIT) Copyright (c) 2014 Jarl Stefansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
#!/usr/bin/python # -*- coding: utf8 -*- """ The MIT License (MIT) Copyright (c) 2014 Jarl Stefansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
Add datas as parameter for v0.2.4
'use strict'; /** * Upload `contact` (containing contact data) onto Cluestr. * * * @param {Object} contact Contact to upload, plus cluestrClient * @param {Object} cluestrClient Client for upload * @param {Object} datas Datas about the current account * @param {Object} contact Contact to upload, plus cluestrCl...
'use strict'; /** * Upload `contact` (containing contact data) onto Cluestr. * * * @param {Object} contact Contact to upload, plus cluestrClient * @param {Function} cb Callback to call once contacts has been uploaded. */ module.exports = function(contact, cluestrClient, cb) { console.log("Uploading ", contac...
Test on thumbnail update to new reference naming
# -*- coding: utf-8 -*- # Author: Γ“scar NΓ‘jera # License: 3-clause BSD """ Testing the rst files generator """ from __future__ import division, absolute_import, print_function import sphinxgallery.backreferences as sg from nose.tools import assert_equals def test_thumbnail_div(): """Test if the thumbnail div gene...
# -*- coding: utf-8 -*- # Author: Γ“scar NΓ‘jera # License: 3-clause BSD """ Testing the rst files generator """ from __future__ import division, absolute_import, print_function import sphinxgallery.backreferences as sg from nose.tools import assert_equals def test_thumbnail_div(): """Test if the thumbnail div gene...
Fix timezone in submitted data SimpleDateFormat uses the system's default time zone by default.
package org.mozilla.mozstumbler; import android.annotation.SuppressLint; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; final class DateTimeUtils { private static final DateFormat mISO8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); ...
package org.mozilla.mozstumbler; import android.annotation.SuppressLint; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; final class DateTimeUtils { private static final DateFormat mISO8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); static final long MILLIS...
Add hasUser Returns true/false if a room contains a user
var mongoose = require('mongoose'); var Message = new mongoose.Schema({ message: String, sender: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, mime: {type: String, default: "text/plain"}, }); var Member = new mongoose.Schema({ id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, permissions: { oper...
var mongoose = require('mongoose'); var Message = new mongoose.Schema({ message: String, sender: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, mime: {type: String, default: "text/plain"}, }); var Member = new mongoose.Schema({ id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, permissions: { oper...
Change MESSAGE_SUCCESS string to be non-static
/** * */ package tars.logic.commands; /** * @author Johnervan * Changes the directory of the Tars storage file, tars.xml */ public class CdCommand extends Command { public static final String COMMAND_WORD = "cd"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Changes the director...
/** * */ package tars.logic.commands; /** * @author Johnervan * Changes the directory of the Tars storage file, tars.xml */ public class CdCommand extends Command { public static final String COMMAND_WORD = "cd"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Changes the director...
Make sure Essential information is not double tracked
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var analytics = new Analytics(); if (window.lp.hasOwnProperty("tracking") && window.lp.tracking.hasOwnProperty("eVar12") && window.lp.tracking.eVar12 !== "dest essential information") { analytics.trackView(); } // S...
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var analytics = new Analytics(); analytics.trackView(); // Set up Omniture event handlers var windowUnloadedFromSubmitClick = false; // If the user clicks anywhere else on the page, reset the click tracker $(docu...
Add lpeg.c to _ppeg.c dependencies
from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - A...
from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - A...
Allow creation of a no metric symptom
/* * Copyright (c) Microsoft Corporation. All rights reserved. * * This program is made available under the terms of the MIT License. * See the LICENSE file in the project root for more information. */ package com.microsoft.dhalion.detector; import java.util.HashMap; import java.util.Map; import com.microsoft.dh...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * * This program is made available under the terms of the MIT License. * See the LICENSE file in the project root for more information. */ package com.microsoft.dhalion.detector; import java.util.HashMap; import java.util.Map; import com.microsoft.dh...
Remove Python 3.4 from classifiers
from setuptools import setup, find_packages from django_s3_storage import __version__ version_str = ".".join(str(n) for n in __version__) setup( name="django-s3-storage", version=version_str, license="BSD", description="Django Amazon S3 file storage.", author="Dave Hall", author_email="dave...
from setuptools import setup, find_packages from django_s3_storage import __version__ version_str = ".".join(str(n) for n in __version__) setup( name="django-s3-storage", version=version_str, license="BSD", description="Django Amazon S3 file storage.", author="Dave Hall", author_email="dave...
Add highlighting for outline files
define(function(require, exports, module) { var modesByName = require("ace/ext/modelist").modesByName; modesByName.javascript.extensions += "|run|build|outline"; var primaryModes = ["c_cpp","clojure","coffee","csharp","css","dart","golang", "html","jade","java","javascript","json","less","lua","perl","php","pyth...
define(function(require, exports, module) { var modesByName = require("ace/ext/modelist").modesByName; modesByName.javascript.extensions += "|run|build"; var primaryModes = ["c_cpp","clojure","coffee","csharp","css","dart","golang", "html","jade","java","javascript","json","less","lua","perl","php","python", ...
Use safe_load to avoid warning
#!/usr/bin/env python3 import sys import yaml from os import path from plistlib import dumps def generated_comment(): return "This file is auto-generated from %s, do not edit it by hand!" \ % path.basename(in_path) def convert(yaml): lines = dumps(yaml).decode('utf-8').splitlines() lines.insert(...
#!/usr/bin/env python3 import sys import yaml from os import path from plistlib import dumps def generated_comment(): return "This file is auto-generated from %s, do not edit it by hand!" \ % path.basename(in_path) def convert(yaml): lines = dumps(yaml).decode('utf-8').splitlines() lines.insert(...
Enable filenameMode option in CLI
#!/usr/bin/env node var fs = require('fs') var path = require('path') var minimist = require('minimist') var fasta = require('./') var argv = minimist(process.argv.slice(2), { boolean: ['path', 'file'], alias: { file: 'f', path: 'p' } }) if (argv.help) { return console.log( 'Usage: bionode-ncbi <o...
#!/usr/bin/env node var fs = require('fs') var path = require('path') var minimist = require('minimist') var fasta = require('./') var argv = minimist(process.argv.slice(2), { boolean: ['p', 'path'] }); if (argv.help) { return console.log( 'Usage: bionode-ncbi <options> <fasta file [required]> <output file>\n\n...
Use current host name for redirect url
<?php use TOL\PhotoHack\Youtube; function hostName() { $protocol = $_SERVER['HTTPS'] ? 'https://' : 'http://'; $serverName = $_SERVER['SERVER_NAME']; return $protocol . $serverName; } return function($app) { $twigView = new \Slim\Views\Twig(); $twigView->parserOptions = ['autoescape' => false]; ...
<?php use TOL\PhotoHack\Youtube; return function($app) { $twigView = new \Slim\Views\Twig(); $twigView->parserOptions = ['autoescape' => false]; $app->config('templates.path', __DIR__ . '/templates'); $view = $app->view($twigView); $view->parserExtensions = [new \Slim\Views\TwigExtension()]; ...
Add comment about future work in confUrl
'use strict'; // Handles params concerning configuration files in the $routeProvider phase angular.module('arethusa.core').factory('confUrl', [ 'CONF_PATH', '$route', function (CONF_PATH, $route) { // The default route is deprectated and can be refactored away return function (useDefault) { var para...
'use strict'; // Handles params concerning configuration files in the $routeProvider phase angular.module('arethusa.core').factory('confUrl', [ 'CONF_PATH', '$route', function (CONF_PATH, $route) { return function (useDefault) { var params = $route.current.params; var confPath = CONF_PATH + '/'; ...
Add addServiceUrl attribute to result from findServices and findAllServices
/* * Copyright (C) 2013 ickStream GmbH * All rights reserved */ package com.ickstream.protocol.service.core; public class ServiceResponse { private String id; private String name; private String type; private String url; private String addServiceUrl; public String getId() { return ...
/* * Copyright (C) 2013 ickStream GmbH * All rights reserved */ package com.ickstream.protocol.service.core; public class ServiceResponse { private String id; private String name; private String type; private String url; public String getId() { return id; } public void setId(S...
Fix Call to pass in options
package main import ( "bufio" "fmt" "log" "os" "strconv" "gopkg.in/jcelliott/turnpike.v2" ) func main() { turnpike.Debug() c, err := turnpike.NewWebsocketClient(turnpike.JSON, "ws://localhost:8000/", nil) if err != nil { log.Fatal(err) } _, err = c.JoinRealm("turnpike.examples", nil) if err != nil { ...
package main import ( "bufio" "fmt" "log" "os" "strconv" "gopkg.in/jcelliott/turnpike.v2" ) func main() { turnpike.Debug() c, err := turnpike.NewWebsocketClient(turnpike.JSON, "ws://localhost:8000/", nil) if err != nil { log.Fatal(err) } _, err = c.JoinRealm("turnpike.examples", nil) if err != nil { ...
Move AuthProvider into first config block
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'ngAuth', 'mgcrea.ngStrap']) .config(['$routeProvider', 'AuthProvider', function($routeProvider, AuthProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: 'HomeCtrl' }) .when('/login', {...
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'ngAuth', 'mgcrea.ngStrap']) .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: 'HomeCtrl' }) .when('/login', { templateUrl: 'views/l...
Python: Add example of QuerySet chain (django)
from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" ...
from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" ...
Remove unneeded import, fix bare except The `os` module isn't needed, so we need not import it. Additionally, a bare `except` clause is pretty much never desired, since it includes all exceptions, including sigkills. Instead, just check for an `ImportError`, since that's what we're really trying to do: fall back on ...
try: from setuptools import setup except ImportError: from distutils.core import setup setup(name = "clrsvsim", version = "0.0.2", description = "Color Genomics Structural Variant Simulator", author = "Color Genomics", author_email = "dev@color.com", url = "https://github.com/Col...
import os try: from setuptools import setup except: from distutils.core import setup setup(name = "clrsvsim", version = "0.0.2", description = "Color Genomics Structural Variant Simulator", author = "Color Genomics", author_email = "dev@color.com", url = "https://github.com/ColorGen...
Update the test connection value
<?php namespace Leezy\PheanstalkBundle\Tests; use Leezy\PheanstalkBundle\ConnectionLocator; class ConnectionLocatorTest extends \PHPUnit_Framework_TestCase { public function testDefaultConnections() { $connectionLocator = new ConnectionLocator(); $this->assertNotNull($connectionLocat...
<?php namespace Leezy\PheanstalkBundle\Tests; use Leezy\PheanstalkBundle\ConnectionLocator; class ConnectionLocatorTest extends \PHPUnit_Framework_TestCase { public function testDefaultConnections() { $connectionLocator = new ConnectionLocator(); $this->assertNotNull($connectionLocat...
Fix lexicographic order in install_requires
#!/usr/bin/env python from setuptools import setup install_requires = [ 'argparse', 'jsonschema', 'M2Crypto', 'mock', 'pycrypto', 'python-augeas', 'python2-pythondialog', 'requests', ] docs_extras = [ 'Sphinx', ] testing_extras = [ 'coverage', 'nose', 'nosexcover', ...
#!/usr/bin/env python from setuptools import setup install_requires = [ 'argparse', 'jsonschema', 'mock', 'M2Crypto', 'pycrypto', 'python-augeas', 'python2-pythondialog', 'requests', ] docs_extras = [ 'Sphinx', ] testing_extras = [ 'coverage', 'nose', 'nosexcover', ...
Remove redundant ugettext_lazy from non-text labels
from django import forms from django.core import validators from django.forms.widgets import TextInput class URLOrAbsolutePathValidator(validators.URLValidator): @staticmethod def is_absolute_path(value): return value.startswith('/') def __call__(self, value): if URLOrAbsolutePathValidato...
from django import forms from django.core import validators from django.forms.widgets import TextInput from django.utils.translation import ugettext_lazy class URLOrAbsolutePathValidator(validators.URLValidator): @staticmethod def is_absolute_path(value): return value.startswith('/') def __call__...
Fix terrible error when filter_horizontal of admin class has not existed.
from django.db import models from django.utils.translation import ugettext_lazy as _ def register(cls, admin_cls): cls.add_to_class('code', models.ForeignKey('profiles.Code', verbose_name=_('Registration code'), null=True, blank=True)) if admin_cls: admin_cls.list_display_filter += ['code', ] ...
from django.db import models from django.utils.translation import ugettext_lazy as _ def register(cls, admin_cls): cls.add_to_class('code', models.ForeignKey('profiles.Code', verbose_name=_('Registration code'), null=True, blank=True)) if admin_cls: admin_cls.list_display_filter += ['code', ] ...
Fix capitalization method in class_names
HEADER = """/** {file_name} Auto-generated code - do not modify. thinglang C++ transpiler, 0.0.0 **/ """ FOUNDATION_ENUM = HEADER + """ #pragma once #include <string> {imports} enum class {name} {{ {values} }}; """ FOUNDATION_SWITCH = """ inline auto {func_name}({name} val){{ switch (val){{ ...
HEADER = """/** {file_name} Auto-generated code - do not modify. thinglang C++ transpiler, 0.0.0 **/ """ FOUNDATION_ENUM = HEADER + """ #pragma once #include <string> {imports} enum class {name} {{ {values} }}; """ FOUNDATION_SWITCH = """ inline auto {func_name}({name} val){{ switch (val){{ ...
Fix for the goto command actions
$(document).ready(function() { var publishCommand = function(notificationName) { return function(tokens) { $.publish(notificationName); }; } window.TerminalCommands = { next : publishCommand('presentation:slide:next'), previous : publishCommand('presentation:slide:previous'), goto : function(tok...
$(document).ready(function() { var publishCommand = function(notificationName) { return function(tokens) { $.publish(notificationName); }; } window.TerminalCommands = { next : publishCommand('presentation:slide:next'), previous : publishCommand('presentation:slide:previous'), goto : function(tok...
Update the benchmark to use the document.readyState to measure page-completedness rather than the onload event. Extensions were moved from the pre-onload state to running at document idle some time ago. BUG=none TEST=none Review URL: http://codereview.chromium.org/397013 git-svn-id: http://src.chromium.org/svn/trun...
// The port for communicating back to the extension. var benchmarkExtensionPort = chrome.extension.connect(); // The url is what this page is known to the benchmark as. // The benchmark uses this id to differentiate the benchmark's // results from random pages being browsed. // TODO(mbelshe): If the page redirects, t...
// The port for communicating back to the extension. var benchmarkExtensionPort = chrome.extension.connect(); // The url is what this page is known to the benchmark as. // The benchmark uses this id to differentiate the benchmark's // results from random pages being browsed. // TODO(mbelshe): If the page redirects, t...
Update JSON object sent for login
import {Router} from 'express' import models from '../models'; export default () => { let app = Router() app.get('/new', (req, res) => { res.render('sessions/new') }) app.post('/', (req, res) => { var email = req.body.email models.User.find({ attributes: ['id', 'first_name', 'last_name', 'email'], wh...
import {Router} from 'express' import models from '../models'; export default () => { let app = Router() app.get('/new', (req, res) => { res.render('sessions/new') }) app.post('/', (req, res) => { var email = req.body.email models.User.find({ where: { email: email } }).then((user) => { let ...
Change the hide function to work in a better way to not brake other functionallity.
/* Magic Mirror * Node Helper: MotionEye * * By Cato Antonsen (https://github.com/CatoAntonsen) * MIT Licensed. */ var NodeHelper = require("node_helper"); module.exports = NodeHelper.create({ start: function() { console.log("Starting module: " + this.name); }, socketNotificationReceived: function(notific...
/* Magic Mirror * Node Helper: MotionEye * * By Cato Antonsen (https://github.com/CatoAntonsen) * MIT Licensed. */ var NodeHelper = require("node_helper"); module.exports = NodeHelper.create({ start: function() { console.log("Starting module: " + this.name); }, socketNotificationReceived: function(notific...
Return app passwords as string
import os import random import uuid from django.utils import timezone from datetime import timedelta WORDLIST_FILE = os.path.join(os.path.dirname(__file__), 'wordlist.txt') def make_token(): """ Generate a random token suitable for activation/confirmation via email A hex-encoded random UUID has plent...
import os import random import uuid from django.contrib.auth.hashers import make_password,is_password_usable from django.utils import timezone from datetime import timedelta WORDLIST_FILE = os.path.join(os.path.dirname(__file__), 'wordlist.txt') def make_token(): """ Generate a random token suitable for a...
Use admin interface by default
# -*- coding: utf-8 -*- """onserver URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.ho...
# -*- coding: utf-8 -*- """onserver URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.ho...
Use green for console intro instead
var Bot = require( 'nodemw' ), readline = require( 'readline' ), c = require( 'ansicolors' ), rl = readline.createInterface( { input: process.stdin, output: process.stdout } ), client = new Bot( { protocol: 'https', server: 'dev.fandom.com', path: '' } ), params = { action: 'scribunto-console', tit...
var Bot = require( 'nodemw' ), readline = require( 'readline' ), c = require( 'ansi-colors' ), rl = readline.createInterface( { input: process.stdin, output: process.stdout } ), client = new Bot( { protocol: 'https', server: 'dev.fandom.com', path: '' } ), params = { action: 'scribunto-console', ti...