text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Allow for 1 arg in a list | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
... | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list) and layers_max > 1:
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
... |
Fix blocking all options except OptionValues | <?php
namespace WP_Migrations\OptionVersions;
class Provider
{
protected $repository;
public function __construct(Repository $optionVersionRepository)
{
$this->repository = $optionVersionRepository;
}
public function init()
{
add_action('updated_option', [$this, 'updated_op... | <?php
namespace WP_Migrations\OptionVersions;
class Provider
{
protected $repository;
public function __construct(Repository $optionVersionRepository)
{
$this->repository = $optionVersionRepository;
}
public function init()
{
add_action('updated_option', [$this, 'updated_op... |
Add mixin to put the username in context | import urlparse
from functools import wraps
from django.conf import settings
from django.utils.decorators import available_attrs, method_decorator
from django.contrib.auth import REDIRECT_FIELD_NAME
from privileges.forms import GrantForm
from privileges.models import Grant
def owner_required(view_func):
@wrap... | import urlparse
from functools import wraps
from django.conf import settings
from django.utils.decorators import available_attrs, method_decorator
from django.contrib.auth import REDIRECT_FIELD_NAME
from privileges.forms import GrantForm
from privileges.models import Grant
def owner_required(view_func):
@wrap... |
Add a services filter to the API | <?php
/**
* @author Kirk Mayo <kirk.mayo@solnet.co.nz>
*
* A controller class for handling API requests
*/
class SocialAPI extends Controller
{
private static $allowed_actions = array(
'countsfor'
);
private static $url_handlers = array(
'countsfor/$SERVICE/$FILTER'
=> 'co... | <?php
/**
* @author Kirk Mayo <kirk.mayo@solnet.co.nz>
*
* A controller class for handling API requests
*/
class SocialAPI extends Controller
{
private static $allowed_actions = array(
'countsfor'
);
private static $url_handlers = array(
'countsfor'
=> 'countsfor'
);
... |
Fix URL pattern for validating OAuth2 tokens | # Copyright (C) 2014 Universidad Politecnica de Madrid
# 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 ag... | # Copyright (C) 2014 Universidad Politecnica de Madrid
# 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 ag... |
Disable non-functional create service button | import React, { Component } from 'react';
import {observer} from 'mobx-react';
import Services from '../components/Services';
import Tasks from '../components/Tasks';
import FlatButton from 'material-ui/FlatButton';
import { Link } from 'react-router';
const styles = {
button: {
margin: 0.6 + 'rem'
}
};
const... | import React, { Component } from 'react';
import {observer} from 'mobx-react';
import Services from '../components/Services';
import Tasks from '../components/Tasks';
import FlatButton from 'material-ui/FlatButton';
import { Link } from 'react-router';
const styles = {
button: {
margin: 0.6 + 'rem'
}
};
const... |
refactor: Save currentTimePeriod passed to component to variable
Prevents bubbling | import Ember from 'ember';
import moment from 'npm:moment';
export default Ember.Component.extend({
btnActive: false,
didReceiveAttrs () {
let timePeriodChanged = {
year: this.get('currentDate').year,
month: this.get('currentDate').month
};
if (!this.get('timePeriods').length) {
this... | import Ember from 'ember';
import moment from 'npm:moment';
export default Ember.Component.extend({
btnActive: false,
didReceiveAttrs () {
this.set('timePeriodChanged', this.get('currentDate'));
},
init () {
this._super();
this.get('userSettings').timePeriods().then(response => {
// Sort by ... |
Put config back in thing | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
'''
Executables
########################
Exa provides two executables; "exa" and "exw". For the graphical user interface,
built on top of the Jupyter n... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
'''
Executables
########################
Exa provides two executables; "exa" and "exw". For the graphical user interface,
built on top of the Jupyter n... |
Add timer and remove confirm buttonk, overall cleanup for better ux | $(document).ready(function(){
$("#new-timeslot-form").submit(function(event){
event.preventDefault();
var data = createDate();
$("#modal_new_timeslot").modal('toggle');
$.ajax({
type: "POST",
url: "/api/timeslots",
data: { start: data },
beforeSend: customBlockUi(this)... | $(document).ready(function(){
$("#new-timeslot-form").submit(function(event){
event.preventDefault();
var data = createDate();
$("#modal_new_timeslot").modal('toggle');
$.ajax({
type: "POST",
url: "/api/timeslots",
data: { start: data },
beforeSend: customBlockUi(this)... |
Fix translations for non present gas load and heat load
Fixes: #1538 | var D3CarrierLoadChart = (function () {
'use strict';
D3CarrierLoadChart.prototype = $.extend({}, D3LoadChart.prototype, {
emptyMessage: function () {
return $(this.chartClass).parent().find(".empty");
},
chartDataCallback: function (chartData) {
if (chartData) ... | var D3CarrierLoadChart = (function () {
'use strict';
D3CarrierLoadChart.prototype = $.extend({}, D3LoadChart.prototype, {
emptyMessage: function () {
return $(this.chartClass).parent().find(".empty");
},
chartDataCallback: function (chartData) {
if (chartData) ... |
Fix file name for Linux / case-sensitive file systems
On Linux, when running trying to run the editor, globalRootRegistry.js could not be found:
Error /home/dali/src/dreem2-dev/lib/dr/globals/globalRootRegistry.js In teemserver.js request handling. File not found, returning 404 | /** Allows a node to act as a "root" for a node hierarchy.
Events:
onready:boolean Fired when the root node has been
completely instantiated.
Attributes:
ready:boolean Indicates that this root node is now ready for use. This
starts as undefined and get... | /** Allows a node to act as a "root" for a node hierarchy.
Events:
onready:boolean Fired when the root node has been
completely instantiated.
Attributes:
ready:boolean Indicates that this root node is now ready for use. This
starts as undefined and get... |
Make the tractor beam louder | package uk.co.alynn.games.ld30;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
public class AudioEngine {
private final Map<String, Sound> m_fx = new HashMap<String, Sound>();
private static AudioEngine s_sharedEngine = null;
public ... | package uk.co.alynn.games.ld30;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
public class AudioEngine {
private final Map<String, Sound> m_fx = new HashMap<String, Sound>();
private static AudioEngine s_sharedEngine = null;
public ... |
Stop validation error notification stack
closes #3383
- Calls closePassive() if a new validation error is thrown to display
only the latest validation error | /* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';
var ForgottenController = Ember.Controller.extend(ValidationEngine, {
email: '',
submitting: false,
// ValidationEngine settings
validationType: 'forgotten',
a... | /* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';
var ForgottenController = Ember.Controller.extend(ValidationEngine, {
email: '',
submitting: false,
// ValidationEngine settings
validationType: 'forgotten',
a... |
Make progress bar visible by default. | from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
... | from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
... |
Fix qs error in history | import logging
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from pytz import timezone
from dojo.filters import LogEntryFilter
from dojo.utils import get_page_items, add_breadcrumb
localtz = timezone(settings.TIME_ZONE)
logging.basicConfig(
level=logging.DE... | import logging
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from pytz import timezone
from dojo.filters import LogEntryFilter
from dojo.utils import get_page_items, add_breadcrumb
localtz = timezone(settings.TIME_ZONE)
logging.basicConfig(
level=logging.DE... |
Add error logging to nagios wrapper | import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = ch... | import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = ch... |
Fix : fix unit test | 'use strict';
describe('Navbar directive', function() {
var scope, element;
beforeEach(module('talend.widget'));
beforeEach(module('htmlTemplates'));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<talend-navbar>' +
... | 'use strict';
describe('Navbar directive', function() {
var scope, element;
beforeEach(module('talend.widget'));
beforeEach(module('htmlTemplates'));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<talend-navbar>' +
... |
:bug: Fix error when files are not found
Using include syntax with a wrong path resulted in a crash without emitting an error message. | var aglio = require('aglio');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var defaults = require('lodash.defaults');
var path = require('path');
module.exports = function (options) {
'use strict';
// Mixes in default options.
options = defaults(optio... | var aglio = require('aglio');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var defaults = require('lodash.defaults');
var path = require('path');
module.exports = function (options) {
'use strict';
// Mixes in default options.
options = defaults(optio... |
Format description to multiple lines using RawTextHelpFormatter.
Reference:
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text
import argparse
from arg... | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
import argparse
def main():
'''
For help, use argument -h
$ ./arg-reader.py -h
To specify an argument, p... |
Make the shouldSkipProperty code more readable | <?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.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
*
* Unless requir... | <?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.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
*
* Unless requir... |
Remove phone-number and email from facilities | <div class="container">
<h2 class="headline">Liste der Hilfsgruppen in Berlin</h2>
<div class="table-responsive">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center"... | <h2 class="headline">Liste der Hilfsgruppen in Berlin</h2>
<div class="table-responsive">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center">Homepage</th>
<th class="text-cente... |
Save modal dialog now correctly imports html template
Error as a result of shufling file structure, not updating paths | import templateUrl from './save-modal-dialog.html';
/** @ngInject */
export function SaveModalDialogFactory($uibModal) {
var modalSaveDialog = {
showModal: showModal,
};
return modalSaveDialog;
function showModal(saveCallback, doNotSaveCallback, cancelCallback, okToSave) {
var modalOptions = {
... | /** @ngInject */
export function SaveModalDialogFactory($uibModal) {
var modalSaveDialog = {
showModal: showModal,
};
return modalSaveDialog;
function showModal(saveCallback, doNotSaveCallback, cancelCallback, okToSave) {
var modalOptions = {
templateUrl: 'app/components/save-modal-dialog/save-m... |
Add --inline autorefreshing to webpack dev server | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
home: path.join(__dirname, 'app/src/home'),
},
module: {
loaders: [
{
test: /\.sass$/,
loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
te... | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
home: path.join(__dirname, 'app/src/home'),
},
module: {
loaders: [
{
test: /\.sass$/,
loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
te... |
Switch yaml CLI argument from file to file path. | """
ydf/cli
~~~~~~~
Defines the command-line interface.
"""
import click
import sys
from ydf import templating, yaml_ext
@click.command('ydf')
@click.argument('yaml',
type=click.Path(dir_okay=False))
@click.option('-v', '--variables',
type=click.Path(dir_okay=False),
... | """
ydf/cli
~~~~~~~
Defines the command-line interface.
"""
import click
import sys
from ydf import templating, yaml_ext
@click.command('ydf')
@click.argument('yaml',
type=click.File('r'))
@click.option('-v', '--variables',
type=click.Path(dir_okay=False),
he... |
Make mobile streaming dialog easier to understand | package de.danoeh.antennapod.dialog;
import android.content.Context;
import androidx.appcompat.app.AlertDialog;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.util.playback.Playable;
import de.danoeh.antennapod.core.util.playback.PlaybackSe... | package de.danoeh.antennapod.dialog;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import androidx.appcompat.app.AlertDialog;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.util.playback.Playable;... |
Use eq function to ge element by index. | import cheerio from 'cheerio';
import moment from 'moment-timezone';
const originalTimeZone = 'Europe/Kiev';
const skiLiftDateFormat = 'DD.MM.YYYY HH:mm:ss';
export default function proceed(data) {
if (data.error) {
return {
errors: Object.values(data.error),
lifts: []
};
}
const cardNumbe... | import cheerio from 'cheerio';
import moment from 'moment-timezone';
const originalTimeZone = 'Europe/Kiev';
const skiLiftDateFormat = 'DD.MM.YYYY HH:mm:ss';
export default function proceed(data) {
if (data.error) {
return {
errors: Object.values(data.error),
lifts: []
};
}
const cardNumbe... |
Create directories for output if they don't already exist
Especially the downloader should do this to allow for easier
scripting. | package com.holmsted.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.annotation.Nonnull;
public class FileWriter {
public static void writeFil... | package com.holmsted.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class FileWriter {
public static void writeFile(String filename, String contents... |
Copy prototype memebers on extend | 'use strict';
var extendPrototypeWithThese = function (prototype, extendThese) {
/*
Helper method to implement a simple inheritance model for object prototypes.
*/
var outp = prototype;
if (extendThese) {
for (var i = extendThese.length - 1; i >= 0; i--) {
// ... | 'use strict';
var extendPrototypeWithThese = function (prototype, extendThese) {
/*
Helper method to implement a simple inheritance model for object prototypes.
*/
var outp = prototype;
if (extendThese) {
for (var i = extendThese.length - 1; i >= 0; i--) {
// ... |
Fix search result image sizes | import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { GEODATA_API_URL } from '@env'
const Thumbnail = ({ recordId, thumbnails, t }) => {
const hasThumbnail = thumbnails && thumbnails.length > 0
const thumbnail = hasThumbnail
? `${GEODATA_API_URL}/recor... | import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { GEODATA_API_URL } from '@env'
const Thumbnail = ({ recordId, thumbnails, t }) => {
const hasThumbnail = thumbnails && thumbnails.length > 0
const thumbnail = hasThumbnail
? `${GEODATA_API_URL}/recor... |
Clear the console when script loads | (() => {
let log = console.debug; // Can change to console.log if needed
console.clear();
let init = () => {
// The Socket.io script tag has loaded
window.ioconn = window.io.connect;
window.io.connect = function() { // The moomoo.io game client uses io.connect to establish a... | (() => {
let log = console.debug; // Can change to console.log if needed
let init = () => {
// The Socket.io script tag has loaded
window.ioconn = window.io.connect;
window.io.connect = function() { // The moomoo.io game client uses io.connect to establish a socket.io connection... |
Add debug.html to build script | var historyApiFallback = require("connect-history-api-fallback");
var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest,
middleware: [historyApiFallback()]
}
},
js: {
src... | var historyApiFallback = require("connect-history-api-fallback");
var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest,
middleware: [historyApiFallback()]
}
},
js: {
src... |
Update minimun zoom to 24 hours | /* global console, Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 86400000,
editable: {
... | /* global console, Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 600000,
editable: {
... |
Fix usage of `url_title` in TeamAdmin. | from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Person, Team
@admin.register(Person)
class PersonAdmin(SearchMetaBaseAdmin):
prepopulated_fields = {"url_title": ("first_name", "last_name",)}
filter_horizontal = ("teams",)
fieldsets = (
... | from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Person, Team
@admin.register(Person)
class PersonAdmin(SearchMetaBaseAdmin):
prepopulated_fields = {"url_title": ("first_name", "last_name",)}
filter_horizontal = ("teams",)
fieldsets = (
... |
Use enum instead of conditional | "use babel";
// @flow
import type { PlanConfig } from "../../PlanConfigurationFeature/Types/types.js.flow";
import path from "path";
import FlowDiagnostic from "./Presenters/FlowDiagnostic.js";
export default {
infos: {
name: "flow",
iconUri:
"atom://molecule-dev-environment/.storybook/public/devtool-... | "use babel";
// @flow
import type { PlanConfig } from "../../PlanConfigurationFeature/Types/types.js.flow";
import path from "path";
import FlowDiagnostic from "./Presenters/FlowDiagnostic.js";
export default {
infos: {
name: "flow",
iconUri:
"atom://molecule-dev-environment/.storybook/public/devtool-... |
Remove the doc that describes the setup. Setup is automated now | import mysql.connector
from luigi.contrib.mysqldb import MySqlTarget
import unittest
host = 'localhost'
port = 3306
database = 'luigi_test'
username = None
password = None
table_updates = 'table_updates'
def _create_test_database():
con = mysql.connector.connect(user=username,
p... | '''
$ mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 211
Server version: 5.6.15 Homebrew
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks... |
Add region in the new API route | <?php
namespace CodeDay\Clear\ModelContracts;
use \CodeDay\Clear\Models;
class Grant extends ModelContract
{
public static function getFields()
{
return [
'id' => [
'name' => 'ID',
'description' => 'The ID of the grant. Numeric.',
... | <?php
namespace CodeDay\Clear\ModelContracts;
use \CodeDay\Clear\Models;
class Grant extends ModelContract
{
public static function getFields()
{
return [
'id' => [
'name' => 'ID',
'description' => 'The ID of the grant. Numeric.',
... |
Adjust which log messages can be filtered out | package io.quarkus.runtime.logging;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.jboss.logging.Logger;
public class LogCleanupFilter implements Filter {
private Map<String, L... | package io.quarkus.runtime.logging;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.jboss.logging.Logger;
public class LogCleanupFilter implements Filter {
private Map<String, L... |
Remove ref to dead Config class | import sys
import argparse
import os
import mediachain.reader.api
def main(arguments=None):
if arguments == None:
arguments = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='mediachain-reader',
description='Mediachain Reader CLI'
)
parser.add_argument('-h', '--host',
... | import sys
import argparse
import os
import mediachain.reader.api
from mediachain.reader.api import Config
def main(arguments=None):
if arguments == None:
arguments = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='mediachain-reader',
description='Mediachain Reader CLI'
)
... |
Fix a hard-coded api root in the image viewer. | import { apiRoot, restRequest } from 'girder/rest';
import View from 'girder/views/View';
var ImageViewerWidget = View.extend({
initialize: function (settings) {
this.itemId = settings.itemId;
restRequest({
type: 'GET',
path: 'item/' + this.itemId + '/tiles'
}).done... | import { restRequest } from 'girder/rest';
import View from 'girder/views/View';
var ImageViewerWidget = View.extend({
initialize: function (settings) {
this.itemId = settings.itemId;
restRequest({
type: 'GET',
path: 'item/' + this.itemId + '/tiles'
}).done((resp) =... |
Make outlook emit single files | import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
... | import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
... |
Fix exception when required options are missing
Options can be on command line and in config file, so we check in merged
dictionary after getting from both sources. | from sys import exit
import argparse
from .commands import dispatch, choices
from .config import get_config
from .utils import merge, error
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--base-url',
dest='url',
metavar='https://redm... | from sys import exit
import argparse
from .commands import dispatch, choices
from .config import get_config
from .utils import merge
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--base-url',
metavar='https://redmine.example.com',
h... |
Change default language : en | 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
... | 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
... |
Terminate the interactive prompt upon completion | import path from 'path';
import {assign} from 'bound-native-methods/object';
import Vorpal from 'vorpal';
import JSONFilePlus from 'json-file-plus';
const cli = Vorpal();
cli.command('config', 'Configures this project.')
.action(function (args, callback) {
const {log, prompt} = this;
log();
promp... | import path from 'path';
import {assign} from 'bound-native-methods/object';
import Vorpal from 'vorpal';
import JSONFilePlus from 'json-file-plus';
const cli = Vorpal();
cli.command('config', 'Configures this project.')
.action(function (args, callback) {
const {log, prompt} = this;
log();
promp... |
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org... | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org... |
Replace the hard coded dictionary path with a variable. | <?php
namespace TuxOne\ValidationBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @Annotation
*/
class NotContainsBadWordsValidator extends ConstraintValidator
{
... | <?php
namespace TuxOne\ValidationBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @Annotation
*/
class NotContainsBadWordsValidator extends ConstraintValidator
{
... |
Add optional text to display | #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
3. (optional) Text to display (without color)
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x... | #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x':
col_char = '3'
cols... |
Add functionality to print list of parseable files | # -*- coding: utf-8 -*-
import os
import argparse
import fs_utils
from pybtex.database.input import bibtex
def main():
"""
Command-line interface
"""
parser = argparse.ArgumentParser(description="Manage BibTeX files")
parser.add_argument("-t", "--test",
action="store_true",
help="... | # -*- coding: utf-8 -*-
import os
import argparse
import fs_utils
from pybtex.database.input import bibtex
def main():
"""
Command-line interface
"""
parser = argparse.ArgumentParser(description="Manage BibTeX files")
parser.add_argument("-t", "--test",
action="store_true",
help="... |
Use proper syntax for User-Agent header | <?php
namespace Kyranb\Footprints;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
class Footprinter implements FootprinterInterface
{
protected Request $request;
protected string $random;
public function __construct()
{
$this->random = Str::r... | <?php
namespace Kyranb\Footprints;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
class Footprinter implements FootprinterInterface
{
protected Request $request;
protected string $random;
public function __construct()
{
$this->random = Str::r... |
Fix default legend type detection | from .legend import Legend
from .constants import SINGLE_LEGEND
class LegendList:
"""LegendList
Args:
legends (list, Legend): List of legends for a layer.
"""
def __init__(self, legends=None, default_legend=None, geom_type=None):
self._legends = self._init_legends(legends, de... | from .legend import Legend
from .constants import SINGLE_LEGEND
class LegendList:
"""LegendList
Args:
legends (list, Legend): List of legends for a layer.
"""
def __init__(self, legends=None, default_legend=None, geom_type=None):
self._legends = self._init_legends(legends, de... |
Add mention of Python 3.6 support | #!/usr/bin/env python
# coding=utf-8
import sys
import os
import re
from setuptools import setup
from setuptools.command.test import test as TestCommand
HERE = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = 'mailjet_rest'
VERSION = 'v1.2.2'
setup(
name=PACKAGE_NAME,
version=VERSION,
author='st... | #!/usr/bin/env python
# coding=utf-8
import sys
import os
import re
from setuptools import setup
from setuptools.command.test import test as TestCommand
HERE = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = 'mailjet_rest'
VERSION = 'v1.2.2'
setup(
name=PACKAGE_NAME,
version=VERSION,
author='st... |
Remove Ember 2.12 from Ember Try config | 'use strict';
const getChannelURL = require('ember-source-channel-url');
module.exports = function() {
return Promise.all([
getChannelURL('release'),
getChannelURL('beta'),
getChannelURL('canary')
]).then((urls) => {
return {
scenarios: [
{
name: 'ember-lts-2.16',
... | 'use strict';
const getChannelURL = require('ember-source-channel-url');
module.exports = function() {
return Promise.all([
getChannelURL('release'),
getChannelURL('beta'),
getChannelURL('canary')
]).then((urls) => {
return {
scenarios: [
{
name: 'ember-lts-2.12',
... |
Use analysis base class form helper and form building blocks | from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import InlineField
from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from analyses.forms import (
AbstractAnalysisCreat... | from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout, Submit
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from analyses.forms import AbstractAnalysisCre... |
Use io.open with UTF-8 encoding to avoid UnicodeDecodeError | import io
import os
import re
from setuptools import setup, find_packages
def find_version():
file_dir = os.path.dirname(__file__)
with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f:
version = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read())
if version:
ret... | import io
import os
import re
from setuptools import setup, find_packages
def find_version():
file_dir = os.path.dirname(__file__)
with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f:
version = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read())
if version:
ret... |
Fix expensive transform tests by increasing timeouts to 5000ms. | import assert from "assert";
import { join } from "path";
import {
readdirSync,
readFileSync,
statSync,
} from "fs";
import { compile, transform } from "../lib/compiler.js";
import { prettyPrint } from "recast";
var jsFiles = Object.create(null);
function walk(dir) {
readdirSync(dir).forEach(function (item) {... | import assert from "assert";
import { join } from "path";
import {
readdirSync,
readFileSync,
statSync,
} from "fs";
import { compile, transform } from "../lib/compiler.js";
import { prettyPrint } from "recast";
var jsFiles = Object.create(null);
function walk(dir) {
readdirSync(dir).forEach(function (item) {... |
Add logging to keyword data migration | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-02 15:46
from __future__ import unicode_literals
from django.db import migrations, models
def forward(apps, schema_editor):
Keyword = apps.get_model('events', 'Keyword')
for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclu... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-02 15:46
from __future__ import unicode_literals
from django.db import migrations, models
def forward(apps, schema_editor):
Keyword = apps.get_model('events', 'Keyword')
for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclu... |
Remove last references to flatpage so it doesnt show up on admin page | # -*- encoding: UTF-8 -*-
from core import settings as stCore
from django import forms
from django.conf import settings as st
from flatpages_i18n.forms import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
... | # -*- encoding: UTF-8 -*-
from core import settings as stCore
from django import forms
from django.conf import settings as st
from django.contrib.flatpages.admin import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageF... |
FIX Import missing namespace for RunBuildTaskJob | <?php
use Heyday\Elastica\ReindexTask;
use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Jobs\RunBuildTaskJob;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;
/**
* These regular updates run as often as is practical.
* They seem to take 2-3 hours at t... | <?php
use Heyday\Elastica\ReindexTask;
use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;
/**
* These regular updates run as often as is practical.
* They seem to take 2-3 hours at the moment, so we run them 4 times per day.
*/... |
Fix most umd export name
See https://unpkg.com/most@1.4.0/dist/most.js | /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarget:... | /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader'],
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarge... |
Add the command that failed to the error log and the error email to help debug problems where the error produces no output. | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self... | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self... |
Update coverage thresholds to current values | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
... | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
... |
Include the uuid with the user attributes | <?php
namespace Sil\SilAuth\saml;
class User
{
public static function convertToSamlFieldNames(
string $employeeId,
string $firstName,
string $lastName,
string $username,
string $email,
string $uuid,
string $idpDomainName,
$passwordExpirationDate,
... | <?php
namespace Sil\SilAuth\saml;
class User
{
public static function convertToSamlFieldNames(
string $employeeId,
string $firstName,
string $lastName,
string $username,
string $email,
string $uuid,
string $idpDomainName,
$passwordExpirationDate,
... |
Work around issue with coveralls lib. | /*
* grunt-contrib-jshint
* http://gruntjs.com/
*
* Copyright (c) 2015 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'tasks/**/*.js', 'test/**/*.js'],
options: {
... | /*
* grunt-contrib-jshint
* http://gruntjs.com/
*
* Copyright (c) 2015 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'tasks/**/*.js', 'test/**/*.js'],
options: {
... |
Enable task addition to the database | angular.module('MainApp')
.controller('FabControl', ($mdToast, $mdDialog, $scope, addToDB) => {
$scope.addNew = (ev) => {
$mdDialog.show({
controller: DialogController,
templateUrl: 'templates/newTaskDialog.html',
parent: angular.element(document.body),
targetEvent: e... | angular.module('MainApp')
.controller('FabControl', ($mdToast, $mdDialog, $scope, addToDB) => {
$scope.addNew = (ev) => {
$mdDialog.show({
controller: DialogController,
templateUrl: 'templates/newTaskDialog.html',
parent: angular.element(document.body),
targetEvent: e... |
Fix unable to revert resolving of SQLinjection
[1] Revert back code for replaceAll
[2] Revert 2 resolve strings one by one |
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
... |
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
... |
Add require statement for api | var api = require('./api');
module.exports = {
login(username, password, callback) {
api.login(username, password)
.then((response) => {
if(response.status === 400){
if(callback) {
callback(false);
}
} else if (response.status === 200) {
console.log("$$$$$$$$", ... |
module.exports = {
login(username, password, callback) {
api.login(username, password)
.then((response) => {
if(response.status === 400){
if(callback) {
callback(false);
}
} else if (response.status === 200) {
console.log("$$$$$$$$", document.cookie);
r... |
Add link explaining why componentWillMount is used. | import './app.styl';
import * as state from '../state';
import Component from '../components/component.react';
import Footer from './footer.react';
import Menu from './menu.react';
import React from 'react';
import persistState from './persiststate.react';
import {RouteHandler} from 'react-router';
// Remember to impo... | import './app.styl';
import * as state from '../state';
import Component from '../components/component.react';
import Footer from './footer.react';
import Menu from './menu.react';
import React from 'react';
import persistState from './persiststate.react';
import {RouteHandler} from 'react-router';
// Remember to impo... |
Use play scene if no show scene for filtering in admin | "use strict";
let Schedule = require('models/schedule');
module.exports = function(router) {
router.get('/', function (req, res, next) {
if (!req.filter) return next();
let filter = req.filter;
Schedule.findOne(filter)
.populate('shows.theatre shows.scene shows.play')
... | "use strict";
let Schedule = require('models/schedule');
module.exports = function(router) {
router.get('/', function (req, res, next) {
if (!req.filter) return next();
let filter = req.filter;
Schedule.findOne(filter)
.populate('shows.theatre shows.scene shows.play')
... |
Use [job.title] as genealogy of input_handler.save while submit job. | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions.
"""
# built-in modules
import json
# 3rd-party modules
from botocore.client import Config
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
def submit(job, protocol=None, priority=1, sched... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions.
"""
# built-in modules
import json
# 3rd-party modules
from botocore.client import Config
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
def submit(job, protocol=None, priority=1, sched... |
Add output of command in hex | #!/usr/bin/env python
# Copyright 2014 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | #!/usr/bin/env python
# Copyright 2014 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
Remove promise where not needed | (function(){
var mod = angular.module('caspy.api', ['ngResource', 'caspy.server']);
mod.config(['$resourceProvider',
function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]
);
mod.factory('caspyAPI',
['$q', '$http', '$resource', 'Constants',
function($q, $htt... | (function(){
var mod = angular.module('caspy.api', ['ngResource', 'caspy.server']);
mod.config(['$resourceProvider',
function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]
);
mod.factory('caspyAPI',
['$q', '$http', '$resource', 'Constants',
function($q, $htt... |
Enable remote, rmessage and rnotify plugins by default | # Module: defaults
# Date: 14th May 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""defaults - System Defaults
This module contains default configuration and sane defaults for various
parts of the system. These defaults are used by the environment initially
when no environment has been ... | # Module: defaults
# Date: 14th May 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""defaults - System Defaults
This module contains default configuration and sane defaults for various
parts of the system. These defaults are used by the environment initially
when no environment has been ... |
Clone the attribution link, which is alreaady an <a> in order to get the correct link. | "use strict";
angular.module("hikeio").
directive("fancybox", ["$rootScope", function($rootScope) {
return {
link: function (scope, element, attrs) {
var context = {
afterLoad: function(current, previous) {
$rootScope.$broadcast("fancyboxLoaded");
var attributionLink = this.element.attr("dat... | "use strict";
angular.module("hikeio").
directive("fancybox", ["$rootScope", function($rootScope) {
return {
link: function (scope, element, attrs) {
var context = {
afterLoad: function(current, previous) {
$rootScope.$broadcast("fancyboxLoaded");
var attributionLink = this.element.attr("dat... |
Make slide start and end optional | <?php
namespace Zeropingheroes\Lanager\Requests;
class StoreSlideRequest extends Request
{
use LaravelValidation;
/**
* Whether the request is valid
*
* @return bool
*/
public function valid(): bool
{
$this->validationRules = [
'lan_id' => ['require... | <?php
namespace Zeropingheroes\Lanager\Requests;
class StoreSlideRequest extends Request
{
use LaravelValidation;
/**
* Whether the request is valid
*
* @return bool
*/
public function valid(): bool
{
$this->validationRules = [
'lan_id' => ['require... |
Support only python >= 3.4 | import os
import re
import sys
from setuptools import setup, find_packages
PY_VER = sys.version_info
if PY_VER >= (3, 4):
pass
else:
raise RuntimeError("Only support Python version >= 3.4")
def get_version():
with open(os.path.join(os.path.dirname(__file__), 'gitlab_mr.py')) as f:
for line in f... | import os
import re
from setuptools import setup, find_packages
def get_version():
with open(os.path.join(os.path.dirname(__file__), 'gitlab_mr.py')) as f:
for line in f.readlines():
m = re.match(r"__version__ = '(.*?)'", line)
if m:
return m.group(1)
raise Valu... |
Correct docs on RabbitMQ crash source. | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import ... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import ... |
Fix name of index created for tests. | # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--s... | # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--s... |
Replace "question" with "step" in Newtrip buttons | function set_correct_origin(prev, last) {
$(last).find("input[id*='origin_auto']").prop("disabled", true).val($(prev).find("input[id*='destination_auto']").val());
$(last).find("input[type='number'][id*='origin']").val($(prev).find("input[type='number'][id*='destination']").val());
}
$(function () {
$(".in... | function set_correct_origin(prev, last) {
$(last).find("input[id*='origin_auto']").prop("disabled", true).val($(prev).find("input[id*='destination_auto']").val());
$(last).find("input[type='number'][id*='origin']").val($(prev).find("input[type='number'][id*='destination']").val());
}
$(function () {
$(".in... |
Make the cookie only add pages lazily | /* Collapse remember
* Use a cookie to "remember" the state of bootstrap collapse divs
* use the 'collapse-remember' class to get this functionality
*/
$(document).ready(function () {
const state_cookie_c = 'collapse-remember';
var page = window.location.pathname;
var state = Cookies.getJSON(state_cookie... | /* Collapse remember
* Use a cookie to "remember" the state of bootstrap collapse divs
* use the 'collapse-remember' class to get this functionality
*/
$(document).ready(function () {
const state_cookie_c = 'collapse-remember';
var page = window.location.pathname;
var state = Cookies.getJSON(state_cookie... |
Fix bad habit caused by c++ programming | package com.skelril.aurora.prayer.PrayerFX;
import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Author: Turtle9598
*/
public cla... | package com.skelril.aurora.prayer.PrayerFX;
import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Author: Turtle9598
*/
public cla... |
Make the alarm list in Vitrage Topology view related to the selected entity
Change-Id: I1de754ada13262ffa0f7a76de2c1b390f31a36f6
story: #2004725
task: # 28763 | angular
.module('horizon.dashboard.project.vitrage')
.directive('hzAlarms', hzAlarms);
function hzAlarms() {
var directive = {
templateUrl: STATIC_URL + 'dashboard/project/components/alarms/alarms.html',
restrict: 'E',
scope: {
selected: '='
},
controller: AlarmsController,
controll... | angular
.module('horizon.dashboard.project.vitrage')
.directive('hzAlarms', hzAlarms);
function hzAlarms() {
var directive = {
templateUrl: STATIC_URL + 'dashboard/project/components/alarms/alarms.html',
restrict: 'E',
scope: {
selected: '='
},
controller: AlarmsController,
controll... |
Return all most frequent subsequences | import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
... | import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
... |
Use the ECMASCRIPT5_STRICT flag otherwise AngularJS dies |
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
from django.core.exceptions import ImproperlyConfigured
class ClosureCompiler(Processor):
def modify_expected_output_filenames(self, filenames):
... |
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
from django.core.exceptions import ImproperlyConfigured
class ClosureCompiler(Processor):
def modify_expected_output_filenames(self, filenames):
... |
Reset search results on new search | (function () {
'use strict';
angular
.module('app')
.controller('MenuController', MenuController);
MenuController.$inject = ['$scope', 'UserService', '$rootScope', 'SearchService', 'TranslateService'];
function MenuController($scope, UserService, $rootScope, SearchService, TranslateSe... | (function () {
'use strict';
angular
.module('app')
.controller('MenuController', MenuController);
MenuController.$inject = ['$scope', 'UserService', '$rootScope', 'SearchService', 'TranslateService'];
function MenuController($scope, UserService, $rootScope, SearchService, TranslateSe... |
Fix typos and grammar errors | {
"%d unread message": {
"one": "%d непрочитане повідомлення",
"other": "%d непрочитаних повідомлень"
},
"Unread messages in %%s, %%s and one other": {
"one": "Непрочитані повідомлення в %%s, %%s і ще одному каналі",
"other": "Непрочитані повідомлення в %%s, %%s і в %d інших каналах"
},
"Unread messages in... | {
"%d unread message": {
"one": "%d непрочитане повідомлення",
"other": "%d непрочитаних пвідомлень"
},
"Unread messages in %%s, %%s and one other": {
"one": "Непрочитані повідомлення в %%s, %%s і ще одному",
"other": "Непрочитані повідомлення в %%s, %%s і в %d інших"
},
"Unread messages in %s": "Непрочита... |
Exclude tests and include sql files in cnx-authoring package
Remove include_package_data=True as it looks for MANIFEST.in instead of
using the package_data that we specified in setup.py.
Tested by running:
```bash
rm -rf cnx_authoring.egg-info dist
python setup.py sdist
```
Close #51 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
... |
fix: Update correct snapper when options change | angular.module('snap')
.directive('snapContent', ['snapRemote', function (snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = {
element: element[0]
};
a... | angular.module('snap')
.directive('snapContent', ['snapRemote', function (snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = {
element: element[0]
};
a... |
Change load date to be constant per loading event | 'use strict';
var through = require('through2');
var formatAddress = require('../lib/formatAddress');
var loadDate = Date.now();
module.exports = function(addr, city, state, zip){
if(!addr) throw new Error('Must provide address at minimum.');
var args = [addr, city, state, zip];
var prefix = '';
var suffix = ... | 'use strict';
var through = require('through2');
var formatAddress = require('../lib/formatAddress');
module.exports = function(addr, city, state, zip){
if(!addr) throw new Error('Must provide address at minimum.');
var args = [addr, city, state, zip];
var prefix = '';
var suffix = '';
//Chunk is a GeoJSON... |
Use more descriptive test constant names | import chai from 'chai';
import React from 'react';
import {
findRenderedDOMComponentWithTag,
renderIntoDocument
} from 'react-addons-test-utils';
import ReactSVG from '../src';
chai.should();
describe('react-svg', () => {
describe('while rendering', () => {
it('should add the className to the rendered com... | import chai from 'chai';
import React from 'react';
import {
findRenderedDOMComponentWithTag,
renderIntoDocument
} from 'react-addons-test-utils';
import ReactSVG from '../src';
chai.should();
describe('react-svg', () => {
describe('while rendering', () => {
it('should add the className to the rendered com... |
Check if all sequences are of the same length | import logging
__author__ = "Antonio J. Nebro"
__license__ = "GPL"
__version__ = "1.0-SNAPSHOT"
__status__ = "Development"
__email__ = "antonio@lcc.uma.es"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Score:
""" Class representing MSA (Multiple Sequence Alignment) scores
... | import logging
__author__ = "Antonio J. Nebro"
__license__ = "GPL"
__version__ = "1.0-SNAPSHOT"
__status__ = "Development"
__email__ = "antonio@lcc.uma.es"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Score:
""" Class representing MSA (Multiple Sequence Alignment) scores
... |
Fix grunt errors in node > 6 | /*global module:false*/
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
exec: {
removeDocs: "rm -rf docs/*",
createDocs: 'coddoc -f multi-html -d ./lib --dir ./docs'
},
jshint: {
... | /*global module:false*/
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
exec: {
removeDocs: "rm -rf docs/*",
createDocs: 'coddoc -f multi-html -d ./lib --dir ./docs'
},
jshint: {
... |
Disable Admin controller user acl | <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/... | <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/... |
Fix eslint ts override tsx matching | module.exports = {
extends: ["matrix-org"],
plugins: [
"babel",
],
env: {
browser: true,
node: true,
},
rules: {
"no-var": ["warn"],
"prefer-rest-params": ["warn"],
"prefer-spread": ["warn"],
"one-var": ["warn"],
"padded-blocks": [... | module.exports = {
extends: ["matrix-org"],
plugins: [
"babel",
],
env: {
browser: true,
node: true,
},
rules: {
"no-var": ["warn"],
"prefer-rest-params": ["warn"],
"prefer-spread": ["warn"],
"one-var": ["warn"],
"padded-blocks": [... |
Fix another bug related to logging dataset errors
OIPA-612 / #589 | import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(loc... | import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(loc... |
Fix "Missing translation key for 'null'" | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { get } from '../../store';
import { areWeFunYet, translate as $t } from '../../helpers';
import ExternalLink from './external-link.js';
import DisplayIf from './display-if';
let showLicense = areWeFunYet();
... | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { get } from '../../store';
import { areWeFunYet, translate as $t } from '../../helpers';
import ExternalLink from './external-link.js';
import DisplayIf from './display-if';
let showLicense = areWeFunYet();
... |
Add option for adding a callback | 'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
if (!opts) opts = {};
function minifier(req, res, next) {
var sendMinified = function (callback) {
// No callbak specified, just minify and send to client.
if (typeof callback === 'undefi... | 'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
if (!opts) opts = {};
function minifier(req, res, next) {
var sendMinified = function (err, html) {
if (err) {
console.error(err)
if (opts.displayErrors === true) {
... |
Remove grant types form field | <?php
namespace App\Form\OAuth;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ClientType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
... | <?php
namespace App\Form\OAuth;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ClientType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
... |
Support configuration with no hidden-layer | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chain... | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chain... |
Fix error in UCB1 algorithm | package com.danisola.bandit;
public class Ucb1Algorithm extends AbstractBanditAlgorithm {
public Ucb1Algorithm(int numArms, UpdateStrategy updateStrategy) {
super(numArms, updateStrategy);
}
@Override
public int selectArm() {
int totalCount = 0;
for (int i = 0; i < counts.leng... | package com.danisola.bandit;
public class Ucb1Algorithm extends AbstractBanditAlgorithm {
public Ucb1Algorithm(int numArms, UpdateStrategy updateStrategy) {
super(numArms, updateStrategy);
}
@Override
public int selectArm() {
int totalCount = 0;
for (int i = 0; i < counts.leng... |
Add menu title to MenuWidget output | "use strict";
const Widget = require('../../layout/widget');
const Item = require('../../router/item');
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class menuWidget extends Widget {
constructor(data={}, engine) {
super(data);
this.engine = engine;
['id', 't... | "use strict";
const Widget = require('../../layout/widget');
const Item = require('../../router/item');
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class menuWidget extends Widget {
constructor(data={}, engine) {
super(data);
this.engine = engine;
['id', 't... |
Use OPENSSL_REFCNT instead of OPENSSL as our SSL provider when possible. | package com.relayrides.pushy.apns;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class for choosing SSL providers.
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*
* @since 0.10
*/
class S... | package com.relayrides.pushy.apns;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class for choosing SSL providers.
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*
* @since 0.10
*/
class S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.