text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix tokenization of +1/-1 emojis | import lunr from 'lunr'
import data from '../../data'
var index = lunr(function() {
this.pipeline.reset()
this.field('short_name', { boost: 2 })
this.field('emoticons')
this.field('name')
this.ref('id')
})
for (let emoji in data.emojis) {
let emojiData = data.emojis[emoji],
{ short_name, name, emo... | import lunr from 'lunr'
import data from '../../data'
var index = lunr(function() {
this.pipeline.reset()
this.field('short_name', { boost: 2 })
this.field('emoticons')
this.field('name')
this.ref('id')
})
for (let emoji in data.emojis) {
let emojiData = data.emojis[emoji],
{ short_name, name, emo... |
Add zebra background color for table section. | W.TableSections = function () {
var win = UI.Win({title:'Table Sections'});
// Create the first TableViewSections.
var section1 = Ti.UI.createTableViewSection({headerTitle:'Header 1'});
// Add some rows to this table.
for (var i = 0; i < 4; i++) {
section1.add(Ti.UI.createTableViewRow({
title:'Ro... | W.TableSections = function () {
var win = UI.Win({title:'Table Sections'});
// Create the first TableViewSections.
var section1 = Ti.UI.createTableViewSection({headerTitle:'Header 1'});
// Add some rows to this table.
for (var i = 0; i < 4; i++) {
section1.add(Ti.UI.createTableViewRow({
title:'Ro... |
Increase concurrent access in tests | package utils
import (
"math/rand"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRandomString(t *testing.T) {
rand.Seed(42)
s1 := RandomString(10)
s2 := RandomString(20)
rand.Seed(42)
s3 := RandomString(10)
s4 := RandomString(20)
assert.Len(t, s1, 10)
assert.Len(t, s2, 20)
assert.Le... | package utils
import (
"math/rand"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRandomString(t *testing.T) {
rand.Seed(42)
s1 := RandomString(10)
s2 := RandomString(20)
rand.Seed(42)
s3 := RandomString(10)
s4 := RandomString(20)
assert.Len(t, s1, 10)
assert.Len(t, s2, 20)
assert.Le... |
WIP: Enable operations that write to the DB to be rolled back on error
by wrapping them in transactions.
Clean up: Make LabeledNodeWithPropertiesManager class abstract. | package managers.nodes;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import managers.functions.JsonFunction;
import models.nodes.LabeledNodeWithProperties;
import models.nodes.Node;
import neo4play.Neo4jService;
import play.libs.F.Promise;
import play.libs.WS;
public abstract class LabeledN... | package managers.nodes;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import managers.functions.JsonFunction;
import models.nodes.LabeledNodeWithProperties;
import models.nodes.Node;
import neo4play.Neo4jService;
import play.libs.F.Promise;
import play.libs.WS;
public class LabeledNodeWithPr... |
Refactor: Break number apart into digits using math instead of string operations. | package org.asaph.happynumber;
import java.util.HashSet;
import java.util.Set;
public class HappyNumber {
public static int nextNumber(int number) {
int sum = 0;
while (number != 0) {
int digit = number % 10;
sum += digit * digit;
number = (number - digit) / 10;
}
return sum;
}
public static bool... | package org.asaph.happynumber;
import java.util.HashSet;
import java.util.Set;
public class HappyNumber {
public static int nextNumber(int number) {
String numberString = Integer.toString(number);
int sum=0;
for (int i=0, length=numberString.length(); i<length; i++) {
char ch = numberString.charAt(i);
in... |
Fix className warning (toString bem-cn) | import React from 'react'
import PropTypes from 'prop-types'
import block from '../../../helpers/bem-cn'
import './Row.css'
const row = block('j-row')
const column = block('j-col')
const propTypes = {
children: PropTypes.node,
col: PropTypes.bool,
className: PropTypes.string
}
const emptyRow = (className, cn... | import React from 'react'
import PropTypes from 'prop-types'
import block from '../../../helpers/bem-cn'
import './Row.css'
const row = block('j-row')
const column = block('j-col')
const propTypes = {
children: PropTypes.node,
col: PropTypes.bool,
className: PropTypes.string
}
const emptyRow = (className, cn... |
Update page title to match others. | <?php
include '_templates/sitewide.php';
$page['name'] = '403';
$page['title'] = 'Access Denied ⋅ elementary';
include $template['header'];
?>
<script>
ga('send', 'event', '403: Forbidden', window.location.host);
</script>
<div class="row">
<div class="column alert">
<i class="war... | <?php
include '_templates/sitewide.php';
$page['name'] = '403';
$page['title'] = 'Forbidden ⋅ elementary';
include $template['header'];
?>
<script>
ga('send', 'event', '403: Forbidden', window.location.host);
</script>
<div class="row">
<div class="column alert">
<i class="warning... |
Make Settings object accessible through $rootScope | Controllers.controller("ToolbarCtrl", ["$scope", "$rootScope", "Connection", "User", "Settings", function ($scope, $rootScope, Connection, User, Settings)
{
$scope.user = User.get("~");
$scope.settings = $.parseJSON($.cookie("settings") || "{}");
$rootScope.settings = $scope.settings;
$scope.setAway... | Controllers.controller("ToolbarCtrl", ["$scope", "$rootScope", "Connection", "User", "Settings", function ($scope, $rootScope, Connection, User, Settings)
{
$scope.user = User.get("~");
$scope.settings = $.parseJSON($.cookie("settings") || "{}");
$scope.setAway = function ()
{
if ($scope.user... |
Attach js to the turbolink load event | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative ... | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative ... |
Refactor repeated checking to a helper method. | // Obtain ALL anchors on the page.
var links = document.links;
// The previous/next urls if they exist.
var prev = findHref("prev");
var next = findHref("next");
/**
* Find the href for a given name.
* @param {String} name - The name of the anchor to search for.
* @return {String} The href for a given tag, otherwi... | // Obtain ALL anchors on the page.
var links = document.links;
// The previous/next urls if they exist.
var prev = findHref("prev");
var next = findHref("next");
/**
* Find the href for a given name.
* @param {String} The name of the anchor to search for.
* @return {String} The href for a given tag, otherwise an e... |
Update exception copy with function name | <?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-decla... | <?php
/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-decla... |
Change name of local variable | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
import segment
def calc_adjacency_matrix(label_img, n_region):
A = numpy.diag([1] * n_region)
h, w = label_img.shape[0], label_img.shape[1]
for y in range(h):
for x in range(w):
here = label_img[y, x]
if y < h - 1:
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
import segment
def calc_adjacency_matrix(label_img, n_region):
adjacency = numpy.diag([1] * n_region)
h, w = label_img.shape[0], label_img.shape[1]
for y in range(h):
for x in range(w):
here = label_img[y, x]
if y <... |
Format `Delete` as “⌦” on macOS
“Delete” is the wrong label to show humans for keyboard shortcuts using
the `Delete` key on macOS, because Apple label their `Backspace` key
“Delete”, and they don’t tend to have a dedicated `Delete` key. On most
or all keyboards they sell now, Fn-Delete is what’s actually required to
g... | import '../core/String'; // For String#capitalise
import { isMac } from '../ua/UA';
const platformKeys = {
ArrowUp: '↑',
ArrowDown: '↓',
ArrowRight: '→',
ArrowLeft: '←',
Alt: isMac ? '⌥' : 'Alt-',
Cmd: isMac ? '⌘' : 'Ctrl-',
Ctrl: isMac ? '⌃' : 'Ctrl-',
Meta: isMac ? '⌘' : 'Meta-',
... | import '../core/String'; // For String#capitalise
import { isMac } from '../ua/UA';
const platformKeys = {
ArrowUp: '↑',
ArrowDown: '↓',
ArrowRight: '→',
ArrowLeft: '←',
Alt: isMac ? '⌥' : 'Alt-',
Cmd: isMac ? '⌘' : 'Ctrl-',
Ctrl: isMac ? '⌃' : 'Ctrl-',
Meta: isMac ? '⌘' : 'Meta-',
... |
Use a while loop rather than a c-style for loop | package com.maxmind.geoip2.record;
import java.util.*;
import org.json.*;
public abstract class RecordWithNames {
private HashMap<String, String> names;
private Integer geoNameId;
private Integer confidence;
protected RecordWithNames(JSONObject json) throws JSONException {
geoNameId = json.g... | package com.maxmind.geoip2.record;
import java.util.*;
import org.json.*;
public abstract class RecordWithNames {
private HashMap<String, String> names;
private Integer geoNameId;
private Integer confidence;
protected RecordWithNames(JSONObject json) throws JSONException {
geoNameId = json.g... |
Fix imports for Django 1.6 and above | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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
#
# ... | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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
#
# ... |
Fix compatibility with newer apispec | from collections import defaultdict
from flask import current_app
from .operation import Operation
from .utils import flask_path_to_swagger, get_state
rules = {}
def schema_path_helper(spec, path, view, **kwargs):
"""Path helper that uses resty views
:param view: an `ApiView` object
"""
resource =... | from collections import defaultdict
from flask import current_app
from .operation import Operation
from .utils import flask_path_to_swagger, get_state
rules = {}
def schema_path_helper(spec, path, view, **kwargs):
"""Path helper that uses resty views
:param view: an `ApiView` object
"""
resource =... |
Fix removal of antecedent '?' or '&' in fidRemove | (function($, undefined) {
// Is History API reliably supported? (based on Modernizr & PJAX)
if (!(window.history && history.pushState && window.history.replaceState && !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/))) return;
// thx to @ic (http://forum.nette.org/cs/profile.php?i... | (function($, undefined) {
// Is History API reliably supported? (based on Modernizr & PJAX)
if (!(window.history && history.pushState && window.history.replaceState && !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/))) return;
// thx to @ic (http://forum.nette.org/cs/profile.php?i... |
Comment out the google ads
git-svn-id: 798f9e0ce1eefcecf757a5f2b692a26d86a9651c@418 c66dcb5a-e80b-0410-ab0e-bb6a4f3ddef9 | <?php
/**
* HTML footer
*
* @url $URL$
* @date $Date$
* @version $Revision$
* @author $Author$
*
* @package Beirdobot
*
/**/
?>
<hr >
<p>IRC Logs collected by
<a href="http://trac.beirdo.ca/projects/beirdobot/">BeirdoBot</a>.<br />
Please use the above link to report any bugs.
</p... | <?php
/**
* HTML footer
*
* @url $URL$
* @date $Date$
* @version $Revision$
* @author $Author$
*
* @package Beirdobot
*
/**/
?>
<hr >
<p>IRC Logs collected by
<a href="http://trac.beirdo.ca/projects/beirdobot/">BeirdoBot</a>.<br />
Please use the above link to report any bugs.
</p... |
Fix installing packages with blueprint | /* global module */
const postCSSCompilingPackages = [
{ name: 'broccoli-funnel', target: '^1.1.0' },
{ name: 'broccoli-merge-trees',target: '^1.2.1' },
{ name: 'broccoli-postcss-single', target: '^1.2.0' },
{ name: 'postcss-cssnext', target: '^2.9.0' },
{ name: 'postcss-import', target: '^9.0.0' }
];
modul... | /* global module */
const postCSSCompilingPackages = [
{ name: 'broccoli-funnel', target: '^1.1.0' },
{ name: 'broccoli-merge-trees',target: '^1.2.1' },
{ name: 'broccoli-postcss-single', target: '^1.2.0' },
{ name: 'postcss-cssnext', target: '^2.9.0' },
{ name: 'postcss-import', target: '^9.0.0' }
];
modul... |
Test to validate trimming scenario | from grazer.core import crawler
from bs4 import BeautifulSoup
def test_extract_links():
text = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were... | from grazer.core import crawler
from bs4 import BeautifulSoup
def test_extract_links():
text = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were... |
Add signing to custom-sidebar integration. | // Deps
var crypto = require('crypto');
var express = require('express');
var bodyParser = require('body-parser');
// Config:
var port = process.env.PORT || 8000;
var root = __dirname + '/';
var sendFileConfig = { root: root };
var secret = '123abc';
// App:
var app = express();
var bodyParserMiddleware = bodyParser.... | // Deps
var express = require('express');
var bodyParser = require('body-parser');
// Config:
var port = process.env.PORT || 8000;
var root = __dirname + '/';
var sendFileConfig = { root: root };
// App:
var app = express();
app.use(bodyParser.urlencoded());
app.get('/', function (req, res) {
res.sendFile('index.h... |
Fix broken camel art and add a better message | 'use strict';
var chalk = require('chalk');
var greetings = '\n' +
chalk.yellow(' ,,__ \n') +
chalk.yellow(" .. .. / o._) .---. \n") +
chalk.yellow(" /--'/--\ \-'|| .----. .' '. \n") +
chalk.yellow(" / \_/ / | ... | var chalk = require('chalk');
var greetings = "" +
chalk.yellow(" .. .. / o._) .---.") +
chalk.yellow(" /--'/--\ \-'|| .----. .' '.") +
chalk.yellow(" / \_/ / | .' '..' '-.") +
chalk.yellow(".'\ \__\ __.'.' .' ì-._")... |
Add methods for 403 and 409 HTTP errors | <?php namespace Neomerx\JsonApi\Contracts\Integration;
/**
* Copyright 2015 info@neomerx.com (www.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.or... | <?php namespace Neomerx\JsonApi\Contracts\Integration;
/**
* Copyright 2015 info@neomerx.com (www.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.or... |
Fix for broken payload when no internal actions | const _ = require('lodash');
const Client = require('ci-client');
const commands = require('./commands');
module.exports.start = (commonConfig) => {
const commandNames = _.flatten(commands.map(cmd => cmd.commands));
console.log('Internal commands found', commandNames);
const clientConfig = Object.assign(... | const _ = require('lodash');
const Client = require('ci-client');
const commands = require('./commands');
module.exports.start = (commonConfig) => {
const commandNames = _.flatten(commands.map(cmd => cmd.commands));
console.log('Internal commands found', commandNames);
const clientConfig = Object.assign(... |
Add support for Node.js v4 and v5 | 'use strict'; // eslint-disable-line strict, lines-around-directive
const socketIo = require('socket.io');
const gatherOsMetrics = require('./gather-os-metrics');
let io;
module.exports = (server, spans) => {
if (io === null || io === undefined) {
io = socketIo(server);
io.on('connection', (socket) => {
... | const socketIo = require('socket.io');
const gatherOsMetrics = require('./gather-os-metrics');
let io;
module.exports = (server, spans) => {
if (io === null || io === undefined) {
io = socketIo(server);
io.on('connection', (socket) => {
socket.emit('start', spans);
socket.on('change', () => {
... |
Remove no longer needed python libs | #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file_... | #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file_... |
Fix inline script visibility in enum handler | 'use strict';
var assign = require('es5-ext/object/assign')
, mixin = require('es5-ext/object/mixin')
, d = require('d')
, autoBind = require('d/auto-bind')
, DOMRadio = require('dbjs-dom/input/enum').Radio
, RadioBtnGroup = require('./_inline-button-group')
, createOp... | 'use strict';
var mixin = require('es5-ext/object/mixin')
, d = require('d')
, DOMRadio = require('dbjs-dom/input/enum').Radio
, RadioBtnGroup = require('./_inline-button-group')
, createOption = DOMRadio.prototype.createOption
, Radio;
module.exports = Radio = function (document, ... |
Add print statement to indicate server is running | package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hostname", hostnameHandler)
http.HandleFunc("/time", timeHandler)
http.HandleFunc("/issue", issueHandler)
fmt.Println("Serving on port 3000...")
http.ListenAndServe(":3000", nil)
}
func hostnameHandler(w http.ResponseWriter, r *http.Requ... | package main
import "net/http"
func main() {
http.HandleFunc("/hostname", hostnameHandler)
http.HandleFunc("/time", timeHandler)
http.HandleFunc("/issue", issueHandler)
http.ListenAndServe(":3000", nil)
}
func hostnameHandler(w http.ResponseWriter, r *http.Request) {
hostname, err := hostname()
if err != nil {... |
Make main template really configurable again | "use strict";
angular.module(
'arethusa', [
'mm.foundation',
'ngRoute',
'arethusa.core',
'arethusa.morph',
'arethusa.hist'
],
function($routeProvider) {
$routeProvider.when('/', {
controller: 'MainCtrl',
template: '<div ng-include="template"></div>',
resolve: {
l... | "use strict";
angular.module(
'arethusa', [
'mm.foundation',
'ngRoute',
'arethusa.core',
'arethusa.morph',
'arethusa.hist'
],
function($routeProvider) {
$routeProvider.when('/', {
controller: 'MainCtrl',
templateUrl: 'templates/main2.html',
resolve: {
loadConfigu... |
Add 'rb' to open() to support python 3 | from distutils.extension import Extension
from setuptools import setup, Extension
from Cython.Distutils import build_ext
import os.path
here = os.path.dirname(os.path.abspath(__file__))
ext_modules = [Extension("sass",
["sass.pyx"],
libraries=["sass", 'stdc++']
)]
setup(
name = 'sass',
cmdclass = ... | from distutils.extension import Extension
from setuptools import setup, Extension
from Cython.Distutils import build_ext
import os.path
here = os.path.dirname(os.path.abspath(__file__))
ext_modules = [Extension("sass",
["sass.pyx"],
libraries=["sass", 'stdc++']
)]
setup(
name = 'sass',
cmdclass = ... |
Remove unneeded Mocha require statement | 'use strict';
const gulpopen = require('../');
const os = require('os');
describe('gulp-open', function() {
const browser = os.platform() === 'linux' ? 'google-chrome' : (
os.platform() === 'darwin' ? 'google chrome' : (
os.platform() === 'win32' ? 'chrome' : 'firefox'));
describe('opening files', fun... | 'use strict';
const gulpopen = require('../');
const os = require('os');
require('mocha');
describe('gulp-open', function() {
const browser = os.platform() === 'linux' ? 'google-chrome' : (
os.platform() === 'darwin' ? 'google chrome' : (
os.platform() === 'win32' ? 'chrome' : 'firefox'));
describe('o... |
Store actual target for actual rule in rule struct | package main
import (
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
type Rules struct {
Rules []Rule
}
type Rule struct {
Description string `yaml:"description"`
EventPattern string `yaml:"event_pattern"`
Name string `yaml:"name"`
ScheduleExpres... | package main
import (
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
type Rules struct {
Rules []Rule
}
type Rule struct {
Description string `yaml:"description"`
EventPattern string `yaml:"event_pattern"`
Name string `yaml:"name"`
ScheduleExpres... |
Fix related box going over footer | $(function(){
function checkOverflow(){
var $related = $(".related-positioning");
if($related.length !== 0 && $related.css('position') == 'fixed') {
var viewPort = $(window).height();
var relatedBox = $(".related").height();
var boxOffset = $related.position().top;
if(relatedBox > (vie... | $(function(){
function checkOverflow(){
var $related = $(".related-positioning");
if($related.length !== 0 && $related.css('position') == 'fixed') {
var viewPort = $(window).height();
var relatedBox = $(".related").height();
var boxOffset = $related.position().top;
if(relatedBox > (vie... |
Rename menu pick that opens into Browser as VisBrowser. Changing JxBrowser menu pick to Visualizer to follow. | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.opensim.threejs;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.eclipse.jetty.JettyMa... | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.opensim.threejs;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.eclipse.jetty.JettyMa... |
Fix ID handling of rst widget | // Copyright (c) 2012 gocept gmbh & co. kg
// See also LICENSE.txt
(function($) {
zeit.cms.RestructuredTextWidget = gocept.Class.extend({
construct: function(widget_id) {
var self = this;
widget_id = widget_id.replace(/\./g, '\\.');
self.textarea = $('#' + widget_id);
self.previe... | // Copyright (c) 2012 gocept gmbh & co. kg
// See also LICENSE.txt
(function($) {
zeit.cms.RestructuredTextWidget = gocept.Class.extend({
construct: function(widget_id) {
var self = this;
widget_id = widget_id.replace('.', '\\.');
self.textarea = $('#' + widget_id);
self.preview ... |
Add source title to messages | 'use strict';
const config = require('./config');
const gooGl = require('goo.gl');
const moment = require('moment-timezone');
const removeUrlGarbage = require('link-cleaner');
if (config.shortenLinks) {
gooGl.setKey(config.gooGlKey);
}
async function formatDocuments(data) {
data.sort((a, b) => {
const... | 'use strict';
const config = require('./config');
const gooGl = require('goo.gl');
const moment = require('moment-timezone');
const removeUrlGarbage = require('link-cleaner');
if (config.shortenLinks) {
gooGl.setKey(config.gooGlKey);
}
async function formatDocuments(data) {
data.sort((a, b) => {
const... |
Update variables names in exam tests | # -*- coding: utf-8 -*-
from django.test import TestCase
from should_dsl import should
from exam.dynamic_import import create_specific_exam
from core.tests import FormatTest
from sys import stderr
class TestDynamicImport(FormatTest, TestCase):
def setUp(self):
self.my_type = '[Exam - Dynamic Import]'
... | # -*- coding: utf-8 -*-
from django.test import TestCase
from should_dsl import should
from exam.dynamic_import import create_specific_exam
from core.tests import FormatTest
from sys import stderr
class TestDynamicImport(FormatTest, TestCase):
def setUp(self):
self.my_type = '[Exam - Dynamic Import]'
... |
Trim down defaults out of TimeoutDetector. | 'use strict'; /*jslint node: true, es5: true, indent: 2 */
var util = require('util');
var stream = require('stream');
var TimeoutDetector = module.exports = function(opts) {
if (!opts || !opts.timeout) throw new Error('TimeoutDetector({timeout: ...}) is a required parameter.');
stream.Transform.call(this, opts);
... | 'use strict'; /*jslint node: true, es5: true, indent: 2 */
var util = require('util');
var stream = require('stream');
var TimeoutDetector = module.exports = function(opts) {
if (opts === undefined) opts = {};
// opts = {[timeout: 60 (seconds)]}
stream.Transform.call(this, opts);
if (opts.timeout !== undefine... |
Fix once again nobody being allowed to connect | from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.chan... | from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.chan... |
Fix another broken sc2reader.plugins reference. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals, division
import sc2reader
from sc2reader.factories.plugins.replay import toJSON
def main():
import argparse
parser = argparse.ArgumentParser(description="Prints replay data to a json string... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals, division
import sc2reader
from sc2reader.plugins.replay import toJSON
def main():
import argparse
parser = argparse.ArgumentParser(description="Prints replay data to a json string.")
pa... |
Update dependencies to make it installable. | """
setup.py
"""
from setuptools import setup, find_packages
setup(
name='SATOSA',
version='2.1.1',
description='Protocol proxy (SAML/OIDC).',
author='DIRG',
author_email='dirg@its.umu.se',
license='Apache 2.0',
url='https://github.com/its-dirg/SATOSA',
packages=find_packages('src/'),
... | """
setup.py
"""
from setuptools import setup, find_packages
setup(
name='SATOSA',
version='2.1.1',
description='Protocol proxy (SAML/OIDC).',
author='DIRG',
author_email='dirg@its.umu.se',
license='Apache 2.0',
url='https://github.com/its-dirg/SATOSA',
packages=find_packages('src/'),
... |
Remove question mark as initial state on tabs | (function(){
'use strict';
angular.module('cla.controllers')
.controller('CaseEditDetailCtrl',
['$scope', 'AlternativeHelpService',
function($scope, AlternativeHelpService){
// when viewing coming back to the details view
// clear out the Alternative Help selections.
... | (function(){
'use strict';
angular.module('cla.controllers')
.controller('CaseEditDetailCtrl',
['$scope', 'AlternativeHelpService',
function($scope, AlternativeHelpService){
// when viewing coming back to the details view
// clear out the Alternative Help selections.
... |
Use default value instead of operator 'or' | 'use strict'
const path = require('path')
const {spawnSync} = require('child_process')
const {
env: {
STANDARDJS_EXECUTABLE = 'standard',
STANDARDJS_ARGV,
SKIP_CODE_STYLE_CHECKING
}
} = require('process')
const wdir = path.resolve(__dirname, '..')
test('JavaScript Code Style: StandardJS', () => {
if... | 'use strict'
const path = require('path')
const {spawnSync} = require('child_process')
const {
env: {
STANDARDJS_EXECUTABLE,
STANDARDJS_ARGV,
SKIP_CODE_STYLE_CHECKING
}
} = require('process')
const wdir = path.resolve(__dirname, '..')
test('JavaScript Code Style: StandardJS', () => {
if (SKIP_CODE_S... |
Set default log level to warn | var winston = require('winston'),
path = require('path');
var logLevel = 'warn';
var sharedLogger = function(filename) {
return new winston.Logger({
transports: [
new winston.transports.Console({
prettyPrint: true,
timestamp: true,
level: logLevel,
label: path.basena... | var winston = require('winston'),
path = require('path');
var logLevel = 'debug';
var sharedLogger = function(filename) {
return new winston.Logger({
transports: [
new winston.transports.Console({
prettyPrint: true,
timestamp: true,
level: logLevel,
label: path.basen... |
Tweak to hard code values to make test pass | package hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class ArchivedCardController {
@RequestMapping("/archivedCards")
public List<ArchivedCard> ar... | package hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class ArchivedCardController {
@RequestMapping("/archivedCards")
public List<ArchivedCard> ar... |
Fix empty first line in migration | <?php
/**
* Copyright (C) 2019 Xibo Signage Ltd
*
* Xibo - Digital Signage - http://www.xibo.org.uk
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, eithe... |
<?php
/**
* Copyright (C) 2019 Xibo Signage Ltd
*
* Xibo - Digital Signage - http://www.xibo.org.uk
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, eith... |
Resolve circular reference during import | import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
import algebra
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebr... | import algebra
import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebra... |
Fix hoem directory for windows | #!/usr/bin/env node
'use strict';
import path from 'path';
import pkg from '../package.json';
import hogan from 'hogan.js';
import app from 'commander';
import DataStore from './DataStore';
var home = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
var src = process.env.TSTORE_HOME || path.join(... | #!/usr/bin/env node
'use strict';
import path from 'path';
import pkg from '../package.json';
import hogan from 'hogan.js';
import app from 'commander';
import DataStore from './DataStore';
var store = new DataStore(process.env.TSTORE_HOME || path.join(process.env.HOME, '.config/tstore'));
app.version(pkg.version);
... |
Fix no notification service client issue. | import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
def no_action(msg):
pass
try:
from iconizer.gui_client.notification_service_client import NotificationServiceClient
notification_method = NotificationSe... | import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
def no_action(msg):
pass
try:
from iconizer.gui_client.notification_service_client import NotificationServiceClient
notification_method = NotificationSe... |
Handle empty response inside Github monitor. | 'use strict';
const assert = require('assert');
const github = require('github');
/**
* @param {secret} ORGANIZATION - Github ORGANIZATION name
* @param {secret} GITHUB_TOKEN - Github API Token with "org:read" permission
* @return JSON ['john', 'mark']
*/
module.exports = (ctx, cb) => {
assert(ctx.secrets, 'Sec... | 'use strict';
const GitHubApi = require('github');
const github = new GitHubApi({
version: '3.0.0',
debug: false,
protocol: 'https',
host: 'api.github.com',
timeout: 5000,
headers: {
'user-agent': 'webtask-mfa-monitor (https://github.com/radekk/webtask-mfa-monitor/)'
}
});
/**
* @param {secret} ORG... |
Test against jQuery 3.2.0 and 3.2.1 | QUnit.config.urlConfig.push({
id: "jquery",
label: "jQuery version",
value: ["3.2.1", "3.2.0", "3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"],
tooltip: "What jQuery Core version to test against"
});
/* Hijacks normal form submit; lets it submit to an iframe to prevent
* navigating away from ... | QUnit.config.urlConfig.push({
id: "jquery",
label: "jQuery version",
value: ["3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"],
tooltip: "What jQuery Core version to test against"
});
/* Hijacks normal form submit; lets it submit to an iframe to prevent
* navigating away from the test suite
*/... |
Send all postures as array | function ddg_spice_yoga_asanas(apiResult) {
if (!apiResult || !apiResult.response.numFound) {
return Spice.failed('yoga_asanas');
}
Spice.add({
id: 'yoga_asanas',
name: 'Yoga Asanas',
data: apiResult.response.docs,
normalize: function(a){
var meta = eval("(" + a.meta + ")");
delete a.m... | function ddg_spice_yoga_asanas(apiResult) {
if (!apiResult || !apiResult.response.numFound) {
return Spice.failed('yoga_asanas');
}
for(i = 0; i < apiResult.response.numFound; i++){
var a = apiResult.response.docs[i];
var meta = eval("(" + a.meta + ")");
delete a.meta;
Spice.add({
id: 'yo... |
Fix the response adding the closing delimiter | package split
import (
"bytes"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
)
// WriteResponses serialize the responses passed as argument into the ResponseWriter
func WriteResponses(w http.ResponseWriter, responses []*http.Response) error {
var buf bytes.Buffer
multipartWriter := multipart.NewWriter(&bu... | package split
import (
"bytes"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
)
// WriteResponses serialize the responses passed as argument into the ResponseWriter
func WriteResponses(w http.ResponseWriter, responses []*http.Response) error {
var buf bytes.Buffer
multipartWriter := multipart.NewWriter(&bu... |
Make the form action redirect to the products.index page with the correct params | // Dependencies
import Ember from 'ember';
import layout from '../templates/components/yebo-search';
/**
The search form
@class YeboDetails
@namespace Component
@extends Ember.Component
*/
export default Ember.Component.extend({
layout: layout,
// The text that is going to be searched
searchText: '',
... | // Dependencies
import Ember from 'ember';
import layout from '../templates/components/yebo-search';
/**
The search form
@class YeboDetails
@namespace Component
@extends Ember.Component
*/
export default Ember.Component.extend({
layout: layout,
// The text that is going to be searched
searchText: '',
... |
Add esc key bind in editor | import React from 'react'
import SimpleMDE from 'react-simplemde-editor'
const PoemEditor = (props) => {
const extraKeys = {
// 'Ctrl-Enter': () => { props.handleEditorSubmit() },
'Cmd-Enter': () => { props.handleEditorSubmit() },
'Esc': () => {
document.activeElement.blur()
}
}
return (
... | import React from 'react'
import SimpleMDE from 'react-simplemde-editor'
const PoemEditor = (props) => {
const extraKeys = {
// 'Ctrl-Enter': () => { props.handleEditorSubmit() },
'Cmd-Enter': () => { props.handleEditorSubmit() },
}
return (
<div className="poem-form">
<SimpleMDE
onCha... |
Update the permission helper functions. | def user_can_view_scans(user, moon):
return (
user_can_delete_scans(user, moon) or
user.has_perm('eve_sde.sys_can_view_scans', moon.planet.system) or
user.has_perm('eve_sde.con_can_view_scans', moon.planet.system.constellation) or
user.has_perm('eve_sde.reg_can_view_scans', moon.plan... | def user_can_view_scans(user, moon):
return (
user_can_delete_scans(user, moon) or
user.has_perm('eve_sde.can_view_scans', moon.planet.system) or
user.has_perm('eve_sde.can_view_scans', moon.planet.system.constellation) or
user.has_perm('eve_sde.can_view_scans', moon.planet.system.co... |
docs: Add comment denoting change and why it's hard to test and when to revisit. | import props from './props';
function getValue (elem) {
const type = elem.type;
if (type === 'checkbox' || type === 'radio') {
return elem.checked ? elem.value || true : false;
}
return elem.value;
}
export default function (elem, target) {
return (e) => {
// We fallback to checking the composed pat... | import props from './props';
function getValue (elem) {
const type = elem.type;
if (type === 'checkbox' || type === 'radio') {
return elem.checked ? elem.value || true : false;
}
return elem.value;
}
export default function (elem, target) {
return (e) => {
const localTarget = target || e.target || e... |
Restructure abstract calendar to use iterators. | <?php
namespace Plummer\Calendar;
abstract class CalendarAbstract implements CalendarInterface
{
protected $name;
protected $events;
protected $recurrenceTypes;
public function __construct($name)
{
$this->name = $name;
}
public function addEvents($events)
{
if($events instanceof \Iterator) {
$this-... | <?php
namespace Plummer\Calendar;
abstract class CalendarAbstract implements CalendarInterface
{
protected $events;
protected $recurrenceTypes;
protected function __construct(\Iterator $events, $recurrenceTypes)
{
$this->events = $events;
$this->addRecurrenceTypes($recurrenceTypes);
}
public static funct... |
Switch over to loading .js file
Gerrit no longer supports html plugins so we have
to use the .js version.
Bug: Issue 14335
Change-Id: I284647480d0cac76f3afde0aa566b47121ff9511 | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... |
Handle unknown extensions with the html frontend | <?php
namespace BNETDocs\Controllers;
use \BNETDocs\Libraries\Controller;
use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException;
use \BNETDocs\Libraries\Router;
use \BNETDocs\Models\Maintenance as MaintenanceModel;
use \BNETDocs\Views\MaintenanceHtml as MaintenanceHtmlView;
use \BNETDocs\Views\MaintenanceJSON a... | <?php
namespace BNETDocs\Controllers;
use \BNETDocs\Libraries\Controller;
use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException;
use \BNETDocs\Libraries\Router;
use \BNETDocs\Models\Maintenance as MaintenanceModel;
use \BNETDocs\Views\MaintenanceHtml as MaintenanceHtmlView;
use \BNETDocs\Views\MaintenanceJSON a... |
Fix annotation retention for reflect usage | package butterknife;
import android.support.annotation.ArrayRes;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Bind a field to the specified array resource ID. The typ... | package butterknife;
import android.support.annotation.ArrayRes;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.CLASS;
/**
* Bind a field to the specified array resource ID. The type ... |
Remove the lert message of passing id info for Block creation
git-svn-id: 6eed24e287f84bf0ab23ca377a3e397011128a6f@3438 fdecad78-55fc-0310-b1b2-d7d25cf747c9 | //TODO:Javacsript can check if checked Ids hasv the same scale ID
function extractSelectedItems(submitButton) {
sourceForm = document.getElementById("modifyFormRows");
destinationForm = submitButton.form;
var count = 0; //enforce at least 2 check box are checked
if (sourceForm && destinationForm) {
var i... | //TODO:Javacsript can check if checked Ids hasv the same scale ID
function extractSelectedItems(submitButton) {
sourceForm = document.getElementById("modifyFormRows");
destinationForm = submitButton.form;
var count = 0; //enforce at least 2 check box are checked
if (sourceForm && destinationForm) {
var i... |
Remove single shard optimization, don't use sharding if you have one shard. | <?php
namespace League\Flysystem\UrlGeneration;
use InvalidArgumentException;
use League\Flysystem\Config;
use League\Flysystem\PathPrefixer;
use function array_map;
use function count;
use function crc32;
final class ShardedPrefixPublicUrlGenerator implements PublicUrlGenerator
{
/** @var PathPrefixer[] */
... | <?php
namespace League\Flysystem\UrlGeneration;
use InvalidArgumentException;
use League\Flysystem\Config;
use League\Flysystem\PathPrefixer;
use function array_map;
use function count;
use function crc32;
final class ShardedPrefixPublicUrlGenerator implements PublicUrlGenerator
{
/** @var PathPrefixer[] */
... |
Update source directory in coveralls configuration. | <?php
use mageekguy\atoum\reports;
$runner
->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
->disallowUndefinedMethodInInterface()
;
$travis = getenv('TRAVIS');
if ($travis)
{
$script->addDefaultReport();
$coverallsToken = getenv('COVERALLS_REPO_TOKEN');
if ($coverallsToken)
{
$coverallsReport = ... | <?php
use mageekguy\atoum\reports;
$runner
->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
->disallowUndefinedMethodInInterface()
;
$travis = getenv('TRAVIS');
if ($travis)
{
$script->addDefaultReport();
$coverallsToken = getenv('COVERALLS_REPO_TOKEN');
if ($coverallsToken)
{
$coverallsReport = ... |
Update to always run, and tune some of the selectors | var doc = window.document;
function setup(container) {
var inputs = container.getElementsByClassName('hours');
var arr = Array.prototype.slice.call(inputs);
for (var i=0; i<arr.length; i++) {
var element = arr[i];
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" smart-processed ") >... | var doc = window.document;
function setup(container) {
var inputs = container.getElementsByTagName('input');
var arr = Array.prototype.slice.call(inputs);
for (var i=0; i<arr.length; i++) {
var element = arr[i];
if (element.id.indexOf('weeks[') !== -1) {
element.addEventListener("blur", function (... |
Make more use-friendly constants for sort ascending, descending. | <?php
namespace UWDOEM\Framework\FilterStatement;
use Propel\Runtime\ActiveQuery\ModelCriteria;
interface FilterStatementInterface {
const COND_SORT_ASC = "ascending";
const COND_SORT_DESC = "descending";
const COND_LESS_THAN = 3;
const COND_GREATER_THAN = 4;
const COND_EQUAL_TO = 5;
const ... | <?php
namespace UWDOEM\Framework\FilterStatement;
use Propel\Runtime\ActiveQuery\ModelCriteria;
interface FilterStatementInterface {
const COND_SORT_ASC = 1;
const COND_SORT_DESC = 2;
const COND_LESS_THAN = 3;
const COND_GREATER_THAN = 4;
const COND_EQUAL_TO = 5;
const COND_NOT_EQUAL_TO = 6... |
Update description and long description
[ci skip] | import os
import sys
from setuptools import setup
__author__ = 'Ryan McGrath <ryan@venodesigns.net>'
__version__ = '2.10.0'
packages = [
'twython',
'twython.streaming'
]
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
setup(
# Basic package information.
na... | import os
import sys
from setuptools import setup
__author__ = 'Ryan McGrath <ryan@venodesigns.net>'
__version__ = '2.10.0'
packages = [
'twython',
'twython.streaming'
]
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
setup(
# Basic package information.
na... |
Remove autopopulation from User model | var modelProperties, mongoose, passportLocalMongoose, Rat, Schema, UserSchema;
mongoose = require( 'mongoose' );
passportLocalMongoose = require( 'passport-local-mongoose' );
Rat = require( './rat' );
Schema = mongoose.Schema;
modelProperties = {
email: String,
password: String,
CMDRs: {
default: [],
ty... | var modelProperties, mongoose, passportLocalMongoose, Rat, Schema, UserSchema;
mongoose = require( 'mongoose' );
passportLocalMongoose = require( 'passport-local-mongoose' );
Rat = require( './rat' );
Schema = mongoose.Schema;
modelProperties = {
email: String,
password: String,
CMDRs: {
default: [],
ty... |
Make browserHistory routing actually work. | var path = require('path');
var webpack = require('webpack');
var babelSettings = JSON.stringify({
presets: ['es2015', 'react']
});
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents r... | var path = require('path');
var webpack = require('webpack');
var babelSettings = JSON.stringify({
presets: ['es2015', 'react']
});
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents r... |
Python: Fix typo in test case | from django.db import connection, models
from django.db.models.expressions import RawSQL
def test_plain():
cursor = connection.cursor()
cursor.execute("some sql") # $getSql="some sql"
def test_context():
with connection.cursor() as cursor:
cursor.execute("some sql") # $getSql="some sql"
... | from django.db import connection, models
from django.db.models.expressions import RawSQL
def test_plain():
cursor = connection.cursor()
cursor.execute("some sql") # $getSql="some sql"
def test_context():
with connection.cursor() as cursor:
cursor.execute("some sql") # $getSql="some sql"
... |
Throw AuthorizationException if user doesn't have scope
Should this not throw AuthorizationException when the user doesn't have the required scopes as the user is authenticated but doesn't have the scope to access the route? | <?php
namespace Laravel\Passport\Http\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Access\AuthorizationException;
class CheckScopes
{
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param arra... | <?php
namespace Laravel\Passport\Http\Middleware;
use Illuminate\Auth\AuthenticationException;
class CheckScopes
{
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param array $scopes
* @return \Illuminate\Http\Response... |
Make label and field selector query strings versionable.
Kubernetes-commit: 266234f3b9ccce6519c2bb500a2b102bf4b7fa16 | /*
Copyright 2014 Google Inc. All rights reserved.
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 ... | /*
Copyright 2014 Google Inc. All rights reserved.
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 ... |
Add throws to the javadoc | package co.paralleluniverse.firebase;
//~--- non-JDK imports --------------------------------------------------------
import co.paralleluniverse.fibers.SuspendExecution;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.Query;
/**
* This class exposes Firebase... | package co.paralleluniverse.firebase;
//~--- non-JDK imports --------------------------------------------------------
import co.paralleluniverse.fibers.SuspendExecution;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.Query;
/**
* This class exposes Firebase... |
Add missing fields in view.state.values | package com.slack.api.model.view;
import com.slack.api.model.block.composition.PlainTextObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class... | package com.slack.api.model.view;
import com.slack.api.model.block.composition.PlainTextObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class... |
Fix glossary file location to relative | #! /usr/bin/python2.7
# -*- coding: utf-8 -*-
from flask import Flask, render_template
import os
import re
from settings import BABEL_SETTINGS, SERVER_SETTINGS
from utils.i18n import PopongBabel
from utils.glossary import load as load_glossary
app = Flask(__name__)
app.debug = SERVER_SETTINGS['debug']
p = os.path.j... | #! /usr/bin/python2.7
# -*- coding: utf-8 -*-
import re
from flask import Flask, render_template
from settings import BABEL_SETTINGS, SERVER_SETTINGS
from utils.i18n import PopongBabel
from utils.glossary import load as load_glossary
app = Flask(__name__)
app.debug = SERVER_SETTINGS['debug']
terms = load_glossary('... |
Add condition on scan of pci.ids to exclude sub-classes from being caught up as a device. | package pci
import (
"bufio"
"bytes"
)
func isHex(b byte) bool {
return ('a' <= b && b <= 'f') || ('A' <= b && b <= 'F') || ('0' <= b && b <= '9')
}
// scan searches for Vendor and Device lines from the input *bufio.Scanner based
// on pci.ids format. Found Vendors and Devices are added to the input ids map.
func... | package pci
import (
"bufio"
"bytes"
)
func isHex(b byte) bool {
return ('a' <= b && b <= 'f') || ('A' <= b && b <= 'F') || ('0' <= b && b <= '9')
}
// scan searches for Vendor and Device lines from the input *bufio.Scanner based
// on pci.ids format. Found Vendors and Devices are added to the input map.
// This ... |
Validate input using class, using return on if else condition | <input type="text" class="form-control input" placeholder="Nama.." id="nama"><br>
<textarea rows="8" id="komentar" placeholder="Komentar anda.." class="form-control input"></textarea><br>
<button class="btn btn-info" onclick="postComment()">Submit</button>
<script type="text/javascript">
function postComment() {
... | <input type="text" class="form-control" placeholder="Nama.." id="nama"><br>
<textarea rows="8" id="komentar" placeholder="Komentar anda.." class="form-control"></textarea><br>
<button class="btn btn-info" onclick="postComment()">Submit</button>
<script type="text/javascript">
function postComment() {
// Firebase
... |
Make email and password have default values
* which must be overriden | package com.fns.xlator.client.impl;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = ... | package com.fns.xlator.client.impl;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = ... |
Add argument to print usernames | #!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to ... | #!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to ... |
Remove application flag, not an application | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',... | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',... |
Rearrange methods to follow route setup | // global_config.js
var Parse = require('parse/node').Parse,
PromiseRouter = require('./PromiseRouter');
var router = new PromiseRouter();
function getGlobalConfig(req) {
return req.config.database.rawCollection('_GlobalConfig')
.then(coll => coll.findOne({'_id': 1}))
.then(globalConfig => ({response: ... | // global_config.js
var Parse = require('parse/node').Parse,
PromiseRouter = require('./PromiseRouter');
var router = new PromiseRouter();
function updateGlobalConfig(req) {
if (!req.auth.isMaster) {
return Promise.resolve({
status: 401,
response: {error: 'unauthorized'},
});
}
return ... |
:bug: Fix a flow warning
Flow does not support the unicode flag with RegExpes yet | 'use babel'
/* @flow */
import type { Message, MessageLegacy } from '../types'
// Code Point 160 ===
const replacementRegex = new RegExp(String.fromCodePoint(160), 'g')
export function visitMessage(message: Message | MessageLegacy) {
const messageFile = message.version === 1 ? message.filePath : message.lo... | 'use babel'
/* @flow */
import type { Message, MessageLegacy } from '../types'
export function visitMessage(message: Message | MessageLegacy) {
const messageFile = message.version === 1 ? message.filePath : message.location.file
const messageRange = message.version === 1 ? message.range : message.location.positi... |
Use the .caller property to test tail-calls instead of trying to cause stackoverflow errors | /*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// Invalid direct eval call and tail calls:
// - direct eval fallback and 'wrong' eval function have both tail c... | /*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// Invalid direct eval call and tail calls:
// - direct eval fallback and 'wrong' eval function have both tail c... |
Return format to please the browser's graph. | import neo4j
class SubTopics(neo4j.Traversal):
"""Traverser that yields all subcategories of a category."""
types = [neo4j.Incoming.is_a]
returnable = neo4j.RETURN_ALL_BUT_START_NODE
order = neo4j.BREADTH_FIRST
stop = neo4j.STOP_AT_END_OF_GRAPH
class Topics(neo4j.Traversal):
types = [
... | import neo4j
class SubTopics(neo4j.Traversal):
"""Traverser that yields all subcategories of a category."""
types = [neo4j.Incoming.is_a]
returnable = neo4j.RETURN_ALL_BUT_START_NODE
order = neo4j.BREADTH_FIRST
stop = neo4j.STOP_AT_END_OF_GRAPH
class Topics(neo4j.Traversal):
types = [
... |
Update the required vectormath version to 0.1.0 | #!/usr/bin/env python
"""
properties: Fancy properties for Python.
"""
from distutils.core import setup
from setuptools import find_packages
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Ma... | #!/usr/bin/env python
"""
properties: Fancy properties for Python.
"""
from distutils.core import setup
from setuptools import find_packages
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Ma... |
Set default jakefile task to 'test' so it gets executed by travis-ci.org | /* globals desc:false, task: false, complete: fase, jake: false */
(function (desc, task, complete, jake) {
"use strict";
desc('The default task. Runs tests.');
task('default', ['test'], function () {
});
desc('Run tests');
task('test', [], function () {
jake.exec(["./node_modules/.bin... | /* globals desc:false, task: false, complete: fase, jake: false */
(function (desc, task, complete, jake) {
"use strict";
desc('The default task. Runs tests.');
task('default', ['tests'], function () {
});
desc('Run tests');
task('tests', [], function () {
jake.exec(["./node_modules/.b... |
Convert tags to a set on init and back to a list on writing. | """Provide the class IdxItem which represents an item in the index.
"""
import hashlib
def _md5file(fname):
"""Calculate the md5 hash for a file.
"""
m = hashlib.md5()
chunksize = 8192
with open(fname, 'rb') as f:
while True:
chunk = f.read(chunksize)
if not chunk:... | """Provide the class IdxItem which represents an item in the index.
"""
import hashlib
def _md5file(fname):
"""Calculate the md5 hash for a file.
"""
m = hashlib.md5()
chunksize = 8192
with open(fname, 'rb') as f:
while True:
chunk = f.read(chunksize)
if not chunk:... |
Change the way text message egress initializes | import BaseWorker from '../../base'
import twilio from 'twilio'
import path from 'path'
export class TextMessage extends BaseWorker {
constructor (rsmq) {
super('text_message', rsmq)
this.client = new twilio.RestClient(
process.env.TWILIO_SID,
process.env.TWILIO_TOKEN
)
}
body (message)... | import BaseWorker from '../../base'
import twilio from 'twilio'
import path from 'path'
const client = new twilio.RestClient(
process.env.TWILIO_SID,
process.env.TWILIO_TOKEN
)
export class TextMessage extends BaseWorker {
constructor (rsmq) {
super('text_message', rsmq)
}
body (message) {
return t... |
Update : uppercase every input commands | # -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
from clint.textui import puts, colored
from elevator.utils.patterns import destructurate
from .helpers import FAILURE_STATUS
def prompt(*args, **kwargs):
current_db = kwargs.pop('current_db', 'default')
... | # -*- coding: utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
from clint.textui import puts, colored
from elevator.utils.patterns import destructurate
from .helpers import FAILURE_STATUS
def prompt(*args, **kwargs):
current_db = kwargs.pop('current_db', 'default')
... |
Test: Increase timeout duration for "scroll" | const { Tracker } = Sentinel;
/* Constants */
const targetSize = 200;
const container = document.getElementById('container');
const bounds = document.getElementById('bounds');
function createTarget(styles = {}, parent = container) {
const element = document.createElement('div');
element.classList.add('target');
... | const { Tracker } = Sentinel;
/* Constants */
const targetSize = 200;
const container = document.getElementById('container');
const bounds = document.getElementById('bounds');
function createTarget(styles = {}, parent = container) {
const element = document.createElement('div');
element.classList.add('target');
... |
Improve download speed by using non-blocking. Also adding upper limit 365. | var cheerio = require('cheerio'),
request = require('request'),
fs = require('fs');
var savePath = process.argv[2];
if(typeof savePath === 'undefined') {
console.log("Error: Save path not defined.");
return;
}
var year = "2013";
var baseUri = 'http://www.facets.la/';
(function getImg(id) {
var uri = baseUri + ... | var cheerio = require('cheerio'),
request = require('request'),
fs = require('fs');
var savePath = process.argv[2];
if(typeof savePath === 'undefined') {
console.log("Error: Save path not defined.");
return;
}
var year = "2013";
var baseUri = 'http://www.facets.la/';
(function getImg(id) {
var uri = baseUri + ... |
Add notification about gemini config overriding | 'use strict';
var path = require('path'),
opener = require('opener'),
chalk = require('chalk'),
pkg = require('../package.json'),
server = require('./server'),
program = require('commander');
exports.run = function() {
program
.version(pkg.version)
.allowUnknownOption(true)
... | 'use strict';
var path = require('path'),
opener = require('opener'),
chalk = require('chalk'),
pkg = require('../package.json'),
server = require('./server'),
program = require('commander');
function getConfigPath(config) {
return path.resolve(config);
}
exports.run = function() {
program... |
Fix an issue where the unit test fails on PHP 5.3 | <?php
namespace Dakatsuka\MonologFluentHandler\Tests;
use Dakatsuka\MonologFluentHandler\FluentHandler;
use Monolog\Logger;
class FluentHandlerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var array
*/
protected $record;
protected function setUp()
{
$record = array();
$... | <?php
namespace Dakatsuka\MonologFluentHandler\Tests;
use Dakatsuka\MonologFluentHandler\FluentHandler;
use Monolog\Logger;
class FluentHandlerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var array
*/
protected $record;
protected function setUp()
{
$record = array();
$... |
Support IPv6 in random ip | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from flask import Flask, request, render_template, url_for, redirect
from pyhipku import encode
app = Flask(__name__)
@app.route('/<current_ip>')
def index(current_ip):
your_ip = request.remote_addr
lines = encode(current_ip).split('\n')
retu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
from flask import Flask, request, render_template, url_for, redirect
from pyhipku import encode
app = Flask(__name__)
@app.route('/<current_ip>')
def index(current_ip):
your_ip = request.remote_addr
lines = encode(current_ip).split('... |
Fix Karma trying to compile files that should not be compiled
Perhaps we need another strategy here. Basically only 'frontend' files
need to be compiled. | module.exports = function(karma) {
const rollupConfig = require("./rollup.config")[0];
karma.set({
frameworks: ["mocha", "chai", "chai-dom", "sinon-chai"],
files: [
{ pattern: "src/**/!(cli|webpack).js", included: false },
"spec/**/*.spec.js"
],
preprocessors: {
"src/**/!(cli|ta... | module.exports = function(karma) {
const rollupConfig = require("./rollup.config")[0];
karma.set({
frameworks: ["mocha", "chai", "chai-dom", "sinon-chai"],
files: [
{ pattern: "src/**/!(cli|webpack).js", included: false },
"spec/**/*.spec.js"
],
preprocessors: {
"src/**/!(cli).j... |
Make intro flashes more interesting | var Drawing = function (pulse, config) {
pulse.framesLeft = 300;
pulse.shade = 0;
this.pulse = pulse;
};
Drawing.prototype.draw = function (p) {
var self = this;
var pulse = self.pulse
if (pulse.framesLeft > 255) {
if (pulse.framesLeft % 10 === 0) {
pulse.r = Math.random() * 255;
pulse.g ... | var Drawing = function (pulse, config) {
pulse.framesLeft = 255;
this.pulse = pulse;
};
Drawing.prototype.draw = function (p) {
var self = this;
var pulse = self.pulse
var shade = 255;
if (pulse.framesLeft > 230) {
pulse.r = Math.random() * 255;
pulse.g = Math.random() * 255;
pulse.b = Math.... |
Update method signature to use interface instead of class
Closes #303 | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\DoctrineORMAdminBundle\Guesser;
use Sonata\AdminBundle... | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\DoctrineORMAdminBundle\Guesser;
use Sonata\AdminBundle... |
Rename method setSliderManager to setSlider | /**
Copyright 2017 John Kester (Jack Kester)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writ... | /**
Copyright 2017 John Kester (Jack Kester)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writ... |
Remove custom 1D lerp() function.
THREE.Math.lerp() was added in three.js r82. | import * as THREE from 'three';
export function randomPointOnSphere( vector = new THREE.Vector3() ) {
const theta = 2 * Math.PI * Math.random();
const u = 2 * Math.random() - 1;
const v = Math.sqrt( 1 - u * u );
return vector.set(
v * Math.cos( theta ),
v * Math.sin( theta ),
u
);
}
export func... | import * as THREE from 'three';
export function randomPointOnSphere( vector = new THREE.Vector3() ) {
const theta = 2 * Math.PI * Math.random();
const u = 2 * Math.random() - 1;
const v = Math.sqrt( 1 - u * u );
return vector.set(
v * Math.cos( theta ),
v * Math.sin( theta ),
u
);
}
export func... |
Set password in user ini | from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def __ini... | from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def set_p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.