text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix timestamps that got messed up by a change in the logging | package heufybot.core;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import heufybot.utils.FileUtils;
public class Logger
{
public static void log(String line, String target)
{
//Timestamp line
DateFormat dateFormat = new SimpleDateFormat("[HH:mm]");
Date date = new ... | package heufybot.core;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import heufybot.utils.FileUtils;
public class Logger
{
public static void log(String line, String target)
{
//Timestamp line
DateFormat dateFormat = new SimpleDateFormat("[HH:mm]");
Date date = new ... |
Rename a variable for clarity
currentDomains → blockedDomains | function checkForPeevskiDomain(url) {
var blockedDomains = [
'monitor.bg',
'telegraph.bg',
'politika.bg',
'europost.eu',
'europost.bg',
'borbabg.com',
'tv7.bg',
'news7.bg',
'super7.bg',
'3bay.bg',
'econ.bg',
'inews.bg',
'jenite.bg',
'div.bg',
'sporta.bg',
'fitwell.bg',
'sportuvaj.bg',... | function checkForPeevskiDomain(url) {
var currentDomains = [
'monitor.bg',
'telegraph.bg',
'politika.bg',
'europost.eu',
'europost.bg',
'borbabg.com',
'tv7.bg',
'news7.bg',
'super7.bg',
'3bay.bg',
'econ.bg',
'inews.bg',
'jenite.bg',
'div.bg',
'sporta.bg',
'fitwell.bg',
'sportuvaj.bg',... |
Sort entities by depth before display | define([], function () {
'use strict';
var GameRenderer = function (canvas, entities) {
this.canvas = canvas;
this.entities = entities;
this.gc = this.canvas.getContext('2d');
};
GameRenderer.prototype.paint = function paint() {
this.gc.fillStyle = '#002b36';
this.gc.fillRect(0, 0, this.ca... | define([], function () {
'use strict';
var GameRenderer = function (canvas, entities) {
this.canvas = canvas;
this.entities = entities;
this.gc = this.canvas.getContext('2d');
};
GameRenderer.prototype.paint = function paint() {
var len = this.entities.length;
var i;
var entity;
t... |
Replace the filter because of php compatibility | <?php
if ( ! function_exists( 'whip_wp_check_versions' ) ) {
/**
* Facade to quickly check if version requirements are met.
*
* @param array $requirements The requirements to check.
*/
function whip_wp_check_versions( $requirements ) {
// Only show for admin users.
if ( ! is_array( $requirements ) ) {
... | <?php
if ( ! function_exists( 'whip_wp_check_versions' ) ) {
/**
* Facade to quickly check if version requirements are met.
*
* @param array $requirements The requirements to check.
*/
function whip_wp_check_versions( $requirements ) {
// Only show for admin users.
if ( ! is_array( $requirements ) ) {
... |
Add validate task to the default build process. | module.exports = function(grunt) {
// Initialize global configuration variables.
var config = grunt.file.readJSON('Gruntconfig.json');
grunt.initConfig({
config: config
});
// Load all included tasks.
grunt.loadTasks(__dirname + '/tasks');
// Define the default task to fully build and configure the... | module.exports = function(grunt) {
// Initialize global configuration variables.
var config = grunt.file.readJSON('Gruntconfig.json');
grunt.initConfig({
config: config
});
// Load all included tasks.
grunt.loadTasks(__dirname + '/tasks');
// Define the default task to fully build and configure the... |
Add ability to override image | package main
import (
"fmt"
"net/http"
"regexp"
"strings"
)
type Request struct {
Filename string
Content string
Command string
Image string
Format string
}
var FilenameRegexp = regexp.MustCompile(`\A([a-z\d\-\_]+)\.[a-z]{1,6}\z`)
func normalizeString(val string) string {
return strings.ToLower(str... | package main
import (
"fmt"
"net/http"
"regexp"
"strings"
)
type Request struct {
Filename string
Content string
Command string
Image string
Format string
}
var FilenameRegexp = regexp.MustCompile(`\A([a-z\d\-\_]+)\.[a-z]{1,6}\z`)
func normalizeString(val string) string {
return strings.ToLower(str... |
Convert dashboard alias using dots with dashes
Using dots in an identifier is common in config files.
By converting it as `-`, it enables using the dashboard
alias as jquery selector. | <?php
App::uses('PhpReader', 'Configure');
App::uses('ConfigReaderInterface', 'Configure');
/**
* DashboardsConfigReader
*
* @package Croogo.Dashboards.Lib.Configure
* @since 2.2
* @author Rachman Chavik <rchavik@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* ... | <?php
App::uses('PhpReader', 'Configure');
App::uses('ConfigReaderInterface', 'Configure');
/**
* DashboardsConfigReader
*
* @package Croogo.Dashboards.Lib.Configure
* @since 2.2
* @author Rachman Chavik <rchavik@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* ... |
Fix missing fontawesome icon (it's now a pro feature) & add train for Train station messages | import React, {Component} from 'react';
/*
* Displays informational message
*/
class MessageRow extends Component {
render() {
let msg = this.props.msg, icon = 'fas-3x fa-exclamation-circle';
if (msg.category === 'System') {
icon = 'fab-3x fa-linux';
} else if (msg.category ==... | import React, {Component} from 'react';
/*
* Displays informational message
*/
class MessageRow extends Component {
render() {
let msg = this.props.msg, icon = 'fa-warning';
if (msg.category === 'System') {
icon = 'fa-linux';
} else if (msg.category === "Station") {
... |
Update dsub version to 0.4.1.dev0
PiperOrigin-RevId: 328627320 | # Copyright 2017 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 a... | # Copyright 2017 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 a... |
Change Webservice in order to limit the entrys | <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Organisms with given ids
*/
class Organisms extends \WebService {
/**
* @param $querydata[ids] array of organism ids
* @returns array of organisms
*/
public function execute($querydata) {
global $db;
... | <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Organisms with given ids
*/
class Organisms extends \WebService {
/**
* @param $querydata[ids] array of organism ids
* @returns array of organisms
*/
public function execute($querydata) {
global $db;
... |
Set logout button to reload state if current state is 'home' | 'use strict';
header.$inject = ['$rootScope', '$state', 'AuthService'];
function header($rootScope, $state, AuthService) {
return {
name: 'header',
template: require('./templates/header.html'),
scope: true,
link: function link(scope) {
scope.toggled = false;
... | 'use strict';
header.$inject = ['$rootScope', '$state', 'AuthService'];
function header($rootScope, $state, AuthService) {
return {
name: 'header',
template: require('./templates/header.html'),
scope: true,
link: function link(scope) {
scope.toggled = false;
... |
Fix race condition in server-test | package emailserver
import (
"bytes"
"fmt"
"log"
"net"
"net/mail"
"testing"
"time"
"github.com/TNG/gpg-validation-server/email-client"
)
var receive_chan = make(chan string)
func init() {
server := Create("127.0.0.1:2525", mailHandler)
go server.Run()
time.Sleep(1 * time.Millisecond)
}
func mailHandler(... | package emailserver
import (
"bytes"
"fmt"
"log"
"net"
"net/mail"
"testing"
"time"
"github.com/TNG/gpg-validation-server/email-client"
)
var received string
func init() {
server := Create("127.0.0.1:2525", mailHandler)
go server.Run()
time.Sleep(1 * time.Millisecond)
}
func mailHandler(origin net.Addr, ... |
Upgrade dependency prompt-toolkit to ==1.0 | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_... | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_... |
Add random ball start angle | import Item, { MovingDirection, ItemType } from './Item'
import Ball from './Ball'
import ItemLoader from '../Loader/ItemLoader'
import Helper from '../Utility/Utility'
export default class Platform extends Item {
constructor(width, height, color) {
super(
[500 - (width / 2), 500 - height - 10],
[wid... | import Item, { MovingDirection, ItemType } from './Item'
import Ball from './Ball'
import ItemLoader from '../Loader/ItemLoader'
export default class Platform extends Item {
constructor(width, height, color) {
super(
[500 - (width / 2), 500 - height - 10],
[width, height],
color,
ItemType... |
Update the view for new notice handling | <div id="notice">
<?php foreach($notices as $type => $set): ?>
<?php if ( ! empty($set)): ?>
<?php foreach ($set as $notice): ?>
<div class="<?php echo $type; ?>">
<h6><?php echo UTF8::ucfirst($notice['type']); ?></h6>
<?php if ($notice['message'] !== NULL): ?>
<p><?php echo HTML::chars($notice['message']); ... |
<div id="notice">
<?php foreach($notifications as $type => $notification): ?>
<?php if ( ! empty($notification)): ?>
<?php foreach ($notification as $notice): ?>
<div class="<?php echo $type ?>">
<h6><?php echo __(UTF8::ucfirst($type)) ?></h6>
<?php if ($notice['message'] !== NULL): ?>
<p><?php echo $notice... |
Fix copy&paste error in test description | const chai = require('chai')
const expect = chai.expect
const calculateScore = require('../../lib/calculateScore')
describe('Score', () => {
it('should be 100 points for a * challenge', () => {
expect(calculateScore(1)).to.equal(100)
})
it('should be 250 points for a ** challenge', () => {
expect(calcul... | const chai = require('chai')
const expect = chai.expect
const calculateScore = require('../../lib/calculateScore')
describe('Score', () => {
it('should be 100 points for a * challenge', () => {
expect(calculateScore(1)).to.equal(100)
})
it('should be 250 points for a ** challenge', () => {
expect(calcul... |
Fix regex utils for long messages | package de.wak_sh.client;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
public static String match(String pattern, String subject) {
Matcher matcher = Pattern.compile(pattern, Pattern.DOTALL).matcher(
subject);
matcher.... | package de.wak_sh.client;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
public static String match(String pattern, String subject) {
Matcher matcher = Pattern.compile(pattern).matcher(subject);
matcher.find();
return matc... |
Add language and title as category page variables
This data will be available in the layouts.
Built from 9faf1c52d3216302ed78f39f27a9e4e361b9a9dc. | var pagination = require('hexo-pagination');
var _ = require('lodash');
hexo.extend.generator.register('category', function(locals){
var config = this.config;
var categories = locals.data.categories;
if (config.category_generator) {
var perPage = config.category_generator.per_page;
} else {
var perPage... | var pagination = require('hexo-pagination');
var _ = require('lodash');
hexo.extend.generator.register('category', function(locals){
var config = this.config;
var categories = locals.data.categories;
if (config.category_generator) {
var perPage = config.category_generator.per_page;
} else {
var perPage... |
Add more API calls to tests | <?php
require_once __DIR__ . "/wavepipe.php";
// Attempt a login request using test credentials
$login = json_decode(file_get_contents("http://localhost:8080/api/v0/login?u=test&p=test"), true);
if (empty($login)) {
printf("Failed to decode login JSON");
exit(1);
}
// Store necessary login information
$publicKey =... | <?php
require_once __DIR__ . "/wavepipe.php";
// Attempt a login request using test credentials
$login = json_decode(file_get_contents("http://localhost:8080/api/v0/login?u=test&p=test"), true);
if (empty($login)) {
printf("Failed to decode login JSON");
exit(1);
}
// Store necessary login information
$publicKey =... |
Update Dialog story to provide required prop. | /**
* Modal Dialog Component Stories.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENS... | /**
* Modal Dialog Component Stories.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENS... |
Debug pour recherche d'un bug | 'use strict';
const core = require('./core.js');
const fd = require('./field.js');
const serv = require('./../services/services.js');
/*
* Fonction qui traite les réponses de type bonjour
*/
function processingGrettings(response) {
core.prepareMessage(response);
}
function processingHour(response) {
if(response ... | 'use strict';
const core = require('./core.js');
const fd = require('./field.js');
const service = require('./../services/services.js');
/*
* Fonction qui traite les réponses de type bonjour
*/
function processingGrettings(response) {
core.prepareMessage(response);
}
function processingHour(response) {
if(respon... |
Return empty when data is empty
Fix for unit tests | module.exports = function(data){
if (!data || data.length < 1) return {};
let d = {},
keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
let key = keys[i],
value = data[key],
current = d,
keyParts = key
.replace(new RegExp(/\[/g), '.')
.replace(new RegE... | module.exports = function(data){
let d = {},
keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
let key = keys[i],
value = data[key],
current = d,
keyParts = key
.replace(new RegExp(/\[/g), '.')
.replace(new RegExp(/\]/g), '')
.split('.');
for... |
FIX Name not showing in updates report | <?php
/**
* Describes an available update to an installed Composer package
*
* Originally from https://github.com/XploreNet/silverstripe-composerupdates
*
* @author Matt Dwen
* @license MIT
*/
class ComposerUpdate extends DataObject
{
/**
* @var array
*/
private static $db = array(
'Nam... | <?php
/**
* Describes an available update to an installed Composer package
*
* Originally from https://github.com/XploreNet/silverstripe-composerupdates
*
* @author Matt Dwen
* @license MIT
*/
class ComposerUpdate extends DataObject
{
/**
* @var array
*/
private static $db = array(
'Nam... |
cmd/torrent-metainfo-pprint: Switch to tagflag for argument parsing | package main
import (
"encoding/hex"
"encoding/json"
"fmt"
"log"
"os"
"github.com/anacrolix/tagflag"
"github.com/bradfitz/iter"
"github.com/anacrolix/torrent/metainfo"
)
var flags struct {
JustName bool
PieceHashes bool
tagflag.StartPos
TorrentFiles []string
}
func main() {
tagflag.Parse(&flags)
f... | package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"github.com/anacrolix/torrent/metainfo"
)
func main() {
name := flag.Bool("name", false, "print name")
flag.Parse()
for _, filename := range flag.Args() {
metainfo, err := metainfo.LoadFromFile(filename)
if err != nil {
log.Print(err)
c... |
Add setup examples for various vdom libs. | export const jsx = function(propMap) {
return function(h) {
return function(type, props) {
const args = [type, props];
if (props) {
Object.keys(propMap).forEach(fromProp => {
if (props[fromProp]) {
const toProp = propMap[fromProp];
props[toProp] = props[fromPr... | export const jsx = function(propMap, defaultProps) {
return function(h) {
return function(type, props) {
const args = [type, props];
if (props) {
Object.keys(propMap).forEach(fromProp => {
if (props[fromProp]) {
const toProp = propMap[fromProp];
props[toProp] ... |
Use real pathname from location | import React from "react";
import { View } from "react-native";
import { withRouter } from "react-router";
import ListingProvider from "../app/ListingProvider";
import PostListSort from "../components/PostListSort";
import PostList from "../components/PostList";
class ListingResolver extends React.Component {
rende... | import React from "react";
import { View } from "react-native";
import { withRouter } from "react-router";
import ListingProvider from "../app/ListingProvider";
import PostListSort from "../components/PostListSort";
import PostList from "../components/PostList";
class ListingResolver extends React.Component {
rende... |
Add a test for read_magic. | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
im... | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
im... |
Move start-time calculation so it measures each initialization | from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
from past.builtins import range
from clifford import Cl, randomMV, Frame, get_mult_function, conformalize, grade_obj
from clifford.tools import orthoFrames2Verser as of2v
import numpy as np
from numpy import exp, ... | from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
from past.builtins import range
from clifford import Cl, randomMV, Frame, get_mult_function, conformalize, grade_obj
from clifford.tools import orthoFrames2Verser as of2v
import numpy as np
from numpy import exp, ... |
Use convenience localStorage functions from Backbone | define([
'backbone',
'ui'
], function (Backbone, Ui) {
var AppRouter = Backbone.Router.extend({
routes: {
// Define some URL routes
'': 'home',
'signup': 'signup',
'orders': 'showOrders',
// Default
'*actions': 'defaultAction'
},
home: function() {
Ui.showH... | define([
'backbone',
'ui'
], function (Backbone, Ui) {
var AppRouter = Backbone.Router.extend({
routes: {
// Define some URL routes
'': 'home',
'signup': 'signup',
'orders': 'showOrders',
// Default
'*actions': 'defaultAction'
},
home: function() {
Ui.showH... |
Fix rpc_message_to_error failing to construct them | import re
from .common import (
ReadCancelledError, InvalidParameterError, TypeNotFoundError,
InvalidChecksumError
)
from .rpc_errors import (
RPCError, InvalidDCError, BadRequestError, UnauthorizedError,
ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError
)
from .rpc_errors_303 i... | import re
from .common import (
ReadCancelledError, InvalidParameterError, TypeNotFoundError,
InvalidChecksumError
)
from .rpc_errors import (
RPCError, InvalidDCError, BadRequestError, UnauthorizedError,
ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError
)
from .rpc_errors_303 i... |
Fix solution of leetcode question 60 | /**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getPermutation = function(n, k) {
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const totalNums = [1];
let index = 1;
let result = '';
while (index <= n) {
totalNums[index] = totalNums[totalNums.length - 1] * index;
... | /**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getPermutation = function(n, k) {
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const totalNums = [1];
let index = 1;
let result = '';
while (index <= n) {
totalNums[index] = totalNums[totalNums.length - 1] * index;
... |
Update createStore for new function names | const { StateSnapshot } = require('./state-snapshot');
class Store {
constructor(backingStore) {
this._backingStore = backingStore;
}
registerReducer(reducer) {
if (this.reducer) {
throw new Error(
'Attempted to register reducer to store that already has one'
);
}
this.reduc... | const { StateSnapshot } = require('./state-snapshot');
class Store {
constructor(backingStore) {
this._backingStore = backingStore;
}
registerReducer(reducer) {
if (this.reducer) {
throw new Error(
'Attempted to register reducer to store that already has one'
);
}
this.reduc... |
Fix an issue with handling of `null` feed URIs
Summary: Ref T8658. Caught this in the logs. This value may be set to `null`. Handle that gracefully.
Test Plan: Will check logs.
Reviewers: btrahan
Reviewed By: btrahan
Subscribers: epriestley
Maniphest Tasks: T8658
Differential Revision: https://secure.phabricator... | <?php
final class FeedPublisherWorker extends FeedPushWorker {
protected function doWork() {
$story = $this->loadFeedStory();
$uris = PhabricatorEnv::getEnvConfig('feed.http-hooks');
if ($uris) {
foreach ($uris as $uri) {
$this->queueTask(
'FeedPublisherHTTPWorker',
a... | <?php
final class FeedPublisherWorker extends FeedPushWorker {
protected function doWork() {
$story = $this->loadFeedStory();
$uris = PhabricatorEnv::getEnvConfig('feed.http-hooks');
foreach ($uris as $uri) {
$this->queueTask(
'FeedPublisherHTTPWorker',
array(
'key' => $... |
Add task and poem container's width | import React from 'react'
import AltContainer from 'alt-container'
import Header from './components/Header'
import Date from './components/Date'
import PoemContainer from './containers/PoemContainer'
import TaskContainer from './containers/TaskContainer'
import DateStore from './stores/DateStore'
import DateActions f... | import React from 'react'
import AltContainer from 'alt-container'
import Header from './components/Header'
import Date from './components/Date'
import PoemContainer from './containers/PoemContainer'
import TaskContainer from './containers/TaskContainer'
import DateStore from './stores/DateStore'
import DateActions f... |
[improvement] Remove duplication of code at deprecated Sync service
Add new line to the end of file | package com.edulify.modules.geolocation;
import org.junit.Test;
import play.test.WithApplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static play.test.Helpers.*;
/**
* Created by sovaalexandr
*/
public class Ge... | package com.edulify.modules.geolocation;
import org.junit.Test;
import play.test.WithApplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static play.test.Helpers.*;
/**
* Created by sovaalexandr
*/
public class Ge... |
Disable failing kotlin-multi-module gradle test | package io.quarkus.gradle.devmode;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Disabled;
import com.google.common.collect.ImmutableMap;
@Disabled
@org.junit.jupiter.api.Tag("failsOnJDK18")
public class MultiModuleKotlinProjectDevModeTest extends QuarkusDevGradleTestBase {
... | package io.quarkus.gradle.devmode;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.common.collect.ImmutableMap;
@org.junit.jupiter.api.Tag("failsOnJDK18")
public class MultiModuleKotlinProjectDevModeTest extends QuarkusDevGradleTestBase {
@Override
protected String projectDirecto... |
Rename parameter "value" to "element" for consistency
git-svn-id: d9b8539636d91aff9cd33ed5cd52a0cf73394897@1183040 13f79535-47bb-0310-9956-ffa450edef68 | // Copyright 2010 The Apache Software Foundation
//
// 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... | // Copyright 2010 The Apache Software Foundation
//
// 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... |
Add back support for safari10 | const os = require('os');
const TerserPlugin = require('terser-webpack-plugin');
/**
* parallel doesn't work yet for WSL (GNU/Linux on Windows)
* cf https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
* https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/302
* @return {Boolean} true if... | const os = require('os');
const TerserPlugin = require('terser-webpack-plugin');
/**
* parallel doesn't work yet for WSL (GNU/Linux on Windows)
* cf https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
* https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/302
* @return {Boolean} true if... |
Add prefix to headshot filenames for easy exclusion from gitignore | from django.core.management.base import BaseCommand, CommandError
from django.core.files import File
from django.conf import settings
from opencivicdata.core.models import Person as OCDPerson
import requests
class Command(BaseCommand):
help = 'Attach headshots to councilmembers'
def handle(self, *args, **o... | from django.core.management.base import BaseCommand, CommandError
from django.core.files import File
from django.conf import settings
from opencivicdata.core.models import Person as OCDPerson
import requests
class Command(BaseCommand):
help = 'Attach headshots to councilmembers'
def handle(self, *args, **o... |
Fix for HHVM false function | <?php
namespace Funct\CodeBlocks;
/**
* Returns true if all of the values in the array pass the callback truth test.
*
* @author Aurimas Niekis <aurimas.niekis@gmail.com>
*
* @param array $collection
* @param callable $callback
*
* @return bool
*/
function collection_every($collection, callable $callback ... | <?php
namespace Funct\CodeBlocks;
/**
* Returns true if all of the values in the array pass the callback truth test.
*
* @author Aurimas Niekis <aurimas.niekis@gmail.com>
*
* @param array $collection
* @param callable $callback
*
* @return bool
*/
function collection_every($collection, callable $callback ... |
Fix bug where rows are clicked by accident | /**
* Default templete script collection
* @author Melcher
*/
$(document).ready(function(e) {
// Make rows clickable while maintaing anchors
$('.clickable-row').click(function(e) {
// event target will always retrieve the anchor when clicked.
if(e.target.tagName !== 'A' && e.target.tagName !== 'INPUT') {
... | /**
* Default templete script collection
* @author Melcher
*/
$(document).ready(function(e) {
// Make rows clickable while maintaing anchors
$('.clickable-row').click(function(e) {
// event target will always retrieve the anchor when clicked.
if(e.target.tagName !== 'A') {
window.location = $(this).data... |
Revert "added a test for the map_reader before map_init -case which fails currently"
(deprecate init functions instead)
This reverts commit 88551bf444b7b358fea8e7eb4475df2c5d87ceeb. | from disco.test import TestCase, TestJob
class InitJob(TestJob):
params = {'x': 10}
sort = False
@staticmethod
def map_init(iter, params):
iter.next()
params['x'] += 100
@staticmethod
def map(e, params):
yield e, int(e) + params['x']
@staticmethod
def reduce_i... | from disco.test import TestCase, TestJob
class InitJob(TestJob):
sort = False
@staticmethod
def map_reader(stream, size, url, params):
params.x = 10
return (stream, size, url)
@staticmethod
def map_init(iter, params):
assert hasattr(params, 'x')
iter.next()
... |
Set registration form popup smaller (but not too much for good render on desktop) to fit better with mobile devices | /*
* Author: Pierre-Henry Soria <ph7software@gmail.com>
* Copyright: (c) 2013-2016, Pierre-Henry Soria. All Rights Reserved.
* License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
*/
// Only for visitors
$(document).ready(function()
{
var $oDial... | /*
* Author: Pierre-Henry Soria <ph7software@gmail.com>
* Copyright: (c) 2013-2016, Pierre-Henry Soria. All Rights Reserved.
* License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
*/
// Only for visitors
$(document).ready(function()
{
var $oDial... |
Fix potential TypeError with malformed cookie | <?php
declare(strict_types=1);
namespace Dflydev\FigCookies;
use function array_filter;
use function assert;
use function explode;
use function is_array;
use function preg_split;
use function urldecode;
class StringUtil
{
/** @return string[] */
public static function splitOnAttributeDelimiter(string $strin... | <?php
declare(strict_types=1);
namespace Dflydev\FigCookies;
use function array_filter;
use function assert;
use function explode;
use function is_array;
use function preg_split;
use function urldecode;
class StringUtil
{
/** @return string[] */
public static function splitOnAttributeDelimiter(string $strin... |
Sort dimensins to reduce code | class TriangleError(Exception):
pass
class Triangle(object):
def __init__(self, *dims):
if not self.is_valid(dims):
raise TriangleError("Invalid dimensions: {}".format(dims))
self.dims = sorted(dims)
def kind(self):
a, b, c = self.dims
if a == b and b == c: # i... | class TriangleError(Exception):
pass
class Triangle(object):
def __init__(self, *dims):
if not self.is_valid(dims):
raise TriangleError("Invalid dimensions: {}".format(dims))
self.dims = dims
def kind(self):
a, b, c = self.dims
if a == b and b == c:
... |
Prepend WAMP client to script block instead of putting it somewhere in between | <?php
namespace WyriHaximus\Ratchet\View\Helper;
use Cake\View\Helper;
class WampHelper extends Helper
{
public $helpers = [
'Html',
];
public function beforeLayout()
{
$this->_View->prepend('script', $this->Html->script('WyriHaximus/Ratchet.client'));
}
public function clie... | <?php
namespace WyriHaximus\Ratchet\View\Helper;
use Cake\View\Helper;
class WampHelper extends Helper
{
public $helpers = [
'Html',
];
public function beforeLayout()
{
$this->_View->append('script', $this->Html->script('WyriHaximus/Ratchet.client'));
}
public function clien... |
Add default value to status enum
Fix https://github.com/junaidnasir/larainvite/issues/6 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateInvitationUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_invitations', function (Blueprint $table) ... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateInvitationUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_invitations', function (Blueprint $table) ... |
Fix default sort order. azawawi-- | jQuery(function ($) {
setup_search_box();
$('.tablesorter').tablesorter({
sortList: [[0,0]],
headers: {
1: { sorter: 'text'},
2: { sorter: false }
}
});
});
function setup_search_box() {
var el = $('#my_search_box .search');
if ( ! el.length ) { retur... | jQuery(function ($) {
setup_search_box();
$('.tablesorter').tablesorter({
sortList: [[1,0]],
headers: {
1: { sorter: 'text'},
2: { sorter: false }
}
});
});
function setup_search_box() {
var el = $('#my_search_box .search');
if ( ! el.length ) { retur... |
Correct call to super constructor | #!/usr/bin/env python
from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math
class getDistance(EventState):
"""
Calcule la distance entre deux points donnes.
### InputKey
># point1
># point2
### OutputKey
#> distance
<= done
"""
def __init__... | #!/usr/bin/env python
from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math
class getDistance(EventState):
"""
Calcule la distance entre deux points donnes.
### InputKey
># point1
># point2
### OutputKey
#> distance
<= done
"""
def __init__... |
Add application object as controller constructor param | <?php
/**
* Base class for controllers
*
* @file BaseController.php
*
* PHP version 5.4+
*
* @author Yancharuk Alexander <alex at itvault dot info>
* @copyright © 2012-2016 Alexander Yancharuk
* @date 2016-10-21 16:43
* @license The BSD 3-Clause License
* <https://tldrlegal.com/lice... | <?php
/**
* Base class for controllers
*
* @file BaseController.php
*
* PHP version 5.4+
*
* @author Yancharuk Alexander <alex at itvault dot info>
* @copyright © 2012-2016 Alexander Yancharuk
* @date 2016-10-21 16:43
* @license The BSD 3-Clause License
* <https://tldrlegal.com/lice... |
Change from hg to git. | import functools
import subprocess
import django
import platform
from django.conf import settings
from django.contrib.sites.models import get_current_site
def system_info(request):
return {
'system': {
'django': django.get_version(),
'python': platform.python_version(),
... | import functools
import subprocess
import django
import platform
from django.conf import settings
from django.contrib.sites.models import get_current_site
def system_info(request):
return {
'system': {
'django': django.get_version(),
'python': platform.python_version(),
... |
Adjust in auth to avoid throwing full errors logs to end user. | 'use strict';
let express = require('express');
let passport = require('passport');
let signToken = require('../auth.service').signToken;
var router = express.Router();
router.post('/', function (req, res, next) {
passport.authenticate('local', (err, user, info) => {
let error = err || info;
if (... | 'use strict';
let express = require('express');
let passport = require('passport');
let signToken = require('../auth.service').signToken;
var router = express.Router();
router.post('/', function (req, res, next) {
passport.authenticate('local', (err, user, info) => {
let error = err || info;
if (... |
Use Victor instead of Jaguar | package com.saintsrobotics.frc.subsystems;
import com.saintsrobotics.frc.RobotMap;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Saints Robotics
*/
public class DriveTrain e... | package com.saintsrobotics.frc.subsystems;
import com.saintsrobotics.frc.RobotMap;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Saints Robotics
*/
public class DriveTrain e... |
Fix element(data) always returns 0 | /*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import 'semantic-ui-css/components/api';
import $ from 'jquery';
$.fn.extend({
taxonMoveUp() {
const e... | /*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import 'semantic-ui-css/components/api';
import $ from 'jquery';
$.fn.extend({
taxonMoveUp() {
const e... |
Add additional validation to request parameters
H1 59701 | <?
defined('C5_EXECUTE') or die("Access Denied.");
$val = \Core::make('helper/validation/numbers');
$cID = 0;
if ($val->integer($_REQUEST['cID'])) {
$cID = $_REQUEST['cID'];
}
if (!is_array($_REQUEST['cvID'])) {
die(t('Invalid Request.'));
}
?>
<div style="height: 100%">
<?
$tabs = array();
foreach ($_REQUEST... | <?
defined('C5_EXECUTE') or die("Access Denied.");
?>
<div style="height: 100%">
<? foreach($_REQUEST['cvID'] as $cvID) {
$tabs[] = array('view-version-' . $cvID, t('Version %s', $cvID), $checked);
$checked = false;
}
print $ih->tabs($tabs);
foreach($_REQUEST['cvID'] as $cvID) { ?>
<div id="ccm-tab-content-vie... |
Support for changing name in profile form | <?php
namespace Vanio\UserBundle\Form;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseProfileFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProfileFormType extends AbstractType
{
/** @var bool */... | <?php
namespace Vanio\UserBundle\Form;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseProfileFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProfileFormType extends AbstractType
{
/** @var bool */... |
Fix a jasmine test in CommentToggler | /* Copyright (c) 2010, Diaspora Inc. This file is
* licensed under the Affero General Public License version 3 or later. See
* the COPYRIGHT file.
*/
describe("Diaspora.Widgets.CommentToggler", function() {
var commentToggler;
beforeEach(function() {
jasmine.Clock.useMock();
spec.loadFixture("as... | /* Copyright (c) 2010, Diaspora Inc. This file is
* licensed under the Affero General Public License version 3 or later. See
* the COPYRIGHT file.
*/
describe("Diaspora.Widgets.CommentToggler", function() {
var commentToggler;
beforeEach(function() {
jasmine.Clock.useMock();
spec.loadFixture("as... |
Add error handling for localization failures | package org.javarosa.xml.util;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.NoLocalizedTextException;
/**
* Invalid structure error that can _potentially_ be recovered from via
* advanced user intervention. Useful for notifying the user that the issue lies
* on the server.
... | package org.javarosa.xml.util;
import org.javarosa.core.services.locale.Localization;
/**
* Invalid structure error that can _potentially_ be recovered from via
* advanced user intervention. Useful for notifying the user that the issue lies
* on the server.
*
* @author Phillip Mates (pmates@dimagi.com).
*/
publ... |
Make wrapped console compatible in oldIE | var config = require('./config')
var logStack = []
module.exports = {
getLogStack: function () {
return logStack
},
error: function(msg, data) {
return this.log('%c ' + msg, 'color: red', data)
},
warning: function(msg, data) {
return this.log('%c ' + msg, 'background-color: ffff00', data)
}... | var config = require('./config')
var logStack = []
module.exports = {
getLogStack: function () {
return logStack
},
error: function(msg, data) {
return this.log('%c' + msg, 'color: red', data)
},
warning: function(msg, data) {
return this.log('%c' + msg, 'background-color: ffff00', data)
},
... |
Remove the reference to table | import * as Boundless from './exports.js';
import * as _ from 'lodash';
import fs from 'fs';
_.mixin({'pascalCase': _.flow(_.camelCase, _.upperFirst)});
describe('exports', () => {
it('does not have any undefined keys (if failed, the require is probably wrong)', () => {
Object.keys(Boundless).forEach((key... | import * as Boundless from './exports.js';
import * as _ from 'lodash';
import fs from 'fs';
_.mixin({'pascalCase': _.flow(_.camelCase, _.upperFirst)});
describe('exports', () => {
it('does not have any undefined keys (if failed, the require is probably wrong)', () => {
Object.keys(Boundless).forEach((key... |
Make the black actually use black ascii BG colors.
The generated QR codes in the original version didn't work when using a
terminal with black text on white background.
This change makes the library use an actual color code for black (or at
least dark grey) background for the black color, just as it was using
the col... | var QRCode = require('./../vendor/QRCode'),
QRErrorCorrectLevel = require('./../vendor/QRCode/QRErrorCorrectLevel'),
black = "\033[40m \033[0m",
white = "\033[47m \033[0m",
toCell = function (isBlack) {
return isBlack ? black : white;
},
repeat = function (color) {
return {
... | var QRCode = require('./../vendor/QRCode'),
QRErrorCorrectLevel = require('./../vendor/QRCode/QRErrorCorrectLevel'),
black = " ",
white = "\033[47m \033[0m",
toCell = function (isBlack) {
return isBlack ? black : white;
},
repeat = function (color) {
return {
times:... |
Fix url reversing in Python 3 | """
Django Storage interface
"""
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse_lazy
from django.utils.encoding import force_text
from . import appconfig
__all__ = (
'private_storage',
'PrivateStorage',
)
class PrivateStorage(FileSystemStorage):
"""
... | """
Django Storage interface
"""
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse_lazy
from . import appconfig
__all__ = (
'private_storage',
'PrivateStorage',
)
class PrivateStorage(FileSystemStorage):
"""
Interface to the Django storage system,
... |
Allow options to be set with environment variables in lambda
Prior to this commit, the way to customize your installation of
echo-sonos was to make a copy of the options.example.js and hand
edit it for your setup.
After this commit, the way to customize your installation of
echo-sonos can be that you use the same opt... | // If you setup basic auth in node-sonos-http-api's settings.json, change the username
// and password here. Otherwise, just leave this alone and it will work without auth.
var auth = new Buffer(process.env.AUTH_USERNAME + ":" + process.env.AUTH_PASSWORD).toString("base64");
var options = {
appid: process.env.APPID... | // If you setup basic auth in node-sonos-http-api's settings.json, change the username
// and password here. Otherwise, just leave this alone and it will work without auth.
var auth = new Buffer("YOUR_USERNAME" + ":" + "YOUR_PASSWORD").toString("base64");
var options = {
appid: "ENTER_YOUR_APP_ID_FOR_ECHO_HERE",
... |
Switch deprecated function from util.print to process.stdout.write | 'use strict';
var exec = require('child_process').exec;
var fs = require('fs');
var rimraf = require('rimraf');
var repos = [
'https://github.com/syngan/vim-vimlint',
'https://github.com/ynkdir/vim-vimlparser'
];
function git_clone(url) {
var folder = url.slice(url.lastIndexOf('/') + 1);
rimraf(folder, fu... | 'use strict';
var exec = require('child_process').exec;
var util = require('util');
var fs = require('fs');
var rimraf = require('rimraf');
var repos = [
'https://github.com/syngan/vim-vimlint',
'https://github.com/ynkdir/vim-vimlparser'
];
function git_clone(url) {
var folder = url.slice(url.lastIndexOf('/') ... |
Add basic HTTP error handling. | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "https://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
... | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "https://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
... |
Swap the test-file assertion, to make output more sensible. | from __future__ import absolute_import
import glob
import os.path
import pytest
from scss import Scss
HERE = os.path.join(os.path.split(__file__)[0], 'files')
@pytest.mark.parametrize(
('scss_fn', 'css_fn'), [
(scss_fn, os.path.splitext(scss_fn)[0] + '.css')
for scss_fn in glob.glob(os.path.joi... | from __future__ import absolute_import
import glob
import os.path
import pytest
from scss import Scss
HERE = os.path.join(os.path.split(__file__)[0], 'files')
@pytest.mark.parametrize(
('scss_fn', 'css_fn'), [
(scss_fn, os.path.splitext(scss_fn)[0] + '.css')
for scss_fn in glob.glob(os.path.joi... |
Replace property kurento.release.url by bower.release.url
Change-Id: I05d204d870b09e32edcfed7a004dfcedbe6dd3c6 | /*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-... | /*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-... |
Write the last point for plot completeness |
# MONOTONE
# Produce a monotonically decreasing output plot from noisy data
# Input: columns: t x
# Output: columns: t_i x_i , sampled such that x_i <= x_j
# for j > i.
from string import *
import sys
# Set PYTHONPATH=$PWD
from plottools import *
if len(sys.argv) != 3:
abort("usage:... |
# MONOTONE
# Produce a monotonically decreasing output plot from noisy data
# Input: columns: t x
# Output: columns: t_i x_i , sampled such that x_i <= x_j
# for j > i.
from string import *
import sys
# Set PYTHONPATH=$PWD
from plottools import *
if len(sys.argv) != 3:
abort("usage:... |
Remove not needed request argument in view decorator.
Patch by: Pawel Solyga
Review by: to-be-reviewed
--HG--
extra : convert_revision : svn%3A32761e7d-7263-4528-b7be-7235b26367ec/trunk%40826 | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
Use regular expression for 'home' router path. | Router.route('home', {
path: /^\/news\/(\d*)/,
template: 'Home',
data: function() {
var news = [{
dateTime: 'December 19, 2014',
text: 'December Devshop SF: Advances in MongoDB scalability, Meteor + Polymer, reactive MySQL, and more'
}, {
dateTime: 'December 10, 2014',
text: 'Meteo... | Router.route('home', {
path: '/:newsLimit?',
template: 'Home',
data: function() {
var news = [{
dateTime: 'December 19, 2014',
text: 'December Devshop SF: Advances in MongoDB scalability, Meteor + Polymer, reactive MySQL, and more'
}, {
dateTime: 'December 10, 2014',
text: 'Meteor ... |
Make settings debug logs less confusing | import { observable, toJS } from 'mobx';
import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra';
import path from 'path';
import { SETTINGS_PATH } from '../config';
const debug = require('debug')('Franz:Settings');
export default class Settings {
type = '';
@observable store = {};
constructor... | import { observable, toJS } from 'mobx';
import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra';
import path from 'path';
import { SETTINGS_PATH } from '../config';
const debug = require('debug')('Franz:Settings');
export default class Settings {
type = '';
@observable store = {};
constructor... |
Print JSON document upon parse error | import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
... | import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
... |
Revert "Revert "Доработки в тесте на модификацию группы""
This reverts commit 6ea561d6543351b6c4c1977a470eabef096b69e6. | package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.HashSet;
import java.util.List;
import static org.testng.Assert.assertEquals;
/**
* Created by Sergei on 16.04.2016.
*/
public class GroupModificationTests extends TestBase {... | package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.HashSet;
import java.util.List;
import static org.testng.Assert.assertEquals;
/**
* Created by Sergei on 16.04.2016.
*/
public class GroupModificationTests extends TestBase {... |
Fix a logical error. A new project was persisted if it
was already found found in the database. It should be the opposite | package com.example.beer.dao;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import com.example.beer.model.Project;
@Singleton
public class ProjectDAO {
@PersistenceCo... | package com.example.beer.dao;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import com.example.beer.model.Project;
@Singleton
public class ProjectDAO {
@PersistenceCo... |
Fix texture applied to model
Former-commit-id: 82019a79aafd9ebd854ab5b23f011874bbb34ae7 | import {
Mesh,
MultiMaterial,
JSONLoader
} from 'three';
import {MeshComponent} from '../../core/MeshComponent';
class Model extends MeshComponent {
static defaults = {
...MeshComponent.defaults,
geometry: {
path: '',
loader: new JSONLoader(),
parser(geometry, materials) {
re... | import {
Mesh,
MultiMaterial,
JSONLoader
} from 'three';
import {MeshComponent} from '../../core/MeshComponent';
class Model extends MeshComponent {
static defaults = {
...MeshComponent.defaults,
geometry: {
path: '',
loader: new JSONLoader(),
parser(geometry, materials) {
re... |
Make compatible with Python 2 and 3. | #!/usr/bin/env python2
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package):
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path):
"""
>>> get_file_root("/tmp/test.txt")
... | #!/usr/bin/env python3
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package: str) -> str:
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path: str) -> str:
"""
>>> get_file_ro... |
Use API key from Env when loading google maps script | /* @flow */
import React from 'react';
import { GoogleMap } from 'react-google-maps';
import ScriptjsLoader from 'react-google-maps/lib/async/ScriptjsLoader';
import { latLon } from '../../../types/map';
type Props = {
spanFullPage: ?boolean,
defaultCenter: latLon,
};
/** @class Map */
function Map(props : Props)... | /* @flow */
import React from 'react';
import { GoogleMap } from 'react-google-maps';
import ScriptjsLoader from 'react-google-maps/lib/async/ScriptjsLoader';
import { latLon } from '../../../types/map';
type Props = {
spanFullPage: ?boolean,
defaultCenter: latLon,
};
/** @class Map */
function Map(props : Props)... |
Add an interface to get the loader | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from ..interface import TableLoaderInterface
class TableLoaderManager(TableLoaderInterface):
def __init__(self, loader):
self.__loader = loader
@property
def loader... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from ..interface import TableLoaderInterface
class TableLoaderManager(TableLoaderInterface):
def __init__(self, loader):
self.__loader = loader
@property
def format... |
Change int to long - now runs as expected | public class ArrayAnalyzerLarge {
public static void main (String[] args) {
ArrayUtil au = new ArrayUtil();
//StopWatch sw = new StopWatch();
int size = 10000000;
int valueSize = 250000001;
for (int i=0; i<11; i++) {
int[] array = au.randomIntArray(size, valueSize);
size... | public class ArrayAnalyzerLarge {
public static void main(String[] args) {
ArrayUtil au = new ArrayUtil();
//StopWatch sw = new StopWatch();
int size = 10000000;
int valueSize = 250000001;
for (int i=0; i<11; i++) {
int[] array = au.randomIntArray(size, valueSize);
size += 10... |
Fix compressed feeds in python3 | from __future__ import unicode_literals
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'wb') as output_file:
if feed.compression:
try:
output = gzip.open(output_file, 'wt')
... | import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'w') as output_file:
if feed.compression:
output = gzip.GzipFile(fileobj=output_file)
else:
output = output_file
writer = ... |
Add other dev domains to trusted domains. |
import {
POST_MESSAGE_TYPE_BACKGROUND_SETTINGS
} from './constants'
import {
updateBackgroundSettings
} from './background'
// Handle messages from webpage.
var trustedOrigins = [
'http://tab.gladly.io',
'https://tab.gladly.io',
'http://www.tabforacause.org',
'https://www.tabforacause.org',
'http://gla... |
import {
POST_MESSAGE_TYPE_BACKGROUND_SETTINGS
} from './constants'
import {
updateBackgroundSettings
} from './background'
// Handle messages from webpage.
var trustedOrigins = [
'http://localhost:3000', // dev
'http://tab.gladly.io',
'https://tab.gladly.io',
'http://www.tabforacause.org',
'https://ww... |
Remove console.log to make linter happy | import $ from 'jquery';
import Ember from 'ember';
export default Ember.Controller.extend({
extraText: '',
move: false,
manage: false,
options: ['move contributors', 'manage permissions'],
actions: {
changeText(option) {
if (option === 'move contributors') {
this.set('manage', false);
... | import $ from 'jquery';
import Ember from 'ember';
export default Ember.Controller.extend({
extraText: '',
move: false,
manage: false,
options: ['move contributors', 'manage permissions'],
actions: {
changeText(option) {
if (option === 'move contributors') {
this.set('manage', false);
... |
Bring into line with new styles | /** @jsx React.DOM */
var React = require('react'),
Tappable = require('../../touchstone/tappable');
module.exports = React.createClass({
displayName: 'RadioList',
propTypes: {
options: React.PropTypes.array,
value: React.PropTypes.string,
onChange: React.PropTypes.func
},
onChange: function(value) {
t... | /** @jsx React.DOM */
var React = require('react'),
Tappable = require('../../touchstone/tappable');
module.exports = React.createClass({
displayName: 'RadioList',
propTypes: {
options: React.PropTypes.array,
value: React.PropTypes.string,
onChange: React.PropTypes.func
},
onChange: function(value) {
t... |
Add a (temporary) bounding box around an added mesh | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
from Cura.Scene.BoxRenderer import BoxRenderer
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._co... | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._controller = Application.getInstance().getControl... |
FIX -Changes to avoid possible Gson fromJson exceptions | package com.martinchamarro.lazystorage.internal.database;
import com.google.gson.Gson;
import com.martinchamarro.lazystorage.internal.exception.JsonConversionException;
import com.martinchamarro.lazystorage.internal.exception.LazyStorageException;
final class TwoWaysJsonConverter {
private Gson gson;
public... | package com.martinchamarro.lazystorage.internal.database;
import com.google.gson.Gson;
import com.martinchamarro.lazystorage.internal.exception.JsonConversionException;
import com.martinchamarro.lazystorage.internal.exception.LazyStorageException;
final class TwoWaysJsonConverter {
private Gson gson;
public... |
Fix filepath to source directory when srcDir is specified and the first argument is blank | var gulp = require('gulp'),
react = require('gulp-react'),
gulpIf = require('gulp-if'),
uglify = require('gulp-uglify'),
_ = require('underscore'),
elixir = require('laravel-elixir'),
utilities = require('laravel-elixir/ingredients/commands/Utilities'),
notification = require('laravel-elixir... | var gulp = require('gulp'),
react = require('gulp-react'),
gulpIf = require('gulp-if'),
uglify = require('gulp-uglify'),
_ = require('underscore'),
elixir = require('laravel-elixir'),
utilities = require('laravel-elixir/ingredients/commands/Utilities'),
notification = require('laravel-elixir... |
Fix error code on non existent page | #!/usr/bin/env python2
from testlib import *
set_port("80")
set_server("us.bittoll.com")
def test_page_error():
r = apicall("nonexistant", "hi")
assert "error" in r
assert r["error"] != ""
assert int(r["error_code"]) == 1
def test_login(login):
info = login
assert 'username' in info
asser... | #!/usr/bin/env python2
from testlib import *
set_port("80")
set_server("us.bittoll.com")
def test_page_error():
r = apicall("nonexistant", "hi")
assert "error" in r
assert r["error"] != ""
assert int(r["error_code"]) == 0
def test_login(login):
info = login
assert 'username' in info
asser... |
Add timeouts to CSRF and cookie | //var ERR = require('async-stacktrace');
var express = require('express');
var router = express.Router();
var csrf = require('../../lib/csrf');
var config = require('../../lib/config');
router.get('/', function(req, res) {
res.locals.passwordInvalid = 'pl_assessmentpw' in req.cookies;
res.render(__filename.r... | //var ERR = require('async-stacktrace');
var express = require('express');
var router = express.Router();
var csrf = require('../../lib/csrf');
var config = require('../../lib/config');
router.get('/', function(req, res) {
res.locals.passwordInvalid = 'pl_assessmentpw' in req.cookies;
res.render(__filename.r... |
Add JobItemLoader and DataScienceJobsItemLoader class. | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
from scrapy.loader import Identity, ItemLoader
from scrapy.loader.processors import TakeFirst
class JobItem(Item):
website_url = F... | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
class JobItem(Item):
website_url = Field()
website_language = Field()
publication_date = Field()
posting_id = Field()... |
Add polish dict to base code | module.exports = {
'ar': require('../../i18n/ar.json'),
'da': require('../../i18n/da.json'),
'de': require('../../i18n/de.json'),
'en': require('../../i18n/en.json'),
'es': require('../../i18n/es.json'),
'fr': require('../../i18n/fr-FR.json'),
'fr-FR': require('../../i18n/fr-FR.json'),
'he': require('..... | module.exports = {
'ar': require('../../i18n/ar.json'),
'da': require('../../i18n/da.json'),
'de': require('../../i18n/de.json'),
'en': require('../../i18n/en.json'),
'es': require('../../i18n/es.json'),
'fr': require('../../i18n/fr-FR.json'),
'fr-FR': require('../../i18n/fr-FR.json'),
'he': require('..... |
Allow trailing slash at the end of URLs
Specifically app detail page and category app list. | from django.conf.urls import url, include
from django.contrib import admin
from nextcloudappstore.core.views import CategoryAppListView, AppDetailView, \
app_description
urlpatterns = [
url(r'^$', CategoryAppListView.as_view(), {'id': None}, name='home'),
url(r'^', include('allauth.urls')),
url(r'^cat... | from django.conf.urls import url, include
from django.contrib import admin
from nextcloudappstore.core.views import CategoryAppListView, AppDetailView, \
app_description
urlpatterns = [
url(r'^$', CategoryAppListView.as_view(), {'id': None}, name='home'),
url(r'^', include('allauth.urls')),
url(r'^cat... |
Correct the model in the trait | <?php
namespace Junaidnasir\Larainvite;
trait InviteTrait
{
/**
* return all invitation as laravel collection
* @return hasMany invitation Models
*/
public function invitations()
{
return $this->hasMany(config('larainvite.InvitationModel'));
}
/**
* return successful i... | <?php
namespace Junaidnasir\Larainvite;
trait InviteTrait
{
/**
* return all invitation as laravel collection
* @return hasMany invitation Models
*/
public function invitations()
{
return $this->hasMany('Junaidnasir\Larainvite\Models\LaraInviteModel');
}
/**
* return s... |
Fix `migrate:reset` args as it doesn't accept --step | <?php
declare(strict_types=1);
namespace Cortex\Foundation\Console\Commands;
use Illuminate\Console\Command;
class RollbackCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:rollback:foundation {--force : Force... | <?php
declare(strict_types=1);
namespace Cortex\Foundation\Console\Commands;
use Illuminate\Console\Command;
class RollbackCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:rollback:foundation {--force : Force... |
Switch to use the playback API | import path from 'path';
const browser = WindowManager.getAll('main')[0];
const resetThumbbarButtons = (isPlaying) => {
browser.setThumbarButtons([
{
tooltip: 'Previous Track',
icon: path.resolve(`${__dirname}/../../../assets/img/media_controls/previous.png`),
click: Emitter.sendToGooglePlayMus... | import path from 'path';
const browser = WindowManager.getAll('main')[0];
const resetThumbbarButtons = (isPlaying) => {
browser.setThumbarButtons([
{
tooltip: 'Previous Track',
icon: path.resolve(`${__dirname}/../../../assets/img/media_controls/previous.png`),
click: Emitter.sendToGooglePlayMus... |
Fix access-control-allow-headers value on response | var httpProxy = require('http-proxy');
var http = require('http');
var morgan = require('morgan');
var logger = morgan('short');
var proxy = httpProxy.createProxyServer({
target: 'https://accountview.net',
secure: false
})
.on('proxyRes', function (proxyRes, req, res) {
proxyRes.headers['access-control-... | var httpProxy = require('http-proxy');
var http = require('http');
var morgan = require('morgan');
var logger = morgan('short');
var proxy = httpProxy.createProxyServer({
target: 'https://accountview.net',
secure: false
})
.on('proxyRes', function (proxyRes, req, res) {
proxyRes.headers['access-control-... |
Add missing semicolon to example
Adds a missing semicolon to the fade transition example. | import opacity from 'ember-animated/motions/opacity';
/**
Fades inserted, removed, and kept sprites.
```js
import fade from 'ember-animated/transitions/fade';
export default Component.extend({
transition: fade
});
```
```hbs
{{#animated-if use=transition}}
...
{{/animated-if}}
```
@fu... | import opacity from 'ember-animated/motions/opacity';
/**
Fades inserted, removed, and kept sprites.
```js
import fade from 'ember-animated/transitions/fade'
export default Component.extend({
transition: fade
});
```
```hbs
{{#animated-if use=transition}}
...
{{/animated-if}}
```
@fun... |
Fix some code quality issues. | from typing import Text, Type
import pytest
from rasa.core.policies.rule_policy import RulePolicy
from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier
from rasa.shared.core.constants import (
CLASSIFIER_NAME_FALLBACK,
POLICY_NAME_RULE,
)
@pytest.mark.parametrize(
"name_in_constant, po... | from typing import Text, Type
import pytest
from rasa.core.policies.rule_policy import RulePolicy
from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier
from rasa.shared.core.constants import (
CLASSIFIER_NAME_FALLBACK,
POLICY_NAME_RULE,
)
@pytest.mark.parametrize(
"name_in_constant, po... |
Fix constraint problem for real. Another sequelize bug | import BSDClient from '../../bsd-instance';
export default function(sequelize, DataTypes) {
let GCBSDGroup = sequelize.define('GCBSDGroup', {
query: {
type: DataTypes.TEXT,
allowNull: true
}
}, {
underscored: true,
tableName: 'gc_bsd_groups',
updatedAt: 'modified_dt',
createdAt:... | import BSDClient from '../../bsd-instance';
export default function(sequelize, DataTypes) {
let GCBSDGroup = sequelize.define('GCBSDGroup', {
query: {
type: DataTypes.TEXT,
allowNull: true
}
}, {
underscored: true,
tableName: 'gc_bsd_groups',
updatedAt: 'modified_dt',
createdAt:... |
Add last action time calc. | 'use strict';
function getTimeInList(actions) {
actions.reverse();
var duration = [];
var listBefore = {};
var listAfter = {};
var i = 1;
actions.forEach(function(action) {
var diff = 0;
listAfter = {
date: action.date,
list: action.data.listAfter
};
if (listBefore.date) {
... | 'use strict';
function getTimeInList(actions) {
actions.reverse();
var duration = [];
var listBefore = {};
var listAfter = {};
actions.forEach(function(action) {
// get date and listAfter
listAfter = {
date: action.date,
list: action.data.listAfter
};
// if isset list before get... |
Fix print format for python3 | # -*- coding: utf-8 -*-
"""
Simple example showing evaluating embedding on similarity datasets
"""
import logging
from six import iteritems
from web.datasets.similarity import fetch_MEN, fetch_WS353, fetch_SimLex999
from web.embeddings import fetch_GloVe
from web.evaluate import evaluate_similarity
# Configure loggi... | # -*- coding: utf-8 -*-
"""
Simple example showing evaluating embedding on similarity datasets
"""
import logging
from six import iteritems
from web.datasets.similarity import fetch_MEN, fetch_WS353, fetch_SimLex999
from web.embeddings import fetch_GloVe
from web.evaluate import evaluate_similarity
# Configure loggi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.