text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add a comment for New. | package gtf
import (
"html/template"
"strings"
)
var GtfFuncMap = template.FuncMap {
"stringReplace": func(s1 string, s2 string) string {
return strings.Replace(s2, s1, "", -1)
},
"stringDefault": func(s1 string, s2 string) string {
if len(s2) > 0 {
return s2
}
return s1
},
"stringLength": func(s... | package gtf
import (
"html/template"
"strings"
)
var GtfFuncMap = template.FuncMap {
"stringReplace": func(s1 string, s2 string) string {
return strings.Replace(s2, s1, "", -1)
},
"stringDefault": func(s1 string, s2 string) string {
if len(s2) > 0 {
return s2
}
return s1
},
"stringLength": func(s... |
Fix JSLint error, use camelCase for functions | Gratipay.giving = {}
Gratipay.giving.init = function() {
Gratipay.giving.activateTab('active');
$('.giving #tab-nav a').on('click', Gratipay.giving.handleClick);
}
Gratipay.giving.handleClick = function(e) {
e.preventDefault();
var $target = $(e.target);
Gratipay.giving.activateTab($target.data('t... | Gratipay.giving = {}
Gratipay.giving.init = function() {
Gratipay.giving.activate_tab('active');
$('.giving #tab-nav a').on('click', Gratipay.giving.handle_click);
}
Gratipay.giving.handle_click = function(e) {
e.preventDefault();
var $target = $(e.target);
Gratipay.giving.activate_tab($target.dat... |
Fix node_modules paths on Windows
This change moves 'prefix' test to happen after the absolute path is
resolved. Without it, the prefix tests never actually fire when starting
with a relative path, and the resulting dirs all end up looking like
[ '/C:..', '/C:...' ] instead of [ 'C:...', 'C:...' ] | var path = require('path');
module.exports = function (start, opts) {
var modules = opts.moduleDirectory
? [].concat(opts.moduleDirectory)
: ['node_modules']
;
// ensure that `start` is an absolute path at this point,
// resolving against the process' current working directory
star... | var path = require('path');
module.exports = function (start, opts) {
var modules = opts.moduleDirectory
? [].concat(opts.moduleDirectory)
: ['node_modules']
;
var prefix = '/';
if (/^([A-Za-z]:)/.test(start)) {
prefix = '';
} else if (/^\\\\/.test(start)) {
prefix =... |
Fix regex so that it even passes for App.jsx | var babel = require('babel-jest'),
jsPath = /.*\/react\-seed\/src\/js(?:\/[a-z]+)?(?:\/__tests__)?\/[a-zA-Z]+(?:\-test)?\.jsx?$/,
lessPath = /.*\/react\-seed\/src\/less\/[a-z]+\/[a-zA-Z]+\.less$/;
module.exports = {
process: function(src, filename) {
var dummyLessModule = 'module.exports = {dumm... | var babel = require('babel-jest'),
jsPath = /.*\/react\-seed\/src\/js(?:\/[a-z]+)?(?:\/__tests__)?\/[a-zA-Z]+(?:\-test)?\.jsx?$/,
lessPath = /.*\/react\-seed\/src\/less\/[a-z]+\/[a-zA-Z]+\.less$/;
module.exports = {
process: function(src, filename) {
var dummyLessModule = 'module.exports = {dumm... |
Handle mkdir error when directory exists | var ls = require('ls');
var fs = require('fs');
exports.generate = function(dir) {
if(dir === undefined || dir === null) {
dir = __dirname;
}
fs.mkdir(dir, 0777, function(err) {
if(err && err.code != 'EEXIST') {
return console.error(err);
}
var decks = ls(__dirnam... | var ls = require('ls');
var fs = require('fs');
exports.generate = function(dir) {
if(dir === undefined || dir === null) {
dir = __dirname;
}
fs.mkdir(dir);
var decks = ls(__dirname + "/decks/*.js");
for(var i = 0, len = decks.length; i < len; i++) {
var json = require(decks[i].full)... |
Increase repo size to 20Mb | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/iv... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/iv... |
Update Postgres test connection string | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_en... | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_en... |
Remove other landing pages service | (function () {
'use strict';
angular
.module('fusionSeedApp.services.landingPage', [])
.factory('LandingPageService', LandingPageService);
function LandingPageService($log, Orwell, $window, ConfigService) {
'ngInject';
activate();
var service = {
getLandingPagesFromData: getLandingPa... | (function () {
'use strict';
angular
.module('fusionSeedApp.services.landingPage', [])
.factory('LandingPageService', LandingPageService);
function LandingPageService($log, Orwell, $window, ConfigService) {
'ngInject';
activate();
var service = {
getLandingPagesFromData: getLandingPa... |
Remove unneeded switchOff function from forgot view | /*
* Module dependencies.
*/
var template = require('./forgot-form');
var t = require('t');
var FormView = require('form-view');
var page = require('page');
/**
* Expose ForgotView.
*/
module.exports = ForgotView;
/**
* Forgot password view
*
* @return {ForgotView} `ForgotView` instance.
* @api public
*/
... | /*
* Module dependencies.
*/
var template = require('./forgot-form');
var t = require('t');
var FormView = require('form-view');
var page = require('page');
/**
* Expose ForgotView.
*/
module.exports = ForgotView;
/**
* Forgot password view
*
* @return {ForgotView} `ForgotView` instance.
* @api public
*/
... |
Increment version number for release | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
... | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
... |
Use Ember.set instead of model.set | import Ember from 'ember';
export default function loadAll(model, relationship, dest, options = {}) {
var page = options.page || 1;
var query = {
'page[size]': 10,
page: page
};
query = Ember.merge(query, options || {});
Ember.set(model, 'query-params', query);
return model.que... | import Ember from 'ember';
export default function loadAll(model, relationship, dest, options = {}) {
var page = options.page || 1;
var query = {
'page[size]': 10,
page: page
};
query = Ember.merge(query, options || {});
model.set('query-params', query);
return model.query(rela... |
Apply oneworld-fix patch before testing connectivity
Summary:
Making the runner apply the necessary oneworld fix patch before running the tests.
This can't be a long term solution, but at least means not getting that breaking change landed doesn't stop our tests from running.
Since that change is only necessary for ... | /**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import Server from '../server.js';
import LogManager from '../fb-stubs/Logger';
import reducers from '../reducers/index.js';
import config... | /**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import Server from '../server.js';
import LogManager from '../fb-stubs/Logger';
import reducers from '../reducers/index.js';
import config... |
Fix test case being unable to fail | import threading
import time
DEFAULT_SLEEP = 0.01
class CustomError(Exception):
pass
def defer(callback, *args, **kwargs):
sleep = kwargs.pop('sleep', DEFAULT_SLEEP)
expected_return = kwargs.pop('expected_return', None)
call = kwargs.pop('call', True)
def func():
time.sleep(sleep)
... | import threading
import time
DEFAULT_SLEEP = 0.01
class CustomError(Exception):
pass
def defer(callback, *args, **kwargs):
sleep = kwargs.pop('sleep', DEFAULT_SLEEP)
expected_return = kwargs.pop('expected_return', None)
call = kwargs.pop('call', True)
def func():
time.sleep(sleep)
... |
Add index.json to content fetch path to be able to omit url rewriting | import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { init } from './redux/page';
import Page from './components/Page';
class FrontendApp extends Component {
componentWillMount() {
const path = window.location.pathname;
const options = { mode: 'no-cors' };
f... | import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { init } from './redux/page';
import Page from './components/Page';
class FrontendApp extends Component {
componentWillMount() {
const path = window.location.pathname;
const options = { mode: 'no-cors' };
f... |
Fix content type bug (415 error from server).
- The server doesn't recognize the POST as type application/json, but adding an empty JSON object {} solves that. | 'use strict';
angular.module('confRegistrationWebApp')
.factory('currentRegistrationInterceptor', function ($q, $injector) {
return {
'responseError': function (rejection) {
var regExp = /conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/;
if (rejection.status === 404 && regExp.test(re... | 'use strict';
angular.module('confRegistrationWebApp')
.factory('currentRegistrationInterceptor', function ($q, $injector) {
return {
'responseError': function (rejection) {
var regExp = /conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/;
if (rejection.status === 404 && regExp.test(re... |
Remove superfluous class from importer | import os
import imp
modules = {}
def load_modules(path="./modules/"): # Consider adding recursive sorting at some point in the future
names = os.listdir(path)
for name in names:
if not name.endswith(".py"): continue
print("Importing module {0}".format(name))
name = name.split('.')[0]
... | import os
class loader:
modules = {};
def __init__(self):
self.load_modules();
def load_modules(self, path="./modules/"): # Consider adding recursive sorting at some point in the future
names = os.listdir(path);
pwd = os.getcwd();
os.chdir(path);
for name in names:... |
Reduce the displayed channels to top 12 | import axios from 'axios';
// get top twitch channels
export const GET_CHANNELS = 'GET_CHANNELS';
export function getChannels() {
const request = axios.get('https://api.twitch.tv/kraken/streams?api_version=3&limit=12');
return {
type: GET_CHANNELS,
payload: request,
};
}
// set the currently active chan... | import axios from 'axios';
// get top twitch channels
export const GET_CHANNELS = 'GET_CHANNELS';
export function getChannels() {
const request = axios.get('https://api.twitch.tv/kraken/streams?api_version=3&limit=25');
return {
type: GET_CHANNELS,
payload: request,
};
}
// set the currently active chan... |
Make sure method call return type is passed by ref | <?php
namespace Psalm\Plugin\Hook;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use Psalm\Codebase;
use Psalm\Context;
use Psalm\FileManipulation;
use Psalm\StatementsSource;
use Psalm\Type\Union;
interface AfterMethodCallAnalysisInterface
{
/**
* @param M... | <?php
namespace Psalm\Plugin\Hook;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use Psalm\Codebase;
use Psalm\Context;
use Psalm\FileManipulation;
use Psalm\StatementsSource;
use Psalm\Type\Union;
interface AfterMethodCallAnalysisInterface
{
/**
* @param M... |
Fix theme colors & drawable on Android 8 Oreo | package org.mtransit.android.commons;
import org.mtransit.android.commons.api.SupportFactory;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
public final class ThemeUtils {
public static int resolveColorAttribute(Con... | package org.mtransit.android.commons;
import org.mtransit.android.commons.api.SupportFactory;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
public final class ThemeUtils {
public static int resolveColorAttribute(Con... |
Use correct vue library for SSR | var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
baseWebpackConfig.plugins = []
delete baseWebpackConfig.resolve.alias['vue$']
var webpackConfig = merge(baseWebpackConfig, {
entry: '.... | var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
baseWebpackConfig.plugins = []
var webpackConfig = merge(baseWebpackConfig, {
entry: './webpack/server.js',
module: {
loaders: u... |
Make use of MarkdownLanguageConfig constants | package flow.netbeans.markdown.highlighter;
import flow.netbeans.markdown.csl.MarkdownLanguageConfig;
import java.util.Collection;
import java.util.EnumSet;
import org.netbeans.spi.lexer.LanguageHierarchy;
import org.netbeans.spi.lexer.Lexer;
import org.netbeans.spi.lexer.LexerRestartInfo;
public class Markd... | package flow.netbeans.markdown.highlighter;
import java.util.Collection;
import java.util.EnumSet;
import org.netbeans.spi.lexer.LanguageHierarchy;
import org.netbeans.spi.lexer.Lexer;
import org.netbeans.spi.lexer.LexerRestartInfo;
public class MarkdownLanguageHierarchy extends LanguageHierarchy<MarkdownToke... |
Tweak padding on summary text | (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var PropTypes = window.shared.PropTypes;
var styles = {
caption: {
marginRight: 5
},
value: {
... | (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var PropTypes = window.shared.PropTypes;
var styles = {
caption: {
marginRight: 5
},
value: {
... |
Add debugging println to show content of spreadsheet on the console. | package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/pilu/traffic"
"github.com/tealeg/xlsx"
)
type ExcelData struct {
DocumentName string
Sheets [][][]string
}
func excelResponse(w traffic.ResponseWriter, r *traffic.Request) {
file, handler, err := r.FormFile("file")
if err != nil { ... | package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/pilu/traffic"
"github.com/tealeg/xlsx"
)
type ExcelData struct {
DocumentName string
Sheets [][][]string
}
func excelResponse(w traffic.ResponseWriter, r *traffic.Request) {
file, handler, err := r.FormFile("file")
if err != nil { ... |
Rename 'URL' to 'link' to match with .link property | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.d... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.d... |
Update id of list element container | (function($) {
$().ready(function() {
var ANIMATION_SPEED = 250;
$('body').addClass('js');
// DMs on the Settings page
$('#user_enable_dms').click(function(event) {
$('#dm-priority-container').slideToggle(ANIMATION_SPEED);
});
if ($('#user_enable_dms:checked').length == 1)
$('#dm-priority-conta... | (function($) {
$().ready(function() {
var ANIMATION_SPEED = 250;
$('body').addClass('js');
// DMs on the Settings page
$('#user_enable_dms').click(function(event) {
$('#dm-priority-container').slideToggle(ANIMATION_SPEED);
});
if ($('#user_enable_dms:checked').length == 1)
$('#dm-priority-conta... |
Fix crash when URL is provided. | import argparse, json, os.path
import jinja2, requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input",
default="swagger.json",
help="path to or URL of the Swagger JSON file (default: swagger.json)",
metavar="SWAGGER_LOCATION"
)
par... | import argparse, json, os.path
import jinja2, requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input",
default="swagger.json",
help="path to or URL of the Swagger JSON file (default: swagger.json)",
metavar="SWAGGER_LOCATION"
)
par... |
Update keyword and asset_url fields to accept arrays.
Resolves #16 | 'use strict';
exports.up = function(knex, Promise) {
return knex.schema.
createTable('paths', function (t) {
t.increments('id');
t.text('curator').notNullable();
t.text('curator_org');
t.specificType('collaborators', 'text[]');
t.text('name').notNullable();
t.text('description... | 'use strict';
exports.up = function(knex, Promise) {
return knex.schema.
createTable('paths', function (t) {
t.increments('id');
t.text('curator').notNullable();
t.text('curator_org');
t.specificType('collaborators', 'text[]');
t.text('name').notNullable();
t.text('description... |
Add missing import and explanation of failure | import numpy as np
import sys
try:
import statsmodels.api as sm
except ImportError:
print "Example requires statsmodels"
sys.exit(0)
from pymc import *
# Generate data
size = 50
true_intercept = 1
true_slope = 2
x = np.linspace(0, 1, size)
y = true_intercept + x*true_slope + np.random.normal(scale=.5, s... | import numpy as np
try:
import statsmodels.api as sm
except ImportError:
sys.exit(0)
from pymc import *
# Generate data
size = 50
true_intercept = 1
true_slope = 2
x = np.linspace(0, 1, size)
y = true_intercept + x*true_slope + np.random.normal(scale=.5, size=size)
# Add outliers
x = np.append(x, [.1, .15,... |
Convert binary string to UTF-8 | from flask import Flask
import consul
import socket
import pprint
import redis
# Consul key
CONSUL_REDIS_KEY = "redis"
app = Flask(__name__)
def GetRedisFromConsul():
MyConsul = consul.Consul(host='172.17.42.1', port=8500)
Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY)
pprint.pprint(C... | from flask import Flask
import consul
import socket
import pprint
import redis
# Consul key
CONSUL_REDIS_KEY = "redis"
app = Flask(__name__)
def GetRedisFromConsul():
MyConsul = consul.Consul(host='172.17.42.1', port=8500)
Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY)
pprint.pprint(C... |
Update the PyPI version to 0.2.19. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.19',
packages=['todoist', 'todoist.managers'],
author='Doist Team... | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.18',
packages=['todoist', 'todoist.managers'],
author='Doist Team... |
Improve comments in vtkjs example | // Fetch the dataset from the server
$.ajax({url: 'capitals.json'}).done(function (capitals) {
// Create a map object with reasonable center and zoom level
var map = geo.map({
node: '#map',
center: {x: 0, y: 0},
zoom: 2.5,
clampBoundsX: false,
clampBoundsY: false,
clampZoom: false,
discr... | $.ajax({url: 'capitals.json'}).done(function (capitals) {
// Create a map object with reasonable center and zoom level
var map = geo.map({
node: '#map',
center: {x: 0, y: 0},
zoom: 2.5,
clampBoundsX: false,
clampBoundsY: false,
clampZoom: false,
discreteZoom: false
});
// Add the til... |
Fix extension to work with latest state changes
Refs flarum/core#2150. | import { extend } from 'flarum/extend';
import LinkButton from 'flarum/components/LinkButton';
import IndexPage from 'flarum/components/IndexPage';
import DiscussionListState from 'flarum/states/DiscussionListState';
export default function addSubscriptionFilter() {
extend(IndexPage.prototype, 'navItems', function(i... | import { extend } from 'flarum/extend';
import LinkButton from 'flarum/components/LinkButton';
import IndexPage from 'flarum/components/IndexPage';
import DiscussionList from 'flarum/components/DiscussionList';
export default function addSubscriptionFilter() {
extend(IndexPage.prototype, 'navItems', function(items) ... |
Add missing cred-alert-worker-ng build test
Signed-off-by: Kalai Wei <920bf42fdcab8ffc364d94066818a17cd391003a@pivotal.io> | package main_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
"testing"
)
func TestBinaries(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Binaries Suite")
}
var _ = AfterSuite(func() {
gexec.CleanupBuildArtifacts()
})
var _ = Describe("Binaries", fu... | package main_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
"testing"
)
func TestBinaries(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Binaries Suite")
}
var _ = AfterSuite(func() {
gexec.CleanupBuildArtifacts()
})
var _ = Describe("Binaries", fu... |
Add example code and tidy up other parts of file | /* Author:
TMW - (Author Name Here)
*/
// Create a closure to maintain scope of the '$' and TMW
;(function (TMW, $) {
$(function() {
// Any globals go here in CAPS (but avoid if possible)
// follow a singleton pattern
// (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavasc... | /* Author:
TMW - (Author Name Here)
*/
// Create a closure to maintain scope of the '$' and TMW
(function (TMW, $) {
$(function() {
// Any globals go here in CAPS (but avoid if possible)
// follow a singleton pattern
// (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascr... |
Mark as compatible for python 2.7, 3.3 and 3.4
Add `classifiers` parameter to `setup` function call in `setup.py` file. | # -*- coding: utf-8 -*-
from distutils.core import setup
readme_file = open('README.rst')
setup(
name='django-db-file-storage',
version='0.3.1',
author='Victor Oliveira da Silva',
author_email='victor_o_silva@hotmail.com',
packages=['db_file_storage'],
url='https://github.com/victor-o-silva/d... | # -*- coding: utf-8 -*-
from distutils.core import setup
readme_file = open('README.rst')
setup(
name='django-db-file-storage',
version='0.3.1',
author='Victor Oliveira da Silva',
author_email='victor_o_silva@hotmail.com',
packages=['db_file_storage'],
url='https://github.com/victor-o-silva/d... |
Refactor to better inject values into path items | import os
import subprocess
import sys
import signal
import itertools
def _build_env(target):
"""
Prepend target and .pth references in target to PYTHONPATH
"""
env = dict(os.environ)
suffix = env.get('PYTHONPATH')
prefix = target,
items = itertools.chain(
prefix,
(suffix,) if suffix else (),
)
joined = ... | import os
import subprocess
import sys
import signal
def _build_env(target):
"""
Prepend target to PYTHONPATH
"""
env = dict(os.environ)
suffix = env.get('PYTHONPATH', '')
prefix = target
joined = os.pathsep.join([prefix, suffix]).rstrip(os.pathsep)
env['PYTHONPATH'] = joined
return env
def with_path(targe... |
Fix page /pipe 's error. | // server.js
/**IMPORT**/
var express = require('express');
var url = require('url');
var inject_piper = require('./inject-piper.js');
/** SET **/
var app = express();
/**FUNCTION**/
function sendViewMiddleware(req, res, next) { //send .html
res.sendHtml = function(html) {
return res.sendFile(__dirname +... | // server.js
/**IMPORT**/
var express = require('express');
var url = require('url');
var inject_pipe = require('./inject-pipe.js');
/** SET **/
var app = express();
/**FUNCTION**/
function sendViewMiddleware(req, res, next) { //send .html
res.sendHtml = function(html) {
return res.sendFile(__dirname + "... |
Adjust logging and fix module documentation | """Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogg... | """Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogge... |
Fix test group for NotFoundException | <?php
namespace Veles\Tests\Routing\Exceptions;
use Veles\Routing\Exceptions\NotFoundException;
/**
* Generated by PHPUnit_SkeletonGenerator on 2015-08-12 at 09:05:52.
* @group route
*/
class NotFoundExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var NotFoundException
*/
protected $ob... | <?php
namespace Veles\Tests\Routing\Exceptions;
use Veles\Routing\Exceptions\NotFoundException;
/**
* Generated by PHPUnit_SkeletonGenerator on 2015-08-12 at 09:05:52.
* @group Dev
*/
class NotFoundExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var NotFoundException
*/
protected $obje... |
Allow repr to show java.lang.Iterables. | function quote(s) {
return "\"" + s.replace(/([\\\"])/, "\\$1") + "\"";
}
function maybe_quote(s) {
if (/[\\\"]/.test(s))
return quote(s);
else
return s;
}
function repr(x, max_depth) {
if (max_depth == undefined)
max_depth = 1;
if (x === null) {
return "null";
} else if (x instanceof java.lang.Iterabl... | function quote(s) {
return "\"" + s.replace(/([\\\"])/, "\\$1") + "\"";
}
function maybe_quote(s) {
if (/[\\\"]/.test(s))
return quote(s);
else
return s;
}
function repr(x, max_depth) {
if (max_depth == undefined)
max_depth = 1;
if (x === null) {
return "null";
} if (typeof x == "object") {
if ("hash... |
Update level checks to allow a verbosity level of 0 or greater | #
# License: MIT (doc/LICENSE)
# Author: Todd Gaunt
from sys import stderr
PROGRAM_NAME = "imgfetch: "
def error(level, msg):
global PROGRAM_NAME
if level < 0:
quit()
if level >= 0:
errmsg=PROGRAM_NAME + "error: " + msg
print(errmsg, file=stderr)
quit()
def warning(level, msg):
... | #
# License: MIT (doc/LICENSE)
# Author: Todd Gaunt
#
# File: imgfetch/fourchan.py
# This file contains the logging functions for writing to stdout stderr etc...
from sys import stderr
PROGRAM_NAME = "imgfetch: "
def error(level, msg):
global PROGRAM_NAME
if level < 0:
errmsg=PROGRAM_NAME + "error: i... |
Remove unused init() add render() method | var ContactModel = require('../model/Contacts');
var ContactView = require('../view/Contact');
var AddContactForm = require('../view/AddContactForm');
/**
* Controller Object to dispatch actions to view/Contact and model/Contacts.
* @constructor
*/
var ContactsController = function() {
};
ContactsController.remove... | var ContactModel = require('../model/Contacts');
var ContactView = require('../view/Contact');
var AddContactForm = require('../view/AddContactForm');
/**
* Controller Object to dispatch actions to view/Contact and model/Contacts.
* @constructor
*/
var ContactsController = function() {
this.init();
};
ContactsCo... |
Fix for touchend event for iOS. | /**
* Flotr Event Adapter
*/
Flotr.EventAdapter = {
observe: function(object, name, callback) {
bean.add(object, name, callback);
return this;
},
fire: function(object, name, args) {
bean.fire(object, name, args);
if (typeof(Prototype) != 'undefined')
Event.fire(object, name, args);
//... | /**
* Flotr Event Adapter
*/
Flotr.EventAdapter = {
observe: function(object, name, callback) {
bean.add(object, name, callback);
return this;
},
fire: function(object, name, args) {
bean.fire(object, name, args);
if (typeof(Prototype) != 'undefined')
Event.fire(object, name, args);
//... |
Update mongoDB address by env. | var express = require('express'),
app = express();
var scores = require('./server/routes/scores');
var users = require('./server/routes/users');
var chats = require('./server/routes/chats');
var rooms = require('./server/routes/rooms');
var paints = require('./server/routes/pictures');
var bodyParser = require('bod... | var express = require('express'),
app = express();
var scores = require('./server/routes/scores');
var users = require('./server/routes/users');
var chats = require('./server/routes/chats');
var rooms = require('./server/routes/rooms');
var paints = require('./server/routes/pictures');
var bodyParser = require('bod... |
Update generator to derive from frost-component | /**
* Component definition for the <%= dasherizedModuleName %> component
*/
import {PropTypes} from 'ember-prop-types'
import computed, {readOnly} from 'ember-computed-decorators'
import {Component} from 'ember-frost-core'
import layout from '<%= templatePath %>'
export default Component.extend({
// == Dependenc... | /**
* Component definition for the <%= dasherizedModuleName %> component
*/
import Ember from 'ember'
const {Component} = Ember
import PropTypesMixin, {PropTypes} from 'ember-prop-types'
import computed, {readOnly} from 'ember-computed-decorators'
import layout from '<%= templatePath %>'
export default Component.e... |
Change buttons on main page | @extends('layouts.app')
@section('content')
@include('includes.sideNav')
<section class="home">
<div class="home--logo">
@include('includes.trio-logo')
</div>
<div>
<p class="center-block text-center home--info">
Trios is a simple exercise to test your English skills.<br>
... | @extends('layouts.app')
@section('content')
@include('includes.sideNav')
<section class="home">
<div class="home--logo">
@include('includes.trio-logo')
</div>
<div>
<p class="center-block text-center home--info">
Trios is a simple exercise to test your English skills.<br>
... |
Enable core text widget now that its usable | <?php
namespace App;
/**
* Unregister all default widgets.
*/
add_action('widgets_init', function () {
$widgets = [
'WP_Widget_Pages',
'WP_Widget_Calendar',
'WP_Widget_Archives',
'WP_Widget_Links',
'WP_Widget_Meta',
// 'WP_Widget_Search',
// 'WP_Widget_Tex... | <?php
namespace App;
/**
* Unregister all default widgets.
*/
add_action('widgets_init', function () {
$widgets = [
'WP_Widget_Pages',
'WP_Widget_Calendar',
'WP_Widget_Archives',
'WP_Widget_Links',
'WP_Widget_Meta',
// 'WP_Widget_Search',
'WP_Widget_Text',... |
Fix data handler name type | const fs = require('fs');
const path = require('path');
module.exports = function(options, fieldname, filename) {
const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/');
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
let tempFilePath = path.join(dir, 'tmp' + Date.now());
let writeSt... | const fs = require('fs');
const path = require('path');
module.exports = function(options, fieldname, filename) {
const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/');
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
let tempFilePath = path.join(dir, 'tmp' + Date.now());
let writeSt... |
Add CustomizeBrowserOptions method to Metric base class
BUG=271177
Review URL: https://chromiumcodereview.appspot.com/22938004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217198 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Metric(object):
"""Base class for all the metrics that are used by telemetry measurements.
The Metric class represents a way of measuring somethin... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Metric(object):
"""Base class for all the metrics that are used by telemetry measurements.
The Metric class represents a way of measuring somethin... |
Remove commonSvc dependency to prevent circular dependency | (function() {
'use strict';
angular.module('Core')
.service('sessionService', sessionService);
sessionService.$inject = [];
function sessionService() {
var service = this;
service.isUserLoggedIn = isUserLoggedIn;
/* ======================================== Va... | (function() {
'use strict';
angular.module('Core')
.service('sessionService', sessionService);
sessionService.$inject = ['commonService'];
function sessionService(commonService) {
var service = this;
service.isUserLoggedIn = isUserLoggedIn;
/* ===============... |
Use unminified for development env | var path = require('path');
module.exports = {
name: 'Ember CLI Data Factory Guy',
blueprintsPath: function() {
return path.join(__dirname, 'blueprints');
},
included: function(app) {
this._super.included(app);
if (app.tests) {
// ember-data must be imported before ember-data-factory-guy.
... | var path = require('path');
module.exports = {
name: 'Ember CLI Data Factory Guy',
blueprintsPath: function() {
return path.join(__dirname, 'blueprints');
},
included: function(app) {
this._super.included(app);
if (app.tests) {
// ember-data must be imported before ember-data-factory-guy.
... |
Fix ctypes call test for windows | import os
import ctypes
from numba import *
@autojit(backend='ast', nopython=True)
def call_ctypes_func(func, value):
return func(value)
def test_ctypes_calls():
# Test puts for no segfault
libc = ctypes.CDLL(ctypes.util.find_library('c'))
puts = libc.puts
puts.argtypes = [ctypes.c_char_p]
c... | import os
import ctypes
from numba import *
@autojit(backend='ast', nopython=True)
def call_ctypes_func(func, value):
return func(value)
def test_ctypes_calls():
libc = ctypes.CDLL(ctypes.util.find_library('c'))
puts = libc.puts
puts.argtypes = [ctypes.c_char_p]
assert call_ctypes_func(puts, "He... |
Create the snippet, then the draft. | import Ember from 'ember';
export default Ember.Route.extend({
actions: {
submit: function () {
var
self = this,
content = this.controller.get('firstSnippet'),
snippet = this.store.createRecord('snippet', {
content: content,
});
snippet.save().then(function ()... | import Ember from 'ember';
export default Ember.Route.extend({
actions: {
submit: function () {
var content = this.controller.get('firstSnippet');
var snippet = this.store.createRecord('snippet', {
content: content,
});
snippet.save().then(function () {
var draft = this.... |
Fix broken test.. was testing the old way of validation of the reconsent command. | package edu.northwestern.bioinformatics.studycalendar.web.schedule;
import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;... | package edu.northwestern.bioinformatics.studycalendar.web.schedule;
import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;... |
Fix param order of assertEquals (expected, actual) in test for Finder\Glob | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Tests;
use Symfony\Component\Finder\Glob;
cla... | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Tests;
use Symfony\Component\Finder\Glob;
cla... |
Make sure to not leave hanging children processes if the parent is killed | # encoding: utf-8
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
import signal
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
d... | # encoding: utf-8
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
def __init__(se... |
Trim even if there's no latest doc | var README_MAXLEN = 64 * 1024
module.exports = readmeTrim
function readmeTrim(doc) {
var changed = false
var readme = doc.readme || ''
var readmeFilename = doc.readmeFilename || ''
if (doc['dist-tags'] && doc['dist-tags'].latest) {
var latest = doc.versions[doc['dist-tags'].latest]
if (latest && lates... | var README_MAXLEN = 64 * 1024
module.exports = readmeTrim
function readmeTrim(doc) {
var changed = false
var readme = doc.readme || ''
var readmeFilename = doc.readmeFilename || ''
if (doc['dist-tags'] && doc['dist-tags'].latest) {
var latest = doc.versions[doc['dist-tags'].latest]
if (latest && lates... |
Set default coordinate to -90, 0(antarctica) since mysql refuses to index coordinates if there exists empty or null value. | <?php
class Db_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function insert_record($record)
{
/*
* convert coordinate string to mysql geospacial fucntion call
*/
$coord_string = $record['coordinates'];
unset($reco... | <?php
class Db_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function insert_record($record)
{
/*
* convert coordinate string to mysql geospacial fucntion call
*/
$coord_string = $record['coordinates'];
unset($reco... |
Remove hack in mdbd fs.host.fqdn driver. | package main
import (
"encoding/json"
"errors"
"github.com/Symantec/Dominator/lib/mdb"
"io"
"log"
)
func loadDsHostFqdn(reader io.Reader, datacentre string, logger *log.Logger) (
*mdb.Mdb, error) {
type machineType struct {
Fqdn string
}
type dataCentreType map[string]machineType
type inMdbType map[stri... | package main
import (
"encoding/json"
"errors"
"github.com/Symantec/Dominator/lib/mdb"
"io"
"log"
)
func loadDsHostFqdn(reader io.Reader, datacentre string, logger *log.Logger) (
*mdb.Mdb, error) {
type machineType struct {
Fqdn string
}
type dataCentreType map[string]machineType
type inMdbType map[stri... |
Add location and expense strings to pastTrip model | // Todo Implement and export schema using mongoose
// Reference angular sprint
var mongoose = require('mongoose');
//var User = require('../users/UserModel.js');
var Schema = mongoose.Schema;
var PastTripSchema = new Schema({
creator: {
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: S... | // Todo Implement and export schema using mongoose
// Reference angular sprint
var mongoose = require('mongoose');
//var User = require('../users/UserModel.js');
var Schema = mongoose.Schema;
var PastTripSchema = new Schema({
creator: {
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: S... |
Add jest module mapper for tests directory | module.exports = {
verbose: true,
bail: true,
collectCoverage: true,
coverageDirectory: 'coverage',
restoreMocks: true,
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stu... | module.exports = {
verbose: true,
bail: true,
collectCoverage: true,
coverageDirectory: 'coverage',
restoreMocks: true,
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stu... |
Remove ominous TESTING_LOGIN config comment | # TODO @Sumukh Better Secret Management System
class TestConfig(object):
DEBUG = True
SECRET_KEY = 'Testing*ok*server*'
RESTFUL_JSON = {'indent': 4}
TESTING_LOGIN = True
class DevConfig(TestConfig):
ENV = 'dev'
DEBUG_TB_INTERCEPT_REDIRECTS = False
SQLALCHEMY_DATABASE_URI = 'postgresql://po... | # TODO @Sumukh Better Secret Management System
class TestConfig(object):
DEBUG = True
SECRET_KEY = 'Testing*ok*server*'
RESTFUL_JSON = {'indent': 4}
TESTING_LOGIN = True # Do NOT turn on for prod
class DevConfig(TestConfig):
ENV = 'dev'
DEBUG_TB_INTERCEPT_REDIRECTS = False
SQLALCHEMY_DATA... |
Remove a debug logging call | function setupBoolPreference(name) {
document.getElementById(name).checked = Preferences[name].value;
document.getElementById(name).addEventListener("change", function(e) {
Preferences[name].value = e.target.checked;
});
}
function setupNumberPreference(name) {
document.getElementById(name).va... | function setupBoolPreference(name) {
document.getElementById(name).checked = Preferences[name].value;
document.getElementById(name).addEventListener("change", function(e) {
Preferences[name].value = e.target.checked;
});
}
function setupNumberPreference(name) {
document.getElementById(name).va... |
Add another test case to increase coverage | package uk.ac.ebi.atlas.bioentity.interpro;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
import static org.hamcrest.MatcherAssert.assertThat;
im... | package uk.ac.ebi.atlas.bioentity.interpro;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
import static org.hamcrest.MatcherAssert.assertThat;
im... |
Index only latest by default. | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from projects import tasks
from projects.models import ImportedFile
from builds.models import Version
log = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''\
Delete and re-create ImportedFile ... | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from projects import tasks
from projects.models import ImportedFile
from builds.models import Version
log = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''\
Delete and re-create ImportedFile ... |
Fix test broken due to delete_record change | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
from ggrc import db
from . import Indexer
class SqlIndexer(Indexer):
def cr... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
from ggrc import db
from . import Indexer
class SqlIndexer(Indexer):
def cr... |
Comment out a test case | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
sys.path.append('..')
from analyzer import rss_parser
#entries = rss_parser.parse(feed_link='http://news.yahoo.com/rss/us', language='en')
#entries = rss_parser.parse(feed_link='http://www.engadget.com/rss.xml', langu... | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
sys.path.append('..')
from analyzer import rss_parser
#entries = rss_parser.parse(feed_link='http://news.yahoo.com/rss/us', language='en')
#entries = rss_parser.parse(feed_link='http://www.engadget.com/rss.xml', langu... |
Add a comment about what happens for expired/non-existent uids | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// helper functions for views with a profile image. Meant to be mixed into views.
'use strict';
define([
'lib/... | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// helper functions for views with a profile image. Meant to be mixed into views.
'use strict';
define([
'lib/... |
Set status button in serial no | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.add_fetch("customer", "customer_name", "customer_name")
cur_frm.add_fetch("supplier", "supplier_name", "supplier_name")
cur_frm.add_fetch("item_code", "item_name", "item_name")
c... | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.add_fetch("customer", "customer_name", "customer_name")
cur_frm.add_fetch("supplier", "supplier_name", "supplier_name")
cur_frm.add_fetch("item_code", "item_name", "item_name")
c... |
Add better notes of when things aren't working. | var ChunkTypes = require('./ChunkTypes');
var DataRequestType = require('./io/DataRequestType');
var Promise = require('bluebird');
var Ranges = require('./utils/Ranges');
var _ = require('lodash');
var fetchDataRedirect = require('./fetchDataRedirect');
var regeneratorRuntime = require('regenerator/runtime');
var sen... | var ChunkTypes = require('./ChunkTypes');
var DataRequestType = require('./io/DataRequestType');
var Promise = require('bluebird');
var Ranges = require('./utils/Ranges');
var _ = require('lodash');
var fetchDataRedirect = require('./fetchDataRedirect');
var regeneratorRuntime = require('regenerator/runtime');
var sen... |
Rename js_lib to js_library in docs/comments/etc... to clean up lingering references to js_lib.
CL automatically created by:
replace_string --pcre '\b([^\":/\n])js_lib\b' '\1js_library'
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=248271419 | // Copyright 2008 The Closure Library Authors. 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 requ... | // Copyright 2008 The Closure Library Authors. 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 requ... |
Use hljs.listLanguages for auto-detection tests | 'use strict';
var fs = require('fs');
var hljs = require('../build');
var path = require('path');
var utility = require('./utility');
function testAutoDetection(language) {
it('should be detected as ' + language, function() {
var languagePath = utility.buildPath('detect', language),
examples ... | 'use strict';
var fs = require('fs');
var hljs = require('../build');
var path = require('path');
var utility = require('./utility');
function testAutoDetection(language) {
it('should be detected as ' + language, function() {
var languagePath = utility.buildPath('detect', language),
examples ... |
Set user password for all sanitized users to '123'. | #!/usr/bin/python
# Setup import paths, since we are using Django models
import sys, os
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production'
# Imports
from django.core import serializers
if len(sys.argv) != 4:
print "Usage: %s format input-file output-file" % sys.a... | #!/usr/bin/python
# Setup import paths, since we are using Django models
import sys, os
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production'
# Imports
from django.core import serializers
if len(sys.argv) != 4:
print "Usage: %s format input-file output-file" % sys.a... |
Move all navigation code into try block
This prevents navigation forward when the validation failed.
Before the user didn't have the chance to correct what was wrong and
where immediately taken on the next page. | import { take, put, select, call } from 'redux-saga/effects';
import { NAVIGATE_TO_NEXT_SECTION, setErrors, load } from '../actions';
import * as selectors from '../selectors';
import { push } from '../../common/actions/router';
import { validateNode, HTTPError } from '../../common/helpers/api';
// Navigate to next s... | import { take, put, select, call } from 'redux-saga/effects';
import { NAVIGATE_TO_NEXT_SECTION, setErrors, load } from '../actions';
import * as selectors from '../selectors';
import { push } from '../../common/actions/router';
import { validateNode, HTTPError } from '../../common/helpers/api';
// Navigate to next s... |
Add missing source map comment when debug is true
Without this comment, source maps won't resolve properly. | import { transformFile } from 'babel-core'
import { debug } from '../util/stdio'
import { default as es2015 } from 'babel-preset-es2015'
import { default as amd } from 'babel-plugin-transform-es2015-modules-amd'
export default function configure(pkg, opts) {
return (name, file, done) => {
transformFile(file
... | import { transformFile } from 'babel-core'
import { debug } from '../util/stdio'
import { default as es2015 } from 'babel-preset-es2015'
import { default as amd } from 'babel-plugin-transform-es2015-modules-amd'
export default function configure(pkg, opts) {
return (name, file, done) => {
transformFile(file
... |
Establish session in default handler. | /**
* Password authentication handler.
*
* This component provides an HTTP handler that authenticates a username and
* password. The credentials are submitted via an HTML form.
*/
exports = module.exports = function(parse, csrfProtection, authenticate, ceremony) {
function establishSession(req, res, next) {
... | /**
* Password authentication handler.
*
* This component provides an HTTP handler that authenticates a username and
* password. The credentials are submitted via an HTML form.
*/
exports = module.exports = function(parse, csrfProtection, authenticate, ceremony) {
function establishSession(req, res, next) {
... |
Add ability to change input color | // @flow
import React, { type ElementRef } from 'react';
import AutosizeInput from 'react-input-autosize';
import { colors, spacing } from '../theme';
import { Div } from '../primitives';
import type { PropsWithStyles } from '../types';
export type InputProps = PropsWithStyles & {
cx: string => string | void,
/*... | // @flow
import React, { type ElementRef } from 'react';
import AutosizeInput from 'react-input-autosize';
import { spacing } from '../theme';
import { Div } from '../primitives';
import type { PropsWithStyles } from '../types';
export type InputProps = PropsWithStyles & {
cx: string => string | void,
/** Refere... |
Remove delete from stop to avoid errors | const RtmpServer = require('rtmp-server');
const rtmpToHLS = require('./rtmpToHLS');
const { streamKey } = require('../config.json');
const { deleteVideos, log } = require('./utils');
function server(socket) {
const rtmpServer = new RtmpServer();
rtmpServer.listen(1935);
rtmpServer.on('error', (err) => {
l... | const RtmpServer = require('rtmp-server');
const rtmpToHLS = require('./rtmpToHLS');
const { streamKey } = require('../config.json');
const { deleteVideos, log } = require('./utils');
function server(socket) {
const rtmpServer = new RtmpServer();
rtmpServer.listen(1935);
rtmpServer.on('error', (err) => {
l... |
Modify exception handling to local config names | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigPa... | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigPa... |
Add timeout to dead links script | from operator import itemgetter
from itertools import chain
import os
import yaml
import requests
yaml.load_all
directory = "_companies"
flat = chain.from_iterable
def link_status_company(filename):
(name, _) = filename.rsplit(".", 1);
print("==== {name} ====".format(name=name))
docs = filter(None, ya... | from operator import itemgetter
from itertools import chain
import os
import yaml
import requests
yaml.load_all
directory = "_companies"
flat = chain.from_iterable
def link_status_company(filename):
(name, _) = filename.rsplit(".", 1);
print("==== {name} ====".format(name=name))
docs = filter(None, ya... |
Fix incorrect login url for sign in form on frontpage | <form name="loginform" action="<?php echo wp_login_url(home_url());?>" method="post">
<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
<input type="hidden" name="user-cookie" value="1" />
<p>
<input type="text" name="log" placeholder="E-postadress eller nick"
<?... | <form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post">
<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
<input type="hidden" name="user-cookie" value="1" />
<p>
<input type="text" name="log" placeholder="E-postadress eller nick"
<... |
Disable the Inspector panel patch (needs to be fixed on the platform) | /* See license.txt for terms of usage */
"use strict";
module.metadata = {
"stability": "experimental"
};
const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { MarkupV... | /* See license.txt for terms of usage */
"use strict";
module.metadata = {
"stability": "experimental"
};
const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { MarkupV... |
Use real model as basis for mock. | <?php if ( ! defined('BASEPATH')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once dirname(__FILE__) .'/../mcp.omnilog.php';
require_once dirname(__FILE__) ... | <?php if ( ! defined('BASEPATH')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once dirname(__FILE__) .'/../mcp.omnilog.php';
require_once dirname(__FILE__) ... |
Make Client, Service importable from pyservice | """
Copyright (c) 2014, Joseph Cross.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute,... | """
Copyright (c) 2014, Joseph Cross.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute,... |
Fix updates of package data | <?php
namespace Outlandish\Wpackagist\Storage;
use Doctrine\ORM\EntityManagerInterface;
use Outlandish\Wpackagist\Entity\PackageData;
final class Database extends Provider
{
/** @var EntityManagerInterface */
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
... | <?php
namespace Outlandish\Wpackagist\Storage;
use Doctrine\ORM\EntityManagerInterface;
use Outlandish\Wpackagist\Entity\PackageData;
final class Database extends Provider
{
/** @var EntityManagerInterface */
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
... |
Make review feedback not a Markdown widget
Review feedback wasn't supposed to be in markdown. Change the
widget to a regular text area. | from django import forms
from django.forms import Textarea
from markedit.widgets import MarkEdit
from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ["vote", "comment"]
widgets = {"comment": M... | from django import forms
from markedit.widgets import MarkEdit
from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ["vote", "comment"]
widgets = {"comment": MarkEdit()}
def __init__(self,... |
Rename the method for getting the compiler. | package com.haskforce.jps.model;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsElementFactory;
import org.jetbrains.jps.model.JpsElementTypeWithDefaultProperties;
import org.jetbrains.jps.model.li... | package com.haskforce.jps.model;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsElementFactory;
import org.jetbrains.jps.model.JpsElementTypeWithDefaultProperties;
import org.jetbrains.jps.model.li... |
Check that the non-plugin events are not caught by the plugin | var Plugin = require('vigour-native/lib/bridge/Plugin')
var plugin
describe('plugin', function () {
it('should be requireable', function () {
plugin = require('../../')
expect(plugin).instanceOf(Plugin)
expect(plugin.key).to.equal('plugin')
})
describe('native events', function () {
it('should f... | var Plugin = require('vigour-native/lib/bridge/Plugin')
var plugin
describe('plugin', function () {
it('should be requireable', function () {
plugin = require('../../')
expect(plugin).instanceOf(Plugin)
expect(plugin.key).to.equal('plugin')
})
describe('native events', function () {
it('should f... |
Fix for using the extension from inside an iframe | // FORKED FROM https://github.com/muaz-khan/WebRTC-Experiment/tree/master/Chrome-Extensions/desktopCapture
// this background script is used to invoke desktopCapture API to capture screen-MediaStream.
var session = ['screen', 'window'];
chrome.runtime.onConnect.addListener(function (port) {
// this one is called f... | // FORKED FROM https://github.com/muaz-khan/WebRTC-Experiment/tree/master/Chrome-Extensions/desktopCapture
// this background script is used to invoke desktopCapture API to capture screen-MediaStream.
var session = ['screen', 'window'];
chrome.runtime.onConnect.addListener(function (port) {
// this one is called f... |
Remove need for static pages | # OSU SPS Website Build Script
import os
def loadFile( src, prefx ):
out = ""
for line in open( src, 'r' ):
out += prefx + line
return out
def outputFile( name, content ):
file = open( name, 'w' )
file.write( content )
file.close()
out_folder = "output/"
src_folder = "src/"
inclu... | # OSU SPS Website Build Script
def loadFile( src, prefx ):
out = ""
for line in open( src, 'r' ):
out += prefx + line
return out
def outputFile( name, content ):
file = open( name, 'w' )
file.write( content )
file.close()
out_folder = "output/"
src_folder = "src/"
includes_folder ... |
Add missing option to tryCreatePlayer | //= require asciinema-player
function tryCreatePlayer(parentNode, asciicast, options) {
function createPlayer() {
asciinema_player.core.CreatePlayer(
parentNode,
asciicast.url,
{
width: asciicast.width,
height: asciicast.height,
snapshot: asciicast.snapshot,
spee... | //= require asciinema-player
function tryCreatePlayer(parentNode, asciicast, options) {
function createPlayer() {
asciinema_player.core.CreatePlayer(
parentNode,
asciicast.url,
{
width: asciicast.width,
height: asciicast.height,
snapshot: asciicast.snapshot,
spee... |
Use where in and cast to array.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
namespace Orchestra\Model\Scopes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
class UserWithRoleScope implements Scope
{
/**
* The selected role.
*
* @var string|array
*/
protected $role;
/**
* C... | <?php
namespace Orchestra\Model\Scopes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
class UserWithRoleScope implements Scope
{
/**
* The selected role.
*
* @var string
*/
protected $role;
/**
* Constru... |
2.5.1: Fix reset GridItem color for SPA preview | from PyQt5.QtGui import QFont
from cadnano.gui.views.styles import BLUE_STROKE, GRAY_STROKE, THE_FONT
# Slice Sizing
SLICE_HELIX_RADIUS = 15.
SLICE_HELIX_STROKE_WIDTH = 0.5
SLICE_HELIX_MOD_HILIGHT_WIDTH = 1
EMPTY_HELIX_STROKE_WIDTH = 0.25
# Z values
# bottom
ZSLICEHELIX = 40
ZSELECTION = 50
ZDESELECTOR = 60
ZWEDGEGIZ... | from PyQt5.QtGui import QFont
from cadnano.gui.views.styles import BLUE_STROKE, GRAY_STROKE, THE_FONT
# Slice Sizing
SLICE_HELIX_RADIUS = 15.
SLICE_HELIX_STROKE_WIDTH = 0.5
SLICE_HELIX_MOD_HILIGHT_WIDTH = 1
EMPTY_HELIX_STROKE_WIDTH = 0.25
# Z values
# bottom
ZSLICEHELIX = 40
ZSELECTION = 50
ZDESELECTOR = 60
ZWEDGEGIZ... |
Add alias for the Guard contract to auth.driver | <?php
namespace MyBB\Auth;
use Illuminate\Auth\AuthServiceProvider as LaravelAuth;
use MyBB\Auth\Hashing\phpass\PasswordHash;
/**
* This class is only used to register our own subclass of the AuthManager instead of Laravel's default one
*/
class AuthServiceProvider extends LaravelAuth
{
/**
* Regis... | <?php
namespace MyBB\Auth;
use Illuminate\Auth\AuthServiceProvider as LaravelAuth;
use MyBB\Auth\Hashing\phpass\PasswordHash;
/**
* This class is only used to register our own subclass of the AuthManager instead of Laravel's default one
*/
class AuthServiceProvider extends LaravelAuth
{
/**
* Regis... |
Use star args to invoke apply_async | from __future__ import absolute_import
import celery
import os
import os.path
import sys
# Add the project to the python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
# Configure the application only if it seemingly isnt already configured
from django.conf import settings
if not setting... | from __future__ import absolute_import
import celery
import os
import os.path
import sys
# Add the project to the python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
# Configure the application only if it seemingly isnt already configured
from django.conf import settings
if not setting... |
Use nltk to extract text from html data | # coding: utf-8
"""
Script to download the raw data from http://www.rsssf.com/
The data was processed mostly by interactive sessions in ipython. Almost every
file had it's own format, so there is no point in trying to automate it in a
fully automatic script, but this downloading script may be useful for future
dowloads... | # coding: utf-8
"""
Script to download the raw data from http://www.rsssf.com/
The data was processed mostly by interactive sessions in ipython. Almost every
file had it's own format, so there is no point in trying to automate it in a
fully automatic script, but this downloading script may be useful for future
dowloads... |
Change custom tag name [rev. matthew.gordon] | /*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.searchcomponents.core.search;
import com.hp.autonomy.types.requests.Documents;
import java.io.Serializable;
im... | /*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.searchcomponents.core.search;
import com.hp.autonomy.types.requests.Documents;
import java.io.Serializable;
im... |
chore(pins): Update dict pin in prep for release
- Update dict pin in prep for release | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.... | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.... |
Revert a debugging change that slipped in.
git-svn-id: 48f3d5eb0141859d8d7d81547b6bd7b3dde885f8@186 8655a95f-0638-0410-abc2-2f1ed958ef3d | from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
... | from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
... |
Change adminSettings/save to accept a list of settings instead of just one | package mil.dds.anet.resources;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.AdminSetting;
import mil.dds.anet.database.... | package mil.dds.anet.resources;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.AdminSetting;
import mil.dds.anet.database.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.