text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Improve example, start pystray in main thread and webview in new process | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
import multiprocessing
if sys.platform == 'darwin':
ctx = multiprocessing.get_context('spawn')
Process = ctx.Process
Queue = ctx.Queue
else:
Process = multiprocessing.Process
Queue = multiprocessing.Queue
"""... | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
raise NotImplementedError('This example does not work on macOS.')
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray ... |
Fix out of date path in a test case. | var fs = require("fs");
var path = require("path");
var utils = require("../utils");
var chai = require("chai");
var expect = chai.expect;
var exec = utils.exec;
var simpleAddonPath = path.join(__dirname, "..", "addons", "simple-addon");
describe("jpm xpi", function () {
beforeEach(utils.setup);
afterEach(utils.t... | var fs = require("fs");
var path = require("path");
var utils = require("../utils");
var chai = require("chai");
var expect = chai.expect;
var exec = utils.exec;
var simpleAddonPath = path.join(__dirname, "..", "addons", "simple-addon");
describe("jpm xpi", function () {
beforeEach(utils.setup);
afterEach(utils.t... |
Fix video URL from PlaylistItem | const duration = require('iso8601-duration');
class Video {
constructor(youtube, data) {
this.youtube = youtube;
this.title = data.snippet.title;
this.id = data.id.videoId ? data.id.videoId : data.id;
this.description = data.snippet.description;
this.publishedAt = da... | const duration = require('iso8601-duration');
class Video {
constructor(youtube, data) {
this.youtube = youtube;
this.title = data.snippet.title;
this.id = data.id.videoId ? data.id.videoId : data.id;
this.description = data.snippet.description;
this.url = `https://w... |
Fix tests for correct environment config | /*global $, assert, trigger*/
'use strict';
describe('Albums create dialog', function () {
this.timeout(20000);
it('should create new album', function (done) {
var user;
TEST.browser
// Authorize
.auth('users_album_create', function (usr) {
user = usr;
})
// Navigate to ... | /*global $, assert, trigger*/
'use strict';
describe('Albums create dialog', function () {
this.timeout(20000);
it('should create new album', function (done) {
var user;
TEST.browser
// Authorize
.auth('users_album_create', function (usr) {
user = usr;
})
// Navigate to ... |
Fix avatar url encoding (whitespace was encoded with + rather than %20) | package com.faforever.api.data.listeners;
import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Avatar;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
import javax.inject.Inject;
import javax.persistence.PostLoad;
import java.nio.charset... | package com.faforever.api.data.listeners;
import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Avatar;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import javax.persistence.PostLoad;
import java.io.UnsupportedEncodingException;
import java.net.URLEncod... |
Fix broken RegExp in Travis mentions | // PiscoBot Script
var commandDescription = {
name: 'Travis CI Build Fails',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: '',
version: 1.0,
description: 'Have the bot react to a build failing on Travis CI.',
module: 'Core'
};
global.botHelp.push(commandDescription);
var _ = require('underscore');... | // PiscoBot Script
var commandDescription = {
name: 'Travis CI Build Fails',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: '',
version: 1.0,
description: 'Have the bot react to a build failing on Travis CI.',
module: 'Core'
};
global.botHelp.push(commandDescription);
var _ = require('underscore');... |
Clean up udevd zombie process | package control
import (
"os"
"os/exec"
"github.com/rancher/os/pkg/log"
"github.com/codegangsta/cli"
)
func udevSettleAction(c *cli.Context) {
if err := UdevSettle(); err != nil {
log.Fatal(err)
}
}
func UdevSettle() error {
cmd := exec.Command("udevd", "--daemon")
defer exec.Command("killall", "udevd").... | package control
import (
"os"
"os/exec"
"github.com/rancher/os/pkg/log"
"github.com/codegangsta/cli"
)
func udevSettleAction(c *cli.Context) {
if err := UdevSettle(); err != nil {
log.Fatal(err)
}
}
func UdevSettle() error {
cmd := exec.Command("udevd", "--daemon")
cmd.Stdout = os.Stdout
cmd.Stderr = os... |
Use io.open with encoding='utf-8' and flake8 compliance | import io
from setuptools import setup, find_packages
long_description = '\n'.join((
io.open('README.rst', encoding='utf-8').read(),
io.open('CHANGES.txt', encoding='utf-8').read()
))
tests_require = [
'pytest >= 2.0',
'pytest-cov',
'WebTest >= 2.0.14',
'mock',
]
setup(
name='bowersta... | from setuptools import setup, find_packages
long_description = (
open('README.rst').read()
+ '\n' +
open('CHANGES.txt').read())
tests_require = [
'pytest >= 2.0',
'pytest-cov',
'WebTest >= 2.0.14',
'mock',
]
setup(
name='bowerstatic',
version='0.10.dev0',
description="A Bo... |
Revert "Change calculateReserves minimum value to zero"
This reverts commit d84468b7631cf9c08d1f9d185f59f36c79d16d68. | import {
fromPairs,
head,
last,
max,
mapObjIndexed,
sortBy,
toPairs,
} from 'ramda'
export function calculateReserves (cumulative, reserveData, mineral, column, series) {
const reserves = getReserves(reserveData, mineral)
if (!reserves) {
// console.debug('No reserves!')
... | import {
fromPairs,
head,
last,
max,
mapObjIndexed,
sortBy,
toPairs,
} from 'ramda'
export function calculateReserves (cumulative, reserveData, mineral, column, series) {
const reserves = getReserves(reserveData, mineral)
if (!reserves) {
// console.debug('No reserves!')
... |
Fix deploy button for second player | "use strict";
var _ = require('mori');
var Router = require('react-router');
var React = require('react');
var mori = require("mori");
var UnitCell = require('../board/UnitCell.react.js');
var GameStore = require('../../stores/GameStore.js');
var ProfileLink = require('../common/ProfileLink.react.js');
var GameActions... | "use strict";
var _ = require('mori');
var Router = require('react-router');
var React = require('react');
var mori = require("mori");
var UnitCell = require('../board/UnitCell.react.js');
var GameStore = require('../../stores/GameStore.js');
var ProfileLink = require('../common/ProfileLink.react.js');
var GameActions... |
Add test case for 404 on docs pages | import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.... | import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.... |
Rewrite lib error with ES6 | exports default {
'lrc_notfound': '抱歉, 没找到歌词',
'account_missing': '请先设置豆瓣账户再操作: $ douban.fm config',
'setup_fail': '啊哦,启动出错了,请检查配置文件 ~/.douban.fm.profile.json',
'love_fail': '未知曲目无法加心',
'normal': '出错了, 请稍后再试...',
'last_song': '这是最后一首了哦,回车以加载最新列表',
'turn_to_local_mode': '获取豆瓣电台频道出错,切换为本地电台...',
'mkdir_fa... | module.exports = {
lrc_notfound: '抱歉, 没找到歌词',
account_missing: '请先设置豆瓣账户再操作: $ douban.fm config',
setup_fail: '啊哦,启动出错了,请检查配置文件 ~/.douban.fm.profile.json',
love_fail: '未知曲目无法加心',
normal: '出错了, 请稍后再试...',
last_song: '这是最后一首了哦,回车以加载最新列表',
turn_to_local_mode: '获取豆瓣电台频道出错,切换为本地电台...',
mkdir_fail: '创建歌曲文件夹出错... |
Document the fix for FreeBSD. | // +build !windows
package runtime
import (
"io/ioutil"
"syscall"
"github.com/codahale/metrics"
)
func getFDLimit() (uint64, error) {
var rlimit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
return 0, err
}
// rlimit.Cur's type is platform-dependent, so here we wi... | // +build !windows
package runtime
import (
"io/ioutil"
"syscall"
"github.com/codahale/metrics"
)
func getFDLimit() (uint64, error) {
var rlimit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
return 0, err
}
return uint64(rlimit.Cur), nil
}
func getFDUsage() (uint... |
Improve format of logging output. | """
@copyright: 2013 Single D Software - All Rights Reserved
@summary: Debugging console interface for Light Maestro.
"""
# Standard library imports
import logging
import threading
import time
# Application imports
import console
# Named logger for this module
_logger = logging.getLogger(__name__)
class LoggingCo... | """
@copyright: 2013 Single D Software - All Rights Reserved
@summary: Debugging console interface for Light Maestro.
"""
# Standard library imports
import logging
import threading
import time
# Application imports
import console
# Named logger for this module
_logger = logging.getLogger(__name__)
class LoggingCo... |
Configure an explicit timeout for Mocha | exports.config = {
host: 'selenium',
specs: [
'./tests/acceptance/specs/**/*.spec.js'
],
maxInstances: 10,
capabilities: [{
browserName: 'chrome'
}],
sync: true,
logLevel: 'error',
coloredLogs: true,
bail: 0,
screenshotPath: './tests/acceptance/results/',
baseUrl: 'http://app:3000',
... | exports.config = {
host: 'selenium',
specs: [
'./tests/acceptance/specs/**/*.spec.js'
],
maxInstances: 10,
capabilities: [{
browserName: 'chrome'
}],
sync: true,
logLevel: 'error',
coloredLogs: true,
bail: 0,
screenshotPath: './tests/acceptance/results/',
baseUrl: 'http://app:3000',
... |
Remove application extensions from optimized image | 'use strict';
const execBuffer = require('exec-buffer');
const gifsicle = require('gifsicle');
const isGif = require('is-gif');
module.exports = opts => buf => {
opts = Object.assign({}, opts);
if (!Buffer.isBuffer(buf)) {
return Promise.reject(new TypeError('Expected a buffer'));
}
if (!isGif(buf)) {
return... | 'use strict';
const execBuffer = require('exec-buffer');
const gifsicle = require('gifsicle');
const isGif = require('is-gif');
module.exports = opts => buf => {
opts = Object.assign({}, opts);
if (!Buffer.isBuffer(buf)) {
return Promise.reject(new TypeError('Expected a buffer'));
}
if (!isGif(buf)) {
return... |
Fix test error with YamlSource | <?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed... | <?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed... |
Update 0.7.0
- specified try-block to check the status
- changed except block
- allowed .gif format but only up to 3MP (Twitter limitation) |
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
# check if website is accessible
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
apod_data.raise_for_status()
apod_data = apod_data.json()
# check if i... |
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
raise TypeError
image_data = requ... |
Fix video jumping to fullscreen on iPhones |
import {Video} from '@thiagopnts/kaleidoscope';
import {ContainerPlugin, Mediator, Events} from 'clappr';
export default class Video360 extends ContainerPlugin {
constructor(container) {
super(container);
Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this);
let {height... |
import {Video} from '@thiagopnts/kaleidoscope';
import {ContainerPlugin, Mediator, Events} from 'clappr';
export default class Video360 extends ContainerPlugin {
constructor(container) {
super(container);
Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this);
let {height... |
Make bot respond to mentions. | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','b... | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','b... |
Fix queue not showing correct times | @section("content")
<div class="container main">
<h1 class="text-center">Queue</h1>
<ul class="list-group col-md-8 col-md-offset-2">
@foreach ($queue as $q)
@if ($q["type"] > 0)
<li class="list-group-item list-group-item-success">
@else
<li class="list-group-item">
@endif
<time date... | @section("content")
<div class="container main">
<h1 class="text-center">Queue</h1>
<ul class="list-group col-md-8 col-md-offset-2">
@foreach ($queue as $q)
@if ($q["type"] > 0)
<li class="list-group-item list-group-item-success">
@else
<li class="list-group-item">
@endif
<span>{{{ ... |
Fix wrong parameter on fail message in init game | /* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope) {
$scope.availableAccounts = web3.eth.accounts;
$scope.selectedAccount = web3.eth.defaultAccount;
$scope.startcolor = 'white';
$scope.us... | /* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope) {
$scope.availableAccounts = web3.eth.accounts;
$scope.selectedAccount = web3.eth.defaultAccount;
$scope.startcolor = 'white';
$scope.us... |
Tweak default sorting once more
Sort all collections by least recent update. These have been waiting
for attention the longest. We initially used least recent response,
but the metadata for that doesn't seem to match what you would
expect. | /* Shaka Team Triage Party - Extra JS for Collection View
*
* Copyright 2021 Google LLC
*
* 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-... | /* Shaka Team Triage Party - Extra JS for Collection View
*
* Copyright 2021 Google LLC
*
* 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-... |
Rename to invalidate possible grunt caches | module.exports = function(grunt) {
require('wf-grunt').init(grunt, {
options: {
requireConfig: {
paths: {
modernizr: 'bower_components/modernizr/modernizr',
'wf-js-common': './src',
'test': './test'
},
... | module.exports = function(grunt) {
require('wf-js-grunt').init(grunt, {
options: {
requireConfig: {
paths: {
modernizr: 'bower_components/modernizr/modernizr',
'wf-js-common': './src',
'test': './test'
}... |
Watch task not re-symlinking template indexes
The watch task does that now. | 'use strict';
(() => {
const debounce = (func, wait, immediate) => {
let timeout;
return () => {
const context = this;
const args = arguments;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeo... | 'use strict';
(() => {
const debounce = (func, wait, immediate) => {
let timeout;
return () => {
const context = this;
const args = arguments;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeo... |
Add battery API detection. Lint code. | (function() {
'use strict';
function toTime(sec) {
sec = parseInt(sec, 10);
var hours = Math.floor(sec / 3600),
minutes = Math.floor((sec - (hours * 3600)) / 60),
seconds = sec - (hours * 3600) - (minutes * 60);
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { minute... | (function(window) {
'use strict';
function toTime(sec) {
sec = parseInt(sec, 10);
var hours = Math.floor(sec / 3600);
var minutes = Math.floor((sec - (hours * 3600)) / 60);
var seconds = sec - (hours * 3600) - (minutes * 60);
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { ... |
Reimplement auto scroll to bottom | import React, { Component, PropTypes } from 'react';
import styles from '../chat.scss';
import Message from './message/Message';
export default class ChatArea extends Component {
componentDidMount() {
setTimeout(this.updateScrollTop, 0);
}
componentDidUpdate() {
this.updateScrollTop();
}
getRef = n... | import React, { Component, PropTypes } from 'react';
import styles from '../chat.scss';
import Message from './message/Message';
export default class ChatArea extends Component {
render() {
const { messages, ...rest } = this.props;
return (
<div id="container" className={styles.container}>
{mes... |
Add action item to TODO. | /**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.GENMODEL({
package: 'foam.nanos.client',
name: 'Client',
implements: [ 'foam.box.Context' ],
requires: [
// TODO This is just for the build part. Without it, there's no way of
... | /**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.GENMODEL({
package: 'foam.nanos.client',
name: 'Client',
implements: [ 'foam.box.Context' ],
requires: [
// TODO This is just for the build part. Without it, there's no way of
... |
Simplify updating of locale field in user account. | // Store the preference locale in cookies and (if available) session to use
// on next requests.
'use strict';
var _ = require('lodash');
var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer.
module.exports = function (N, apiPath) {
N.validate(apiPath, {
locale: { type: 'string' }
... | // Store the preference locale in cookies and (if available) session to use
// on next requests.
'use strict';
var _ = require('lodash');
var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer.
module.exports = function (N, apiPath) {
N.validate(apiPath, {
locale: { type: 'string' }
... |
Fix issue where demo text does not autosize textarea.
Closes #8 | import autosize from "autosize"
const script = String.raw`<script type="text/javascript">
var emojis = "tada, fire, grinning"
var selector = "body"
var url = window.location.href.replace(/(http:\/\/|https:\/\/)/gi, '').replace(/^\/|\/$/g, '');
var iframe = document.createElement("iframe")
iframe.src = "http... | const script = String.raw`<script type="text/javascript">
var emojis = "tada, fire, grinning"
var selector = "body"
var url = window.location.href.replace(/(http:\/\/|https:\/\/)/gi, '').replace(/^\/|\/$/g, '');
var iframe = document.createElement("iframe")
iframe.src = "https://emojireact.com/embed?emojis="... |
Remove bad use of profiling step | module.exports = function authorize (authApi) {
return function authorizeMiddleware (req, res, next) {
authApi.authorize(req, res, (err, authorized) => {
req.profiler.done('authorize');
if (err) {
return next(err);
}
if(!authorized) {
... | module.exports = function authorize (authApi) {
return function authorizeMiddleware (req, res, next) {
req.profiler.done('req2params.setup');
authApi.authorize(req, res, (err, authorized) => {
req.profiler.done('authorize');
if (err) {
return next(err);
... |
Fix regression on 6269f48ba356c4e7f in cygwin.
signal.SIGBREAK is not defined on cygwin, causing an exception.
R=vadimsh@chromium.org
BUG=
Review URL: https://codereview.chromium.org/1349183005 | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Utilities."""
import logging
import os
import signal
import sys
from utils import subprocess42
def exec_python(args):
"""Executes a python proce... | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Utilities."""
import logging
import os
import signal
import sys
from utils import subprocess42
def exec_python(args):
"""Executes a python proce... |
Fix error in getting mouse posititions. | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos()[0], mouse.get_pos()[1]):
curr_element = element
... | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos):
curr_element = element
element.on_hov... |
Load all source files in Karma | 'use strict';
module.exports = function(config) {
config.set({
'basePath': '',
'frameworks': ['jasmine'],
'files': [
'bower_components/jquery/dist/jquery.js',
'bower_components/ScrollToFixed/jquery-scrolltofixed.js',
'bower_components/angular/angular.js',
'bower_components/angular... | 'use strict';
module.exports = function(config) {
config.set({
'basePath': '',
'frameworks': ['jasmine'],
'files': [
'bower_components/jquery/dist/jquery.js',
'bower_components/ScrollToFixed/jquery-scrolltofixed.js',
'bower_components/angular/angular.js',
'bower_components/angular... |
Remove createJSModules from Package java file - RN 0.47 compatibility |
package com.b8ne.RNPusherPushNotifications;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
i... |
package com.b8ne.RNPusherPushNotifications;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
i... |
Fix javascript access in spring security | package org.example.shelf.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.w... | package org.example.shelf.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.w... |
Add auto branch checkout functionality | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from ..utils import DEVNULL, change_working_directory
from .base import DOWNLOAD_CONTAINER
def _checkout(name):
with change_working_directory(DOWNLOAD_CONTAINER):
subprocess.call(
('git', 'checkout', name),
stdout=DEV... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from ..utils import DEVNULL, change_working_directory
from .base import DOWNLOAD_CONTAINER
def download(source_info):
url = source_info['git']
subprocess.call(
('git', 'clone', url, DOWNLOAD_CONTAINER),
stdout=DEVNULL, stderr=sub... |
Change time difference assert from > to >= 0
diff == 0 occurs on when executing trivial code in a cell. Updating the
assert to include this. | from __future__ import print_function
import time
from IPython.core.magics.execution import _format_time as format_delta
class LineWatcher(object):
"""Class that implements a basic timer.
Notes
-----
* Register the `start` and `stop` methods with the IPython events API.
"""
def __init__(s... | from __future__ import print_function
import time
from IPython.core.magics.execution import _format_time as format_delta
class LineWatcher(object):
"""Class that implements a basic timer.
Notes
-----
* Register the `start` and `stop` methods with the IPython events API.
"""
def __init__(s... |
Set user service to always create a display name if one is not supplied | 'use strict';
const bcrypt = require('bcrypt-nodejs');
class UsersService {
constructor(options, usersRepository) {
const self = this;
self._options = options;
self.usersRepository = usersRepository;
}
getUserById(id, callback) {
const self = this;
self.usersRepository.findUserById(id, call... | 'use strict';
const bcrypt = require('bcrypt-nodejs');
class UsersService {
constructor(options, usersRepository) {
const self = this;
self._options = options;
self.usersRepository = usersRepository;
}
getUserById(id, callback) {
const self = this;
self.usersRepository.findUserById(id, call... |
Fix for when using python3.5. Don't install enum34 if enum already exists (python35) | import os
from setuptools import setup
readme_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'README.rst',
)
long_description = open(readme_path).read()
version_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'VERSION',
)
version = open(version_path).read()
requires = ['ld... | import os
from setuptools import setup
readme_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'README.rst',
)
long_description = open(readme_path).read()
version_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'VERSION',
)
version = open(version_path).read()
setup(
name='fl... |
[trunk] Convert line endings for .h, .c and .cpp files as well as .cs | #!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
... | #!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
... |
Correct imports in loc package. | import re
from pypods.datasource import DataSource
from pypods.loc.locchannelhandler import LocChannelHandler
class LocDataSource(DataSource):
def __init__(self):
super(LocDataSource, self).__init__()
self.channels = dict()
def create_channel(self, channel_name):
"""Creates a channel... | import re
from pypods.datasource import DataSource
from pypods.loc.locchannelhandler import LocChannelHandler
class LocDataSource(DataSource):
def __init__(self):
super(LocDataSource, self).__init__()
self.channels = dict()
def create_channel(self, channel_name):
"""Creates a channel... |
Use Stream instead of StringUtils | package org.kepennar.aproc.complicatebusiness;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.stream.Stream;
import javax.inject.Inject;
import org.kepennar.aproc.tasks.Task... | package org.kepennar.aproc.complicatebusiness;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.stream.Stream;
import javax.inject.Inject;
import org.kepennar.aproc.tasks.Task... |
Use /etc/hosts to find redis | import collections
import pickle
import redis
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = 'redis', 6379
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
... | import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get... |
Set depth for Lake Superior | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 10:42:40 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 08:44:50 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... |
Modify export to allow importing selectively | import rms from './extractors/rms';
import energy from './extractors/energy';
import spectralSlope from './extractors/spectralSlope';
import spectralCentroid from './extractors/spectralCentroid';
import spectralRolloff from './extractors/spectralRolloff';
import spectralFlatness from './extractors/spectralFlatness';
im... | import rms from './extractors/rms';
import energy from './extractors/energy';
import spectralSlope from './extractors/spectralSlope';
import spectralCentroid from './extractors/spectralCentroid';
import spectralRolloff from './extractors/spectralRolloff';
import spectralFlatness from './extractors/spectralFlatness';
im... |
Fix test_email_url() after changes to email templating for sharing emails | import urlparse
from django.test import TestCase, override_settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
... | import urlparse
from django.test import TestCase, override_settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
... |
[LIB-464] Remove Raw import from Admin model | import stampit from 'stampit';
import {Meta, Model} from './base';
import {BaseQuerySet, Get, List, First, PageSize} from '../querySet';
const AdminQuerySet = stampit().compose(
BaseQuerySet,
Get,
List,
First,
PageSize
);
const AdminMeta = Meta({
name: 'admin',
pluralName: 'admins',
endpoints: {
'... | import stampit from 'stampit';
import {Meta, Model} from './base';
import {BaseQuerySet, Get, List, First, PageSize, Raw} from '../querySet';
const AdminQuerySet = stampit().compose(
BaseQuerySet,
Get,
List,
First,
PageSize
);
const AdminMeta = Meta({
name: 'admin',
pluralName: 'admins',
endpoints: {
... |
Remove slash already present in APP_URL | <?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark... | <?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark... |
Clean command - tool help fix | # Copyright 2014-2015 0xc0170
#
# 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,... | # Copyright 2014-2015 0xc0170
#
# 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,... |
Add encoding hint (and which python version is required). | # -*- coding: UTF-8 -*-
# REQUIRES: Python >= 3.5
from behave import given, then, step
from behave.api.async_step import use_or_create_async_context, AsyncContext
from hamcrest import assert_that, equal_to, empty
import asyncio
@asyncio.coroutine
def async_func(param):
yield from asyncio.sleep(0.2)
return str(... | from behave import given, then, step
from behave.api.async_step import use_or_create_async_context, AsyncContext
from hamcrest import assert_that, equal_to, empty
import asyncio
@asyncio.coroutine
def async_func(param):
yield from asyncio.sleep(0.2)
return str(param).upper()
@given('I dispatch an async-call w... |
Break after receiving no bytes to prevent hanging | from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.... | from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.... |
fix(macro): Delete the desks settings for macro | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
im... | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
im... |
Make App a context manager
This means it can be used either as it is now unchanged or like this:
with libui.App():
... # code
Note that (1) the build instructions for libui appear to be wrong "make" vs "cmake ."; and (2) I can't build libui because of a bug in it or Ubuntu 14.04's cmake I don't know which. ... | """
Python wrapper for libui.
"""
from . import libui
class App:
def __init__(self):
"""
Creates a new pylibui app.
"""
options = libui.uiInitOptions()
libui.uiInit(options)
def __enter__(self):
self.start()
def start(self):
"""
Star... | """
Python wrapper for libui.
"""
from . import libui
class App:
def __init__(self):
"""
Creates a new pylibui app.
"""
options = libui.uiInitOptions()
libui.uiInit(options)
def start(self):
"""
Starts the application main loop.
:return: N... |
Make sure HTML entities are converted to the symbols they represent before passing them to the Markdown parser. | // From https://gist.github.com/1343518
// Modified by Hakim to handle markdown indented with tabs
(function(){
var slides = document.querySelectorAll('[data-markdown]');
for( var i = 0, len = slides.length; i < len; i++ ) {
var elem = slides[i];
// strip leading whitespace so it isn't evalua... | // From https://gist.github.com/1343518
// Modified by Hakim to handle markdown indented with tabs
(function(){
var slides = document.querySelectorAll('[data-markdown]');
for( var i = 0, len = slides.length; i < len; i++ ) {
var elem = slides[i];
// strip leading whitespace so it isn't evalua... |
Modify tests to implement the required rules property. | <?php
use Mockery as m;
use Samrap\Validation\Validator;
class ValidatorTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}
public function testValidatorPasses()
{
$validator = $this->getValidator();
$rules = ['foo' => 'bar'];
$thi... | <?php
use Mockery as m;
use Samrap\Validation\Validator;
class ValidatorTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}
public function testValidatorPasses()
{
$validator = $this->getValidator();
$rules = ['foo' => 'bar'];
$thi... |
Allow running tests without Django. | #!/usr/bin/env python
import os
import sys
import unittest
from huey import tests
def _requirements_installed():
try:
import django
return True
except Exception:
return False
def run_tests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittes... | #!/usr/bin/env python
import os
import sys
import unittest
from huey import tests
def _requirements_installed():
try:
import django
return True
except Exception:
return False
def run_tests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittes... |
Remove Python 3 incompatible print statement | #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Sc... | #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Sc... |
Use array for benchmark bytes | #!/usr/bin/env node
const crypto = require('crypto');
const b64 = require('../');
const prettyBytes = require('pretty-bytes');
const bytesToBenchmark = [10000, 100000, 1000000, 10000000];
const timer = {
reset: () => timer.startTime = process.hrtime(),
duration: () => process.hrtime(timer.startTime)[1] / 1000000... | #!/usr/bin/env node
const crypto = require('crypto');
const b64 = require('../');
const prettyBytes = require('pretty-bytes');
const timer = {
reset: () => timer.startTime = process.hrtime(),
duration: () => process.hrtime(timer.startTime)[1] / 1000000
};
const bench = noOfBytes => Promise.resolve().then(async (... |
Allow SDK location to be overridden by environment variable. | import os
import logging
class PblCommand:
name = ''
help = ''
def run(args):
pass
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
parser.add_argument('--debug', action='store_true',
... | import os
class PblCommand:
name = ''
help = ''
def run(args):
pass
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
parser.add_argument('--debug', action='store_true',
help = 'Ena... |
Remove del fetched_tweets (now a generator) | from apscheduler.schedulers.blocking import BlockingScheduler
from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins,
update_status)
from memory_profiler import profile
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=16)
@profile
def twinsy_finder(fetch_size=10000):
... | from apscheduler.schedulers.blocking import BlockingScheduler
from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins,
update_status)
from memory_profiler import profile
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=16)
@profile
def twinsy_finder(fetch_size=10000):
... |
Fix issue with path variable | import os
from setuptools import setup
PACKAGE_VERSION = '0.3'
def version():
def version_file(mode='r'):
return open(os.path.dirname(os.path.abspath(__file__), 'version.txt'), mode)
if os.getenv('TRAVIS'):
with version_file('w') as verfile:
verfile.write('{0}.{1}'.format(PACKAG... | import os
from setuptools import setup
PACKAGE_VERSION = '0.3'
def version():
def version_file(mode='r'):
return open(os.path.join(__path__, 'version.txt'), mode)
if os.getenv('TRAVIS'):
with version_file('w') as verfile:
verfile.write('{0}.{1}'.format(PACKAGE_VERSION, os.getenv... |
Update install_requires to support future django versions | #!/usr/bin/env python
from setuptools import setup
setup(name='django_emarsys',
version='0.34',
description='Django glue for Emarsys events',
license="MIT",
author='Markus Bertheau',
author_email='mbertheau@gmail.com',
long_description=open('README.md').read(),
packages=['dja... | #!/usr/bin/env python
from setuptools import setup
setup(name='django_emarsys',
version='0.34',
description='Django glue for Emarsys events',
license="MIT",
author='Markus Bertheau',
author_email='mbertheau@gmail.com',
long_description=open('README.md').read(),
packages=['dja... |
Remove writing to Zookeeper when kafka is selected as offset storage and dual.commit is false. | /*
* 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 ... | /*
* 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 ... |
Refactor translation downloads according to downloadFile service | import Controller from '@ember/controller';
export default Controller.extend({
isLoading: false,
actions: {
translationsDownload() {
this.set('isLoading', true);
this.get('loader')
.downloadFile('/admin/content/translations/all')
.then(res => {
const anchor = document.cre... | import Controller from '@ember/controller';
export default Controller.extend({
isLoading: false,
actions: {
translationsDownload() {
this.set('isLoading', true);
this.get('loader')
.downloadFile('/admin/content/translations/all')
.then(() => {
this.get('notify').success(t... |
Make it more obvious that values initialize at 0 | import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUIn... | import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUIn... |
Use plat_specific site-packages dir in CI script | import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackages... | import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackages... |
Add order in nodes in topic creation form | # -*- coding:utf-8 -*-
from flask.ext.sqlalchemy import models_committed
from gather.extensions import db, cache
class Node(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False, unique=True, index=True)
slug = db.Column(db.String(100), nullable=False, un... | # -*- coding:utf-8 -*-
from flask.ext.sqlalchemy import models_committed
from gather.extensions import db, cache
class Node(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False, unique=True, index=True)
slug = db.Column(db.String(100), nullable=False, un... |
Change code style to use single-quoted strings instead of double-quoted strings. | /*
* Copyright (c) 2015 Steven Soloff
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publi... | /*
* Copyright (c) 2015 Steven Soloff
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publi... |
Add default port to database connection script
The default port is used if the ~/.catmaid-db file doesn't contain it. This
fixes #454. | import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: loc... | import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: loc... |
Fix typo with expected metric | """
Contains tests for the timer metric.
"""
from statsite.metrics import Timer
class TestTimerMetric(object):
def test_fold_sum(self):
"""
Tests that folding generates a sum of the timers.
"""
now = 10
metrics = [Timer("k", 10),
Timer("k", 15),
... | """
Contains tests for the timer metric.
"""
from statsite.metrics import Timer
class TestTimerMetric(object):
def test_fold_sum(self):
"""
Tests that folding generates a sum of the timers.
"""
now = 10
metrics = [Timer("k", 10),
Timer("k", 15),
... |
Disable the unifier until the hint is passed to the StramChild about the type of the unifier. | /*
* Copyright (c) 2012-2013 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.lib.stream;
import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.DefaultInputPort;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.... | /*
* Copyright (c) 2012-2013 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.lib.stream;
import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.DefaultInputPort;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.... |
Update to use new computed property syntax | import Ember from 'ember';
export default Ember.ArrayController.extend({
queryParams: ['query', 'offset'],
query: null,
offset: 0,
increment: 20,
queryField: Ember.computed.oneWay('query'),
meta: Ember.computed('content.[]', function() {
return this.get("content.meta");
}),
resultsAvailable: Emb... | import Ember from 'ember';
export default Ember.ArrayController.extend({
queryParams: ['query', 'offset'],
query: null,
offset: 0,
increment: 20,
queryField: Ember.computed.oneWay('query'),
meta: function() {
return this.get("content.meta");
}.property('content.[]'),
resultsAvailable: Ember.comp... |
Add dependency on little scrapy autoresponse tool | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='B... | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='B... |
Update to User.save api references. | (function (module) {
module.controller("AccountSettingsController", AccountSettingsController);
AccountSettingsController.$inject = ["mcapi", "User", "toastr"];
/* @ngInject */
function AccountSettingsController(mcapi, User, toastr) {
var ctrl = this;
ctrl.fullname = User.attr().fullna... | (function (module) {
module.controller("AccountSettingsController", AccountSettingsController);
AccountSettingsController.$inject = ["mcapi", "User", "toastr"];
/* @ngInject */
function AccountSettingsController(mcapi, User, toastr) {
var ctrl = this;
ctrl.fullname = User.attr().fullna... |
Use a theme instead of vanilla twbs. Add padding. | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
@section('title')
{{ Lang::get('messages.page-title') }}
@stop
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.2/united/bootstrap.min.css">... | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
@section('title')
{{ Lang::get('messages.page-title') }}
@stop
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.c... |
Mark the sub-package server as deprecated | // +build go1.9
// Package server is deprecated. which is migrated into net2.
package server
import (
"github.com/xgfone/go-tools/net2"
)
type (
// THandle is the type alias of net2.THandle.
//
// DEPRECATED!!! Please the package net2.
THandle = net2.THandle
// THandleFunc is the type alias of net2.THandleFun... | // +build go1.9
package server
import (
"github.com/xgfone/go-tools/net2"
)
type (
// THandle is the type alias of net2.THandle.
//
// DEPRECATED!!! Please the package net2.
THandle = net2.THandle
// THandleFunc is the type alias of net2.THandleFunc.
//
// DEPRECATED!!! Please the package net2.
THandleFunc... |
Change node-dir options to disable recursion to have a more predictable behaviour | import safeEval from 'safe-eval';
import dir from 'node-dir';
import path from 'path';
import {ipcRenderer} from 'electron';
const babel = require('babel-core');
const babelOptions = {
presets: ['es2015']
}
let scriptDirectory = process.env.script;
let options = {
match: /.js$/,
exclude: /^\./,
recursive: fal... | import safeEval from 'safe-eval';
import dir from 'node-dir';
import path from 'path';
import {ipcRenderer} from 'electron';
const babel = require('babel-core');
const babelOptions = {
presets: ['es2015']
}
let scriptDirectory = process.env.script;
let options = {
match: /.js$/,
exclude: /^\./
}
if (path.isAbs... |
Add a missing annotation for a package and fix structure of comments | /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRES... | /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRES... |
Update service provider to use bindShared.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Memory;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class MemoryServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('o... | <?php namespace Orchestra\Memory;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class MemoryServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.mem... |
FRIN23-284: Add option to disable adding target blank to full urls
Uses the same behaviour as in frg -> external.js | /*jslint browser: true, indent: 2, todo: true, unparam: true */
/*global jQuery,Ornament */
(function (document, window, Orn, $) {
"use strict";
var query = [];
// Add suffixes to query.
$.each(Orn.externalLinkExtensions, function (i, v) {
query.push("[href$='." + v + "']");
query.push("[href$='." +... | /*jslint browser: true, indent: 2, todo: true, unparam: true */
/*global jQuery,Ornament */
(function (document, window, Orn, $) {
"use strict";
var query = [];
// Add suffixes to query.
$.each(Orn.externalLinkExtensions, function (i, v) {
query.push("[href$='." + v + "']");
query.push("[href$='." +... |
Fix format constant for PHP 7.1 | <?php namespace Limoncello\Flute\Types;
/**
* Copyright 2015-2017 info@neomerx.com
*
* 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
*
*... | <?php namespace Limoncello\Flute\Types;
/**
* Copyright 2015-2017 info@neomerx.com
*
* 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
*
*... |
Drop buffers with under-used capacity in order to reduce memory waste | package bytebufferpool
import "sync"
const (
minBitSize = 8
steps = 20
minSize = 1 << minBitSize
maxSize = 1 << (minBitSize + steps - 1)
)
type byteBufferPool struct {
// Pools are segemented into power-of-two sized buffers
// from minSize bytes to maxSize.
//
// This allows reducing fragmentation of B... | package bytebufferpool
import "sync"
const (
minBitSize = 8
steps = 20
minSize = 1 << minBitSize
maxSize = 1 << (minBitSize + steps - 1)
)
type byteBufferPool struct {
// Pools are segemented into power-of-two sized buffers
// from minSize bytes to maxSize.
//
// This allows reducing fragmentation of B... |
[AllBundles] Fix codestyle issues after 5.7 upmerge | <?php
namespace Kunstmaan\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
class WysiwygType extends AbstractType
{
/**
* @var DataTran... | <?php
namespace Kunstmaan\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
class WysiwygType extends AbstractType
{
/**
* @var DataTran... |
Fix import following namespace movement
Docker-DCO-1.1-Signed-off-by: Mangled Deutz <olivier@webitup.fr> (github: dmp42) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from .app import app
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT_WWW', 5000))
app.debug = True
app.run(host='0.0.0.0', port=port)
# Or you can run:
# gu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from . import app
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT_WWW', 5000))
app.debug = True
app.run(host='0.0.0.0', port=port)
# Or you can run:
# gunic... |
Change label text of second view | /* ************************************************************************
coretest
Copyright:
2009 Deutsche Telekom AG, Germany, http://telekom.com
************************************************************************ */
/**
* Start View
*/
core.Class("coretest.view.Test", {
include : [unify.view.... | /* ************************************************************************
coretest
Copyright:
2009 Deutsche Telekom AG, Germany, http://telekom.com
************************************************************************ */
/**
* Start View
*/
core.Class("coretest.view.Test", {
include : [unify.view.... |
Annotate clean classes as @Nullsafe:: (4/14) libraries/components/litho-core/src/main/java/com/facebook/litho/
Reviewed By: pasqualeanatriello
Differential Revision: D28505758
fbshipit-source-id: 2bb4c97a1d166c4090db5edb7e6178719f0c2a5d | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
test: Check transform definitions are well set | /* global describe, it, expect */
import { filterByKeys, transform } from '../src/transform'
import * as mocks from './mocks'
describe('Transform suite', () => {
const keys = Object.keys(mocks.defs.simple)
it('should filter by keys two objects', () => {
expect(filterByKeys(keys, mocks.defs.complex)).toEqual(m... | /* global describe, it, expect */
import { filterByKeys, transform } from '../src/transform'
import * as mocks from './mocks'
describe('Transform suite', () => {
it('should filter by keys two objects', () => {
const keys = Object.keys(mocks.defs.simple)
expect(filterByKeys(keys, mocks.defs.complex)).toEqual(... |
Clarify something in the docs. | package com.raoulvdberge.refinedstorage.api.storage.externalstorage;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
import java.util.function.Supplier;
/**
* Provides an external storage handler to the external storage block.
*
* @param <T>
*/
p... | package com.raoulvdberge.refinedstorage.api.storage.externalstorage;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
import java.util.function.Supplier;
/**
* Provides an external storage handler to the external storage block.
*
* @param <T>
*/
p... |
Add a todo for statsd gauges. | // Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package exporter
import (
"expvar"
"flag"
"fmt"
"github.com/google/mtail/metrics"
)
var (
statsdHostPort = flag.String("statsd_hostport", "",
"Host:port to statsd server to write metrics to.")
statsdExpor... | // Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package exporter
import (
"expvar"
"flag"
"fmt"
"github.com/google/mtail/metrics"
)
var (
statsdHostPort = flag.String("statsd_hostport", "",
"Host:port to statsd server to write metrics to.")
statsdExpor... |
Update test to run only against sdk 23, since the new method doesn't exist on older versions of android and the tests are compiled against the latest version of the sdk. The test still fails because it is missing | // Copyright 2015 Google Inc. All Rights Reserved.
package org.robolectric.shadows;
import android.os.Build;
import android.text.format.DateUtils;
import libcore.icu.DateIntervalFormat;
import android.icu.util.TimeZone;
import android.icu.util.ULocale;
import org.junit.Test;
import org.junit.runner.RunWith;
import o... | // Copyright 2015 Google Inc. All Rights Reserved.
package org.robolectric.shadows;
import android.os.Build;
import android.text.format.DateUtils;
import libcore.icu.DateIntervalFormat;
import android.icu.util.TimeZone;
import android.icu.util.ULocale;
import org.junit.Test;
import org.junit.runner.RunWith;
import o... |
Remove the static pin fir analog read | #Creating a key value store for all the urls
BASE_URL = 'http://cloud.boltiot.com/remote/'
url_list = {
'digitalWrite' : '{}/digitalWrite?pin={}&state={}&deviceName={}',
'digitalRead' : '{}/digitalRead?pin={}&deviceName={}',
'analogWrite' : '{}/analogWrite?pin={}&value={}&deviceName={}',
'analogRead' :... | #Creating a key value store for all the urls
BASE_URL = 'http://cloud.boltiot.com/remote/'
url_list = {
'digitalWrite' : '{}/digitalWrite?pin={}&state={}&deviceName={}',
'digitalRead' : '{}/digitalRead?pin={}&deviceName={}',
'analogWrite' : '{}/analogWrite?pin=1&value={}&state={}&deviceName={}',
'analo... |
Fix system.setting does not exist
Signed-off-by: SamPoyigi <f16bed56189e249fe4ca8ed10a1ecae60e8ceac0@sampoyigi.com> | <?php
namespace Igniter\Flame\Setting;
use Igniter\Flame\Setting\Middleware\SaveSetting;
use Illuminate\Support\ServiceProvider;
class SettingServiceProvider extends ServiceProvider
{
protected $defer = TRUE;
/**
* Register the service provider.
* @return void
*/
public function register(... | <?php
namespace Igniter\Flame\Setting;
use Igniter\Flame\Setting\Middleware\SaveSetting;
use Illuminate\Support\ServiceProvider;
class SettingServiceProvider extends ServiceProvider
{
protected $defer = TRUE;
/**
* Register the service provider.
* @return void
*/
public function register(... |
Make sure we don't miss "low" confidence warnings
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@14961 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3 | package sfBugsNew;
import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
public class Bug1219 {
interface A {
}
interface B {
}
interface C {
}
interface D {
}
static class CC imp... | package sfBugsNew;
import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
public class Bug1219 {
interface A {
}
interface B {
}
interface C {
}
interface D {
}
static class CC imp... |
Fix spacing between month names | Datepicker.language['pt-br'] = {
days: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
daysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
daysMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sa'],
months: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', ... | Datepicker.language['pt-br'] = {
days: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
daysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
daysMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sa'],
months: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho', 'Julho','Agosto... |
Fix a typo that make the setup fail for localfs | <?php
/**
* Interface for the file system models.
*
* This defines the interface for any model that wants to interact with a remote file system.
* @author Jaisen Mathai <jaisen@jmathai.com>
*/
interface FileSystemInterface
{
public function deletePhoto($id);
public function getPhoto($filename);
public functi... | <?php
/**
* Interface for the file system models.
*
* This defines the interface for any model that wants to interact with a remote file system.
* @author Jaisen Mathai <jaisen@jmathai.com>
*/
interface FileSystemInterface
{
public function deletePhoto($id);
public function getPhoto($filename);
public functi... |
Fix error in telemetry task
A condition had been changed to always match for debugging purposes, and
was accidentally committed that way. | from django.core.cache import cache
from celery.utils.log import get_task_logger
from enhydris.celery import app
from enhydris.telemetry.models import Telemetry
FETCH_TIMEOUT = 300
LOCK_TIMEOUT = FETCH_TIMEOUT + 60
logger = get_task_logger(__name__)
@app.task
def fetch_all_telemetry_data():
for telemetry in T... | from django.core.cache import cache
from celery.utils.log import get_task_logger
from enhydris.celery import app
from enhydris.telemetry.models import Telemetry
FETCH_TIMEOUT = 300
LOCK_TIMEOUT = FETCH_TIMEOUT + 60
logger = get_task_logger(__name__)
@app.task
def fetch_all_telemetry_data():
for telemetry in T... |
Move sleep call to begining of loop | <?php
define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
$alerts = array(
"Coldest Air of the Season Sweeping Through Central and Southern States",
"Belgium on 'high alert'",
"Multiple raids in Brussels as police seek ISIS terrorists",
"Syria fighters may be fueled by amphetamines... | <?php
define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
$alerts = array(
"Coldest Air of the Season Sweeping Through Central and Southern States",
"Belgium on 'high alert'",
"Multiple raids in Brussels as police seek ISIS terrorists",
"Syria fighters may be fueled by amphetamines... |
Modify pyauto test ChromeosPrivateViewTest to use 2.2.28 data file.
BUG=none
TEST=This is a test.
Review URL: https://chromiumcodereview.appspot.com/10389084
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@136454 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright (c) 2012 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.
import os
import pyauto_functional # must be imported before pyauto
import pyauto
class ChromeosPrivateViewTest(pyauto.PyUITest)... | #!/usr/bin/env python
# Copyright (c) 2012 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.
import os
import pyauto_functional # must be imported before pyauto
import pyauto
class ChromeosPrivateViewTest(pyauto.PyUITest)... |
Change to use boxed type | /*-
* Copyright 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclips... | /*-
* Copyright 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclips... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.