text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix bool logic in mask test & add test criteria | import numpy as np
import pytest
import yatsm._cyprep as cyprep
def test_get_valid_mask():
n_bands, n_images, n_mask = 8, 500, 50
data = np.random.randint(0, 10000,
size=(n_bands, n_images)).astype(np.int32)
# Add in bad data
_idx = np.arange(0, n_images)
for b in rang... | import numpy as np
import pytest
import yatsm._cyprep as cyprep
def test_get_valid_mask():
n_bands, n_images, n_mask = 8, 500, 50
data = np.random.randint(0, 10000,
size=(n_bands, n_images)).astype(np.int32)
# Add in bad data
_idx = np.arange(0, n_images)
for b in rang... |
Fix for quotation marks in redirect URL
Some websites use quotation marks around the url= query in the meta-refresh tag. Example: https://presse.stuttgart-tourist.de/die-weihnachtsmaerkte-in-der-region-stuttgart
<meta HTTP-EQUIV="refresh" content="0;url='https://presse.stuttgart-tourist.de/die-weihnachtsmaerkte-in-de... | <?php
declare(strict_types = 1);
namespace Embed\Detectors;
use Psr\Http\Message\UriInterface;
class Redirect extends Detector
{
public function detect(): ?UriInterface
{
$document = $this->extractor->getDocument();
$value = $document->select('.//meta', ['http-equiv' => 'refresh'])->str('cont... | <?php
declare(strict_types = 1);
namespace Embed\Detectors;
use Psr\Http\Message\UriInterface;
class Redirect extends Detector
{
public function detect(): ?UriInterface
{
$document = $this->extractor->getDocument();
$value = $document->select('.//meta', ['http-equiv' => 'refresh'])->str('cont... |
[Core] Fix class loading on Windows
Fixes: #1540 | package cucumber.runtime.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
class FileResource implements Resource {
private final File root;
private final File file;
private final boolean classpathFileResource;
static FileResource createF... | package cucumber.runtime.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
class FileResource implements Resource {
private final File root;
private final File file;
private final boolean classpathFileResource;
static FileResource createF... |
Add attribution for macro used | <?php
// Inspired from: http://forums.laravel.io/viewtopic.php?id=827
HTML::macro('nav_item', function($url, $text, $a_attr = [], $active_class = 'active', $li_attrs = [])
{
$href = HTML::link($url, $text, $a_attr);
$response = '';
if( Request::is($url) || Request::is($url . '/*') )
{
if(i... | <?php
HTML::macro('nav_item', function($url, $text, $a_attr = [], $active_class = 'active', $li_attrs = [])
{
$href = HTML::link($url, $text, $a_attr);
$response = '';
if( Request::is($url) || Request::is($url . '/*') )
{
if(isset($li_attrs['class']))
{
$li_attrs['class... |
Set the default prefix for ProjectSurveys to gsoc_program. | #!/usr/bin/python2.5
#
# Copyright 2009 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 2009 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... |
Remove cms dependency in test-runner | HELPER_SETTINGS = {
'SITE_ID': 1,
'TIME_ZONE': 'Europe/Zurich',
'LANGUAGES': (
('en', 'English'),
('de', 'German'),
('fr', 'French'),
),
'INSTALLED_APPS': [
'parler',
'treebeard',
'aldryn_categories',
],
'PARLER_LANGUAGES': {
1: (
... | HELPER_SETTINGS = {
'SITE_ID': 1,
'TIME_ZONE': 'Europe/Zurich',
'LANGUAGES': (
('en', 'English'),
('de', 'German'),
('fr', 'French'),
),
'INSTALLED_APPS': [
'parler',
'treebeard',
'aldryn_categories',
],
'PARLER_LANGUAGES': {
1: (
... |
Update action item distribution alert text to better reflect current application logic | export default {
"prime-directive": {
alert: null,
confirmationMessage: "Are you sure want to proceed to the Idea Generation stage? This will commence the retro in earnest.",
nextStage: "idea-generation",
button: {
copy: "Proceed to Idea Generation",
iconClass: "arrow right",
},
},
... | export default {
"prime-directive": {
alert: null,
confirmationMessage: "Are you sure want to proceed to the Idea Generation stage? This will commence the retro in earnest.",
nextStage: "idea-generation",
button: {
copy: "Proceed to Idea Generation",
iconClass: "arrow right",
},
},
... |
Add APA websites to URL patterns where client is known to be embedded.
URL patterns provided by Kadidra McCloud at APA.
Fixes https://github.com/hypothesis/product-backlog/issues/814 | import fnmatch
import re
from urllib.parse import urlparse
# Hardcoded URL patterns where client is assumed to be embedded.
#
# Only the hostname and path are included in the pattern. The path must be
# specified; use "example.com/*" to match all URLs on a particular domain.
#
# Patterns are shell-style wildcards ('*'... | import fnmatch
import re
from urllib.parse import urlparse
# Hardcoded URL patterns where client is assumed to be embedded.
#
# Only the hostname and path are included in the pattern. The path must be
# specified; use "example.com/*" to match all URLs on a particular domain.
#
# Patterns are shell-style wildcards ('*'... |
Make NetworkDevice serializable to help with potential cache implementations. | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribut... | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribut... |
Fix bug with how Pantheon is disabling updates | <?php
// Only in Test and Live Environments...
if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) {
//
// Disable Core Updates EVERYWHERE (use git upstream)
//
function _pantheon_disable_wp_updates() {
include ABSPATH . WPINC . '/version.php';
return (object) array(
'updates' =... | <?php
// Only in Test and Live Environments...
if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) {
//
// Disable Core Updates EVERYWHERE (use git upstream)
//
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
//
// Disable Plugin Updates
//
a... |
Fix LINE login procedure:
1. First fire App() so that assertions are not interrupted by LINE login
2. LINE login redirect URI fix: location.href already includes location.search. Repeating that will result in incorrect url token | import 'core-js';
import 'normalize.css';
import './index.scss';
import { isDuringLiffRedirect } from './lib';
import App from './App.svelte';
liff.init({ liffId: LIFF_ID }).then(() => {
// liff.init should have corrected the path now, don't initialize app and just wait...
// Ref: https://www.facebook.com/groups/l... | import 'core-js';
import 'normalize.css';
import './index.scss';
import { isDuringLiffRedirect } from './lib';
import App from './App.svelte';
liff.init({ liffId: LIFF_ID }).then(() => {
// liff.init should have corrected the path now, don't initialize app and just wait...
// Ref: https://www.facebook.com/groups/l... |
Add missing conditional for spring-security
Without it, if spring security is not present, it creates a runtime exception
due to AuthenticationEntryPointr not being in the classpath | package org.zalando.problem.spring.web.autoconfigure.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
im... | package org.zalando.problem.spring.web.autoconfigure.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.builders.HttpSecurit... |
Fix error in loading trees
Former-commit-id: 6fda03a47c5fa2d65c143ebdd81e158ba5e1ccda | #! /usr/bin/env python3
import os
import shutil
import datetime
import sys
from ete3 import Tree
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=Tree(tree_newick_fn,format=format)
def process_node(self,node):
if node... | #! /usr/bin/env python3
import os
import shutil
import datetime
import sys
import argparse
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=read_newick(tree_newick_fn,format=format)
... |
Clean up nicely upon $destruction. | 'use strict';
angular.module('ngClipboard', []).
value('ZeroClipboardConfig', {
path: '//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/1.2.3/ZeroClipboard.swf'
}).
directive('clipCopy', ['$window', 'ZeroClipboardConfig', function ($window, ZeroClipboardConfig) {
return {
scope: {
clipCopy: '... | 'use strict';
angular.module('ngClipboard', []).
value('ZeroClipboardConfig', {
path: '//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/1.2.3/ZeroClipboard.swf'
}).
directive('clipCopy', ['$window', 'ZeroClipboardConfig', function ($window, ZeroClipboardConfig) {
return {
scope: {
clipCopy: '... |
Tweak documentation for market listener in matching engine | package org.jvirtanen.parity.match;
/**
* The interface for outbound events from the matching engine.
*/
public interface MarketListener {
/**
* Match an incoming order to a resting order in the order book. The match
* occurs at the price of the order in the order book.
*
* @param restingOrd... | package org.jvirtanen.parity.match;
/**
* <code>MarketListener</code> is the interface for outbound events from the
* matching engine.
*/
public interface MarketListener {
/**
* Match an incoming order to a resting order in the order book. The match
* occurs at the price of the order in the order boo... |
Add name attribute to function | package net.ssehub.kernel_haven.code_model.ast;
import net.ssehub.kernel_haven.util.logic.Formula;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
public class Function extends SyntaxElementWithChildreen {
private @NonNull String name;
private @NonNull SyntaxElement header;
public Func... | package net.ssehub.kernel_haven.code_model.ast;
import net.ssehub.kernel_haven.util.logic.Formula;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
public class Function extends SyntaxElementWithChildreen {
private @NonNull SyntaxElement header;
public Function(@NonNull Formula presenceCondition... |
Update env - only load dotenv in development | 'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser');
var hbs = require('hbs');
var app = express();
if(process.env.NODE_E... | 'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser');
var hbs = require('hbs');
var app = express();
require('dotenv').loa... |
Add label so we know where it came from | package comments
import (
"log"
"os"
"github.com/google/go-github/github"
)
var (
pendingFeedbackLabel = "pending-feedback"
HandlerPendingFeedbackLabel = func(client *github.Client, event github.IssueCommentEvent) error {
// if the comment is from the issue author & issue has the "pending-feedback", remove t... | package comments
import (
"log"
"os"
"github.com/google/go-github/github"
)
var (
pendingFeedbackLabel = "pending-feedback"
HandlerPendingFeedbackLabel = func(client *github.Client, event github.IssueCommentEvent) error {
// if the comment is from the issue author & issue has the "pending-feedback", remove t... |
Put ExcelWriter in pandas namespace | # pylint: disable-msg=W0614,W0401,W0611,W0622
__docformat__ = 'restructuredtext'
from datetime import datetime
import numpy as np
try:
import pandas._tseries as lib
except Exception, e: # pragma: no cover
if 'No module named' in str(e):
raise ImportError('C extensions not built: if you installed al... | # pylint: disable-msg=W0614,W0401,W0611,W0622
__docformat__ = 'restructuredtext'
from datetime import datetime
import numpy as np
try:
import pandas._tseries as lib
except Exception, e: # pragma: no cover
if 'No module named' in str(e):
raise ImportError('C extensions not built: if you installed al... |
Fix brackets in the user number migration. | """hide user numbers
Revision ID: 2945717e3720
Revises: f8acbd22162
Create Date: 2016-01-31 00:43:02.777003
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
# revision identifiers, used by Alembic.
revision = '2945717e3720'
down_revision = 'f8acbd22162'
branch_labels = None... | """hide user numbers
Revision ID: 2945717e3720
Revises: f8acbd22162
Create Date: 2016-01-31 00:43:02.777003
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
# revision identifiers, used by Alembic.
revision = '2945717e3720'
down_revision = 'f8acbd22162'
branch_labels = None... |
Use computeIfAbsent to avoid concurrency issues
(cherry picked from commit a79513112c7e3b46370deca6d3bb1b47432df00b) | package liquibase.executor;
import liquibase.database.Database;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.ServiceLocator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ExecutorService {
private static ExecutorService instance = n... | package liquibase.executor;
import liquibase.database.Database;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.ServiceLocator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ExecutorService {
private static ExecutorService instance = n... |
[tracker] Add + button to add a model | <?php
/*
----------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2008 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org/
----------------------------------------------------------------... | <?php
/*
----------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2008 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org/
----------------------------------------------------------------... |
Fix an error on the test | <?php
namespace PiradoIV\Munchitos\Test;
use \PiradoIV\Munchitos\Munchitos;
class ImagesTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->html = <<<HTML
<!doctype html>
<html>
<body>
<a href="http://www.example.org/">
<img src="images/testing.png" alt="Test... | <?php
namespace PiradoIV\Munchitos\Test;
use \PiradoIV\Munchitos\Munchitos;
class ImagesTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->html = <<<HTML
<!doctype html>
<html>
<body>
<a href="http://www.example.org/">
<img src="images/testing.png" alt="Test... |
Break the build for kicks | import { addError } from './codeship-notifications';
describe('codeship-notifications/add-error', () => {
beforeAll(() => {
global.atom = {
notifications: {
addError: jest.fn(),
},
};
});
afterAll(() => {
global.atom = undefined;
});
it('adds error notification to atom', () ... | import { addError } from './codeship-notifications';
describe('codeship-notifications/add-error', () => {
beforeAll(() => {
global.atom = {
notifications: {
addError: jest.fn(),
},
};
});
afterAll(() => {
global.atom = undefined;
});
it('adds error notification to atom', () ... |
Update for plug-in : wallhaven.cc | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name: 'wallhaven.cc',
version:'3.0',
prepareImgLinks: function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'img[src*="/th.wallhaven.cc/"]',
/\/th.wallhaven.cc\/(.*)\/(.*)\/(.*)\.(.*)$/,... | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name: 'wallhaven.cc',
prepareImgLinks: function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'img[src*="/th.wallhaven.cc/"]',
/\/th.wallhaven.cc\/(.*)\/(.*)\/(.*)\.(.*)$/,
'/w.wall... |
Remove Babel dependency and convert to standard code style | const TabStop = require('./tab-stop')
class TabStopList {
constructor (snippet) {
this.snippet = snippet
this.list = {}
}
get length () {
return Object.keys(this.list).length
}
findOrCreate ({ index, snippet }) {
if (!this.list[index]) {
this.list[index] = new TabStop({ index, snippet... | /** @babel */
import TabStop from './tab-stop';
class TabStopList {
constructor (snippet) {
this.snippet = snippet;
this.list = {};
}
get length () {
return Object.keys(this.list).length;
}
findOrCreate({ index, snippet }) {
if (!this.list[index]) {
this.list[index] = new TabStop({ ... |
Remove focus effect on readonly fields | $(window).load(function(){
var selector = '.settings-nav li';
$(selector).not(".collapse-li").click(function () {
$(selector).not(".collapse-li").removeClass('active');
});
// Show the relevant tab from url
var url = document.location.toString();
if (url.match('#')) {
$('.setti... | $(window).load(function(){
var selector = '.settings-nav li';
$(selector).not(".collapse-li").click(function () {
$(selector).not(".collapse-li").removeClass('active');
});
// Show the relevant tab from url
var url = document.location.toString();
if (url.match('#')) {
$('.setti... |
Add necessary behaviors and validation rules. | <?php
namespace common\models\comments;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
abstract class Comment extends ActiveRecord
{
public static function instantiate($row)
{
return new AdjacencyListComment();
}
public static function crea... | <?php
namespace common\models\comments;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
abstract class Comment extends ActiveRecord
{
public static function instantiate($row)
{
return new AdjacencyListComment();
}
public static function crea... |
Fix typo in inventory API test script. | #!/usr/bin/env python
import json
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-l', '--list', default=False, dest="list_hosts", action="store_true")
parser.add_option('-H', '--host', default=None, dest="host")
parser.add_option('-e', '--extra-vars', default=None, dest="extr... | #!/usr/bin/env python
import json
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-l', '--list', default=False, dest="list_hosts", action="store_true")
parser.add_option('-H', '--host', default=None, dest="host")
parser.add_option('-e', '--extra-vars', default=None, dest="extr... |
Write function to deal with colons in url | import React from 'react'
import {connect} from 'react-redux';
const Article = ({article, channelName}) => {
return (
<div>
<h1>{article.title}</h1>
<img src={article.urlToImage} className="image"/>
<h5>Posted at: {article.publishedAt}</h5>
<p>{article.description}</p>
<a href={art... | import React from 'react'
import {connect} from 'react-redux';
const Article = ({article, channelName}) => {
return (
<div>
<h1>{article.title}</h1>
<img src={article.urlToImage} className="image"/>
<h5>Posted at: {article.publishedAt}</h5>
<p>{article.description}</p>
<a href={art... |
Make sure s.Relevance is normalized (0, 1) | package scoring
import (
"fmt"
"math"
"time"
)
// A point of reference Score.Update and Score.Relevance use to reference the
// current time. It is used in testing, so we always have the same current
// time. This is okay for this programs as it won't run for long.
var Now time.Time
// Represents a weight of a sc... | package scoring
import (
"fmt"
"math"
"time"
)
// A point of reference Score.Update and Score.Relevance use to reference the
// current time. It is used in testing, so we always have the same current
// time. This is okay for this programs as it won't run for long.
var Now time.Time
// Represents a weight of a sc... |
Fix provider constant in the example.
git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@1090630 13f79535-47bb-0310-9956-ffa450edef68 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
Add a comment to explain fsCall() safety checks | //go:build js
package syscall
import (
"syscall/js"
)
// fsCall emulates a file system-related syscall via a corresponding NodeJS fs
// API.
//
// This version is similar to the upstream, but it gracefully handles missing fs
// methods (allowing for smaller prelude) and removes a workaround for an
// obsolete NodeJ... | //go:build js
package syscall
import (
"syscall/js"
)
// fsCall emulates a file system-related syscall via a corresponding NodeJS fs
// API.
//
// This version is similar to the upstream, but it gracefully handles missing fs
// methods (allowing for smaller prelude) and removes a workaround for an
// obsolete NodeJ... |
Add more modules to vendor entry | var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BundleTracker = require('webpack-bundle-tracker');
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
context: __dirname,
devtool: 'eval-sou... | var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BundleTracker = require('webpack-bundle-tracker');
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
context: __dirname,
devtool: 'eval-sou... |
Correct permission tests for organization stats | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationStatsPermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationStatsPermissionTest, self).setUp()
self.path = reverse('sent... | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationStatsPermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationStatsPermissionTest, self).setUp()
self.path = reverse('sent... |
Allow POST requests on server side | """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.... | """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.... |
Fix broken list_methods due to inspect behaviour | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import inspect
class DynamicMethods(object):
def list_methods(self, predicate):
"""Find all transform methods within the class that satisfies the
predicate.
Returns:
A list of tuples containing method names and correspon... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import inspect
class DynamicMethods(object):
def list_methods(self, predicate):
"""Find all transform methods within the class that satisfies the
predicate.
Returns:
A list of tuples containing method names and correspon... |
[ProductVariant] Add locale to product variant query builders | <?php
/*
* 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.
*/
namespace Sylius\Component\Product\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Pr... | <?php
/*
* 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.
*/
namespace Sylius\Component\Product\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Pr... |
Allow opening a database (bolt, leveldb, mongo) through Go API | package cayley
import (
"github.com/google/cayley/graph"
_ "github.com/google/cayley/graph/memstore"
"github.com/google/cayley/graph/path"
"github.com/google/cayley/quad"
_ "github.com/google/cayley/writer"
)
type Iterator graph.Iterator
type QuadStore graph.QuadStore
type QuadWriter graph.QuadWriter
type Path ... | package cayley
import (
"github.com/google/cayley/graph"
_ "github.com/google/cayley/graph/memstore"
"github.com/google/cayley/graph/path"
"github.com/google/cayley/quad"
_ "github.com/google/cayley/writer"
)
type Iterator graph.Iterator
type QuadStore graph.QuadStore
type QuadWriter graph.QuadWriter
type Path ... |
Add defined() guard around define(ARTISAN_BINARY) | <?php
namespace OpenDominion;
use Illuminate\Foundation\Application as LaravelApplication;
class Application extends LaravelApplication
{
protected $appPath;
public function __construct($basePath)
{
parent::__construct($basePath);
$this->appPath = ($this->basePath() . DIRECTORY_SEPARATO... | <?php
namespace OpenDominion;
use Illuminate\Foundation\Application as LaravelApplication;
class Application extends LaravelApplication
{
protected $appPath;
public function __construct($basePath)
{
parent::__construct($basePath);
$this->appPath = ($this->basePath() . DIRECTORY_SEPARATO... |
Add finally blocks to ensure tests always clean up | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from io import BytesIO
import sys
import mock_modules
import yv_suggest.shared as yvs
@contextmanager
def redirect_stdout():
"""temporarily redirect stdout to new output stream"""
original_stdout = sys.stdout
out = BytesI... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from io import BytesIO
import sys
import mock_modules
import yv_suggest.shared as yvs
@contextmanager
def redirect_stdout():
"""temporarily redirect stdout to new output stream"""
original_stdout = sys.stdout
out = BytesI... |
Hide the button after adding the page | $('#likes').click(function() {
var catid;
catid = $(this).attr('data-catid');
$.get('/rango/like_category/', {category_id: catid}, function(data) {
$('#like_count').html(data);
$('#likes').hide();
});
});
$('#suggestion').keyup(function () {
var query;
query = $(this).val();
$.get('/rango/suggest... | $('#likes').click(function() {
var catid;
catid = $(this).attr('data-catid');
$.get('/rango/like_category/', {category_id: catid}, function(data) {
$('#like_count').html(data);
$('#likes').hide();
});
});
$('#suggestion').keyup(function () {
var query;
query = $(this).val();
$.get('/rango/suggest... |
Add example of scheme_eval_v usage | #! /usr/bin/env python
#
# values.py
#
"""
An example of using values via Python API
"""
from opencog.atomspace import AtomSpace, TruthValue
from opencog.type_constructors import *
from opencog.scheme_wrapper import scheme_eval_v
atomspace = AtomSpace()
set_type_ctor_atomspace(atomspace)
a = FloatValue([1.0, 2.0, 3.... | #! /usr/bin/env python
#
# values.py
#
"""
An example of using values via Python API
"""
from opencog.atomspace import AtomSpace, TruthValue
from opencog.type_constructors import *
a = AtomSpace()
set_type_ctor_atomspace(a)
a = FloatValue([1.0, 2.0, 3.0])
b = FloatValue([1.0, 2.0, 3.0])
c = FloatValue(1.0)
print('{}... |
Add "is it" as option to ask for temperature | module.exports = {
'responses': {
'GREET': 'Hello! How are you doing today :\)',
'HELP': 'I can help you with a bunch of things around your house.\n\n'
+ 'You can check in on your security cameras, ask me the temperature, and much more!\n'
+ 'I will also notify you during events such as a visitor ... | module.exports = {
'responses': {
'GREET': 'Hello! How are you doing today :\)',
'HELP': 'I can help you with a bunch of things around your house.\n\n'
+ 'You can check in on your security cameras, ask me the temperature, and much more!\n'
+ 'I will also notify you during events such as a visitor ... |
Add ifEnabled function for idea-hub and wrap main exports. | /**
* Idea Hub module initialization.
*
* 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... | /**
* Idea Hub module initialization.
*
* 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... |
42: Add direct inferred edges as part of loading SciGraph
Task-Url: https://github.com/SciCrunch/SciGraph/issues/issue/42
Removes test to resolve inference issues | package edu.sdsc.scigraph.owlapi.cases;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import org.junit.Ignore;
import org.junit.Test;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Node;
impo... | package edu.sdsc.scigraph.owlapi.cases;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import org.junit.Test;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Rela... |
Fix 'zero length field name in format' error | from django.db import models
class Metric(models.Model):
class Meta:
db_table = 'metric'
def __unicode__(self):
return self.name
name = models.CharField(max_length=128)
explanation_url = models.CharField(max_length=256)
units = models.CharField(max_length=128)
class Environment... | from django.db import models
class Metric(models.Model):
class Meta:
db_table = 'metric'
def __unicode__(self):
return self.name
name = models.CharField(max_length=128)
explanation_url = models.CharField(max_length=256)
units = models.CharField(max_length=128)
class Environment... |
Move import back to the top | # Color palette returns an array of colors (rainbow)
from matplotlib import pyplot as plt
import numpy as np
from plantcv.plantcv import params
def color_palette(num):
"""color_palette: Returns a list of colors length num
Inputs:
num = number of colors to return.
Returns:
colors = a ... | # Color palette returns an array of colors (rainbow)
import numpy as np
from plantcv.plantcv import params
def color_palette(num):
"""color_palette: Returns a list of colors length num
Inputs:
num = number of colors to return.
Returns:
colors = a list of color lists (RGB values)
... |
Rename babel to transpile for consistency with socket.io repo | var gulp = require('gulp');
var mocha = require('gulp-mocha');
var babel = require("gulp-babel");
var TESTS = 'test/*.js';
var REPORTER = 'dot';
gulp.task("default", ["transpile"]);
gulp.task('test', function(){
return gulp.src(TESTS, {read: false})
.pipe(mocha({
slow: 500,
reporter: REPORTER,
... | var gulp = require('gulp');
var mocha = require('gulp-mocha');
var babel = require("gulp-babel");
var TESTS = 'test/*.js';
var REPORTER = 'dot';
gulp.task("default", ["babel"]);
gulp.task('test', function(){
return gulp.src(TESTS, {read: false})
.pipe(mocha({
slow: 500,
reporter: REPORTER,
... |
Make autosuggest getSuggestionalValue with 'id' style default | import React from 'react'
import Autosuggest from 'react-autosuggest'
import style from './bpk-autosuggest.scss'
const defaultTheme = {
container: 'bpk-autosuggest__container',
containerOpen: 'bpk-autosuggest__container--open',
input: 'bpk-autosuggest__input',
suggestionsConta... | import React from 'react'
import Autosuggest from 'react-autosuggest'
import style from './bpk-autosuggest.scss'
const defaultTheme = {
container: 'bpk-autosuggest__container',
containerOpen: 'bpk-autosuggest__container--open',
input: 'bpk-autosuggest__input',
suggestionsConta... |
Fix Markdown integration tests due to server changes | package org.sagebionetworks.markdown;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.t... | package org.sagebionetworks.markdown;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJ... |
Add back empty line removed previously by zuuperman while committing debug statements | <?php
/**
* @file
*/
namespace CultuurNet\UDB3\EventHandling;
use Broadway\Domain\DomainMessage;
trait DelegateEventHandlingToSpecificMethodTrait
{
/**
* {@inheritDoc}
*/
public function handle(DomainMessage $domainMessage)
{
$event = $domainMessage->getPayload();
$method = $... | <?php
/**
* @file
*/
namespace CultuurNet\UDB3\EventHandling;
use Broadway\Domain\DomainMessage;
trait DelegateEventHandlingToSpecificMethodTrait
{
/**
* {@inheritDoc}
*/
public function handle(DomainMessage $domainMessage)
{
$event = $domainMessage->getPayload();
$method = $... |
Use normal without extra libs | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Generate hastag from a webpage</title>
<link rel="styl... | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Generate hastag from a webpage</title>
<link rel="styl... |
Simplify pubtator test to only check for entities, not exact number |
import kindred
def test_pubtator_pmid():
corpus = kindred.pubtator.load(19894120)
assert isinstance(corpus,kindred.Corpus)
docCount = len(corpus.documents)
entityCount = sum([ len(d.entities) for d in corpus.documents ])
relationCount = sum([ len(d.relations) for d in corpus.documents ])
assert docCount == ... |
import kindred
def test_pubtator_pmid():
corpus = kindred.pubtator.load(19894120)
assert isinstance(corpus,kindred.Corpus)
docCount = len(corpus.documents)
entityCount = sum([ len(d.entities) for d in corpus.documents ])
relationCount = sum([ len(d.relations) for d in corpus.documents ])
assert docCount == ... |
SEC-1996: Fix javadoc to work with jdk 1.5
The javadoc did not work with JDK 1.5 due to a JDK bug fixed in JDK 1.6.
This changed the javadoc that had a tag that started with <a and was not
closed to escape the < >. This resolves the issue with the JDK 1.5 javadoc
bug. | package org.springframework.security.config;
/**
* Contains globally used default Bean IDs for beans created by the namespace support in Spring Security 2.
* <p>
* These are intended for internal use.
*
* @author Ben Alex
* @author Luke Taylor
*/
public abstract class BeanIds {
private static final String P... | package org.springframework.security.config;
/**
* Contains globally used default Bean IDs for beans created by the namespace support in Spring Security 2.
* <p>
* These are intended for internal use.
*
* @author Ben Alex
* @author Luke Taylor
*/
public abstract class BeanIds {
private static final String P... |
Add logger for uncatched exceptions | package eu.europa.esig.dss.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.... | package eu.europa.esig.dss.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.ann... |
Fix error when creating categories
Resolves #267 | import React from 'react';
import emoji from '../../../common/services/js-emoji';
export default function CategoryListItem(props) {
const {
category, isOnline, onClickDelete,
onClickEdit
} = props;
const deleteIsDisabled = !isOnline;
const categoryEmojiHtml = {
__html: ''
};
if (category.emo... | import React from 'react';
import emoji from '../../../common/services/js-emoji';
export default function CategoryListItem(props) {
const {
category, isOnline, onClickDelete,
onClickEdit
} = props;
const deleteIsDisabled = !isOnline;
const categoryEmojiHtml = {
__html: emoji.replace_colons(catego... |
Move inf to shortest_path_d for clarity | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from ds_binary_heap_tuple import BinaryHeap
def dijkstra(weighted_graph_d, start_vertex):
shortest_path_d = {
vertex: float('inf') for vertex in weighted_graph_d
}
shortest_path_d[start_ver... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from ds_binary_heap_tuple import BinaryHeap
def dijkstra(weighted_graph_d, start_vertex):
inf = float('inf')
shortest_path_d = {
vertex: inf for vertex in weighted_graph_d
}
shortest_p... |
Add an actual message for a missing lethe-data.json | var fs = require('fs');
var exports = {
saved: {
videos: {},
},
};
var FILENAME = 'lethe-data.json';
exports.read = function() {
try {
fs.readFile(FILENAME, 'utf8', (err, data) => {
if (err) {
if (err.message.indexOf('ENOENT') > -1) {
// File doesn't exist
console.log(... | var fs = require('fs');
var exports = {
saved: {
videos: {},
},
};
var FILENAME = 'lethe-data.json';
exports.read = function() {
try {
fs.readFile(FILENAME, 'utf8', (err, data) => {
if (err) {
// Probably the file just doesn't exist, so don't do anything else
console.log(err);
... |
Correct translation of the description. | module.exports = {
title: 'Animación',
subtitle: '',
description: `
Para hacer animaciones con glamorous, puedes usar las transiciones regulares de CSS para cosas sencillas,
y para cosas más avanzadas, puedes usar ~keyframes~ a través de la API ~css.keyframes~ de ~glamor~.
~~~js
// importamos css... | module.exports = {
title: 'Animación',
subtitle: '',
description: `
Para hacer animaciones con glamorous, puedes usar las transiciones regulares de CSS para cosas sencillas,
y para cosas más avanzadas, puedes usar ~keyframes~ vía ~glamor~'s ~css.keyframes~
API.
~~~js
// importamos css desde g... |
Make sure not to scale null values | function halfBandwidth(scale: Function): number {
if(scale.bandwidth) {
return scale.bandwidth() / 2;
}
return 0;
}
/**
* applyScaledValue
*
* Because primitive dimensions correlate to an onScreen pixel value the need
* a slightly different calculation when applying the scale. This is abstract... | function halfBandwidth(scale: Function): number {
if(scale.bandwidth) {
return scale.bandwidth() / 2;
}
return 0;
}
/**
* applyScaledValue
*
* Because primitive dimensions correlate to an onScreen pixel value the need
* a slightly different calculation when applying the scale. This is abstract... |
Make tests pass in Django 1.4. | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND'... | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND'... |
Fix case typo in 'to_dataframe' abstract method return type.
Also updates abstract property to abstract method.
PiperOrigin-RevId: 339248589 | # Copyright 2020 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2020 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
Use improved animation code as it was used inline | var updateClock = (function() {
var sDial = document.getElementById("secondDial");
var mDial = document.getElementById("minuteDial");
var hDial = document.getElementById("hourDial");
function moveDials(hours, minutes, seconds) {
hDeg = (360 / 12) * (hours + minutes/60);
mDeg = (360 / 60) * minutes;
... | var clock = function() {
var sDial = document.getElementsByClassName("seconds")[0];
var mDial = document.getElementsByClassName("minutes")[0];
var hDial = document.getElementsByClassName("hours")[0];
function moveDials(hours, minutes, seconds) {
hDeg = (360 / 12) * hours;
mDeg = (360 / 60) * minutes;
... |
Kickass: Remove ? from show title when searching | import cache
import network
import scraper
import urllib
KICKASS_URL = 'http://kickass.so'
################################################################################
def movie(movie_info):
return __search('category:{0} imdb:{1}'.format('movies', movie_info['imdb_id'][2:]))
#################################... | import cache
import network
import scraper
import urllib
KICKASS_URL = 'http://kickass.so'
################################################################################
def movie(movie_info):
return __search('category:{0} imdb:{1}'.format('movies', movie_info['imdb_id'][2:]))
#################################... |
Revert "remove unnecessary ./ from relative url"
This reverts commit dbd8e6a59f41cc761446f2580fa82c055b17033e. | /**
* Copyright 2020 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/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | /**
* Copyright 2020 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/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... |
[Optimization] Use lazyLoadChunks API to load small chunks at a time | /*!
* Copyright 2016 Joji Doi
* Licensed under the MIT license
*/
function getMediaFilePath(mediaItem) {
return "ext-content/" + mediaItem.dir + '/' + mediaItem.title +
mediaItem.file_ext;
}
function getMediaThumbFilePath(mediaItem) {
return "ext-content/" + mediaItem.dir + '/thumbs/' + mediaItem.title +
... | /*!
* Copyright 2016 Joji Doi
* Licensed under the MIT license
*/
function getMediaFilePath(mediaItem) {
return "ext-content/" + mediaItem.dir + '/' + mediaItem.title +
mediaItem.file_ext;
}
function getMediaThumbFilePath(mediaItem) {
return "ext-content/" + mediaItem.dir + '/thumbs/' + mediaItem.title +
... |
Send context for on event listeners | console.log('background.js');
config.background = true;
/**
* Create an app with the config and accounts
*/
app = new App({
model: config,
collection: accounts,
});
/**
* Wire events
*/
config.on('ready', app.ready, app);
accounts.on('ready', app.ready, app);
config.on('change:frequency', app.changeInterval... | console.log('background.js');
config.background = true;
/**
* Create an app with the config and accounts
*/
app = new App({
model: config,
collection: accounts,
});
/**
* Wire events
*/
config.on('ready', app.ready);
accounts.on('ready', app.ready);
config.on('change:frequency', app.changeInterval);
app.on(... |
Correct and simplify calculation of miliseconds
Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com> | import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.... | import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.... |
Move the `/* @var` syntax above | <?php
namespace SimpleBus\DoctrineORMBridge\MessageBus;
use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware;
use Throwable;
class WrapsMessageHandlingInTransaction implements MessageBusMiddleware
{
/**
* @var ManagerRegistry
... | <?php
namespace SimpleBus\DoctrineORMBridge\MessageBus;
use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware;
use Throwable;
class WrapsMessageHandlingInTransaction implements MessageBusMiddleware
{
/**
* @var ManagerRegistry
... |
Fix UUID column error in membership seeder | module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Memberships',
[
{
id: '047fbd50-2d5a-4800-86f0-05583673fd7f',
memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5',
groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440',
userRole:... | module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Memberships',
[
{
id: new Sequelize.UUIDV1(),
memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5',
groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440',
userRole: 'admin',
... |
Use destructuring assignment to improve readability | const dataviews = require('./');
module.exports = class DataviewFactory {
static get dataviews() {
return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => {
allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName];
return allDataviews;
}... | const dataviews = require('./');
module.exports = class DataviewFactory {
static get dataviews() {
return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => {
allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName];
return allDataviews;
}... |
Add some more spice to those lovely messages | window.lovelyTabMessage = (function(){
var stringTree = {
comeBackIMissYou: {
de: 'Komm zurück, ich vermisse dich.',
en: 'Come back, i miss you.'
}
}
// Let's see what lovely options we have to build our very romantic string
var lovelyOptions = Object.keys(stringT... | window.lovelyTabMessage = (function(){
var hearts = ['❤','💓','💖','💗','💘','💝','💕'];
var heart = hearts[Math.floor(Math.random() * (hearts.length))];
var lang = (window && window.navigator && window.navigator.language || 'en');
switch(lang){
case 'en':
return 'Come back, i miss y... |
Make test fails for CI | var _ = require('lodash');
var gulp = require('gulp');
var gulp_mocha = require('gulp-mocha');
var gulp_jshint = require('gulp-jshint');
var gulp_jsdoc = require("gulp-jsdoc");
var files = ['lib/**/*.js'];
var tests = ['test/**/*.spec.js'];
var alljs = files.concat(tests);
var readme = 'README.md';
function ignoreE... | var _ = require('lodash');
var gulp = require('gulp');
var gulp_mocha = require('gulp-mocha');
var gulp_jshint = require('gulp-jshint');
var gulp_jsdoc = require("gulp-jsdoc");
var files = ['lib/**/*.js'];
var tests = ['test/**/*.spec.js'];
var alljs = files.concat(tests);
var readme = 'README.md';
function ignoreE... |
Move all PPL* records to locality
Looking at localadmins vs localities, this is the right choice. | var through2 = require('through2');
function featureCodeToLayer(featureCode) {
switch (featureCode) {
case 'PCLI':
return 'country';
case 'ADM1':
return 'region';
case 'ADM2':
return 'county';
case 'ADMD':
return 'localadmin';
case 'PPL':
ca... | var through2 = require('through2');
function featureCodeToLayer(featureCode) {
switch (featureCode) {
case 'PCLI':
return 'country';
case 'ADM1':
return 'region';
case 'ADM2':
return 'county';
case 'ADMD':
case 'PPLA':
case 'PPLA2':
case 'PPLA3'... |
Change database interface to return List<>. | package eic.beike.projectx.network.projectXServer;
import eic.beike.projectx.util.ScoreEntry;
import java.util.List;
/**
* Used to interact with the database, these are long running network operations and should not be called
* from the UI thread.
*
* @Author alex
*/
public interface IDatabase {
/**
*... | package eic.beike.projectx.network.projectXServer;
import eic.beike.projectx.util.ScoreEntry;
/**
* Used to interact with the database, these are long running network operations and should not be called
* from the UI thread.
*
* Created by alex on 10/1/15.
*/
public interface IDatabase {
/**
* Register... |
Fix base url for public generation | from base64 import urlsafe_b64encode
from datetime import timedelta
from marshmallow import Schema, fields, post_load
from zeus.models import Hook
from zeus.utils import timezone
class HookSchema(Schema):
id = fields.UUID(dump_only=True)
provider = fields.Str()
token = fields.Method('get_token', dump_onl... | from base64 import urlsafe_b64encode
from datetime import timedelta
from marshmallow import Schema, fields, post_load
from zeus.models import Hook
from zeus.utils import timezone
class HookSchema(Schema):
id = fields.UUID(dump_only=True)
provider = fields.Str()
token = fields.Method('get_token', dump_onl... |
feat(middleware): Add state name and action name to the middleware object | /**
* Created by thram on 16/01/17.
*/
import {getState, setState, resetState} from "./store";
let dicts = {}, middlewares = [];
export const register = (key, dict) => dicts[key] = dict;
export const addMiddleware = (middleware) => middlewares.push(middleware);
export const dispatch = (keyType, data) => {
cons... | /**
* Created by thram on 16/01/17.
*/
import {getState, setState, resetState} from "./store";
let dicts = {}, middlewares = [];
export const register = (key, dict) => dicts[key] = dict;
export const addMiddleware = (middleware) => middlewares.push(middleware);
export const dispatch = (keyType, data) => {
cons... |
Normalize already returns encoded value. | import unicodedata
import urllib
def normalize(name):
if not isinstance(name, unicode):
name = name.decode('utf-8')
return unicodedata.normalize('NFKC', name.replace("'", '')).encode('utf-8')
def quote(name):
if isinstance(name, unicode):
name = normalize(name)
return urllib.quote(... | import unicodedata
import urllib
def normalize(name):
if not isinstance(name, unicode):
name = name.decode('utf-8')
return unicodedata.normalize('NFKC', name.replace("'", '')).encode('utf-8')
def quote(name):
if isinstance(name, unicode):
name = normalize(name).encode('utf8')
retur... |
Fix name field for empty values | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
class BaseUser(AbstractUser):
slug = models.SlugField(_('slug'), max_length=255)
name = models.CharField(_('name'), max_le... | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
class BaseUser(AbstractUser):
slug = models.SlugField(_('slug'), max_length=255)
name = models.CharField(_('name'), max_le... |
Change name of output file in example
--HG--
extra : convert_revision : svn%3A3ed01bd8-26fb-0310-9e4c-ca1a4053419f/networkx/trunk%401549 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example using the NetworkX ego_graph() function to return the main egonet of
the largest hub in a Barabási-Albert network.
"""
__author__="""Drew Conway (drew.conway@nyu.edu)"""
from operator import itemgetter
import networkx as nx
import matplotlib.pyplot as plt
if... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example using the NetworkX ego_graph() function to return the main egonet of
the largest hub in a Barabási-Albert network.
"""
__author__="""Drew Conway (drew.conway@nyu.edu)"""
from operator import itemgetter
import networkx as nx
import matplotlib.pyplot as plt
if... |
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems |
# Enables detailed tracebacks and an interactive Python console on errors.
# Never use in production!
#DEBUG = True
# Makes the server more performant at sending static files when the
# server is being proxied by a server that supports X-Sendfile.
#USE_X_SENDFILE = True
# Address to listen for clients on
HOST = "0.0... |
# Enables detailed tracebacks and an interactive Python console on errors.
# Never use in production!
#DEBUG = True
# Makes the server more performant at sending static files when the
# server is being proxied by a server that supports X-Sendfile.
#USE_X_SENDFILE = True
# Address to listen for clients on
HOST = "0.0... |
Include redux devtools through compose | import React from 'react'
import ReactDOM from 'react-dom'
import getRoutes from './config/routes'
import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import users from 'redux/modules/users'
import thunk from 'redux-thunk'
import { checkIfAuthed } from 'helpers/auth'
co... | import React from 'react'
import ReactDOM from 'react-dom'
import getRoutes from './config/routes'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import users from 'redux/modules/users'
import thunk from 'redux-thunk'
import { checkIfAuthed } from 'helpers/auth'
const store... |
Add common in import statement | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Nicolas Bessi (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Nicolas Bessi (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who ... |
Solve 'invalid target element' error | import React from 'react';
import ClipboardJS from 'clipboard';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.btnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
componentDidMoun... | import React from 'react';
import ClipboardJS from 'clipboard';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.btnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
componentDidMoun... |
Move python rl history file
just to help clean up ~/ | # pylint: disable=unused-import, unused-variable, missing-docstring
def _readline():
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], 'p... | # pylint: disable=unused-import, unused-variable, missing-docstring
def _readline():
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], '.... |
Use icosahedron instead of sphere for less faces | /* globals AFRAME THREE */
AFRAME.registerBrush('single-sphere',
{
init: function (color, width) {
this.material = new THREE.MeshStandardMaterial({
color: this.data.color,
roughness: 0.6,
metalness: 0.2,
side: THREE.FrontSide,
shading: THREE.SmoothShading
});
... | /* globals AFRAME THREE */
AFRAME.registerBrush('single-sphere',
{
init: function (color, width) {
this.material = new THREE.MeshStandardMaterial({
color: this.data.color,
roughness: 0.6,
metalness: 0.2,
side: THREE.FrontSide,
shading: THREE.SmoothShading
});
... |
Fix persistence in private tabs | import localForage from 'localforage';
import { withClientState } from 'apollo-link-state';
import { DialerInfo } from './queries';
import { CONFERENCE_PHONE_NUMBER } from '../config';
// TODO refactor after https://github.com/apollographql/apollo-link-state/issues/119 is resolved
let persistedPhoneNumber;
(async () =... | import localForage from 'localforage';
import { withClientState } from 'apollo-link-state';
import { DialerInfo } from './queries';
import { CONFERENCE_PHONE_NUMBER } from '../config';
let defaultPhoneNumber;
(async () => {
defaultPhoneNumber =
(await localForage.getItem('dialer/CONFERENCE_PHONE_NUMBER')) || CON... |
Fix issue when API wasn't returning correct service dialog results | (function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'marketplace.details': {
url: '/:serviceTemplateId',
templateUrl: 'app/sta... | (function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'marketplace.details': {
url: '/:serviceTemplateId',
templateUrl: 'app/sta... |
Add a test for a date missing from English historical calendars. | import unittest
from datetime import date
import qual
class TestProlepticGregorianCalendar(unittest.TestCase):
def setUp(self):
self.calendar = qual.ProlepticGregorianCalendar()
def check_valid_date(self, year, month, day):
d = self.calendar.date(year, month, day)
self.assertIsNotNon... | import unittest
from datetime import date
import qual
class TestProlepticGregorianCalendar(unittest.TestCase):
def setUp(self):
self.calendar = qual.ProlepticGregorianCalendar()
def check_valid_date(self, year, month, day):
d = self.calendar.date(year, month, day)
self.assertIsNotNon... |
Add support for BS4 menu items | import cx from 'classnames';
import {noop} from 'lodash';
import React from 'react';
import menuItemContainer from './containers/menuItemContainer';
class BaseMenuItem extends React.Component {
displayName = 'BaseMenuItem';
constructor(props) {
super(props);
this._handleClick = this._handleClick.bind(th... | import cx from 'classnames';
import {noop} from 'lodash';
import React from 'react';
import menuItemContainer from './containers/menuItemContainer';
class BaseMenuItem extends React.Component {
displayName = 'BaseMenuItem';
constructor(props) {
super(props);
this._handleClick = this._handleClick.bind(th... |
Fix typo when renaming ingestor -> ingester | #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'... | #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'... |
Change on account id for enablestudents | EnableStudentController.$inject = ['$rootScope', 'toaster', 'TbUtils', '$state', 'students'];
function EnableStudentController ($rootScope, toaster, TbUtils, $state, students) {
const vm = this;
vm.email = "";
vm.accountId = "";
vm.password = "";
vm.submitting = false;
vm.enableStudent = EnableStudent;
... | EnableStudentController.$inject = ['$rootScope', 'toaster', 'TbUtils', '$state', 'students'];
function EnableStudentController ($rootScope, toaster, TbUtils, $state, students) {
const vm = this;
vm.email = "";
vm.accountId = "";
vm.password = "";
vm.enableStudent = EnableStudent;
function EnableStudent()... |
Fix unit test of voice function | import unittest
from tests import PluginTest
from plugins import voice
from CmdInterpreter import JarvisAPI
from Jarvis import Jarvis
# this test class contains test cases for the plugins "gtts" and "disable_gtts"
# which are included in the "voice.py" file in the "plugins" folder
class VoiceTest(PluginTest):
# ... | import unittest
from tests import PluginTest
from plugins import voice
from CmdInterpreter import JarvisAPI
from Jarvis import Jarvis
# this test class contains test cases for the plugins "gtts" and "disable_gtts"
# which are included in the "voice.py" file in the "plugins" folder
class VoiceTest(PluginTest):
# ... |
Order qualifier corresponding to Java conventions. | package nerd.tuxmobil.fahrplan.congress.navigation;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
public class RoomForC3NavConverter {
private static final Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, Str... | package nerd.tuxmobil.fahrplan.congress.navigation;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
public class RoomForC3NavConverter {
private final static Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, Str... |
Add logic to show elapsed time in windows | package battery
import (
"math"
"syscall"
"unsafe"
)
var (
modkernel32 = syscall.NewLazyDLL("kernel32")
procGetSystemPowerStatus = modkernel32.NewProc("GetSystemPowerStatus")
)
type SYSTEM_POWER_STATUS struct {
ACLineStatus byte
BatteryFlag byte
BatteryLifePercent byte
Reserved1... | package battery
import (
"syscall"
"unsafe"
)
var (
modkernel32 = syscall.NewLazyDLL("kernel32")
procGetSystemPowerStatus = modkernel32.NewProc("GetSystemPowerStatus")
)
type SYSTEM_POWER_STATUS struct {
ACLineStatus byte
BatteryFlag byte
BatteryLifePercent byte
Reserved1 ... |
Improve choose_nodes method (set problem) | #!/usr/bin/env python
from utils import read_input
from constants import EURISTIC_FACTOR
from collections import Counter
import sys
def choose_nodes(nodes, neighbours_iterable):
neighbours_count = len(neighbours_iterable)
unpacked_list = []
for t in neighbours_iterable:
unpacked_list += t[1:]
... | #!/usr/bin/env python
from utils import read_input
from constants import EURISTIC_FACTOR
from collections import Counter
import sys
def choose_nodes(nodes, neighbours_iterable):
neighbours_count = len(neighbours_iterable)
unpacked_list = []
for t in neighbours_iterable:
unpacked_list += t[1:]
... |
Refactor internals to store date in a Map instead of Object | class FakeStorage {
#data = new Map();
get length() {
return this.#data.size;
}
key(n) {
n = Number.parseInt(n, 10);
const iterator = this.#data.keys();
let i = 0;
let result = iterator.next();
while (!result.done) {
if (i === n) {
return result.value;
}
i += ... | class FakeStorage {
#data = {};
get length() {
return Object.keys(this.#data).length;
}
key(n) {
return Object.keys(this.#data)[Number.parseInt(n, 10)] ?? null;
}
getItem(key) {
const _data = this.#data;
const _key = `${key}`;
return _data.hasOwnProperty(_key) ? _data[_key] : null;
... |
Change for L.Class and add zombie function | var TC = require('tangram.cartodb');
var LeafletLayerView = require('./leaflet-layer-view');
var L = require('leaflet');
var LeafletCartoDBVectorLayerGroupView = L.Class.extend({
includes: [
LeafletLayerView.prototype
],
options: {
minZoom: 0,
maxZoom: 28,
tileSize: 256,
zoomOffset: 0,
t... | var TC = require('tangram.cartodb');
var LeafletLayerView = require('./leaflet-layer-view');
var L = require('leaflet');
var LeafletCartoDBVectorLayerGroupView = L.Layer.extend({
includes: [
LeafletLayerView.prototype
],
options: {
minZoom: 0,
maxZoom: 28,
tileSize: 256,
zoomOffset: 0,
t... |
Add pull to load remote chagnes in before | <?php namespace Kironuniversity\Git\Controllers;
use BackendMenu;
use Backend\Classes\Controller;
use GitWrapper\GitWrapper;
use Flash;
/**
* Deploy Back-end Controller
*/
class Deploy extends Controller
{
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Kiron... | <?php namespace Kironuniversity\Git\Controllers;
use BackendMenu;
use Backend\Classes\Controller;
use GitWrapper\GitWrapper;
use Flash;
/**
* Deploy Back-end Controller
*/
class Deploy extends Controller
{
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Kiron... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.