text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add a boolean field to Store model (store.has_coffee) | # coding: utf-8
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField('self', blank=True)
def __unicode__(self):
return self.name
class Publisher(models.Model):
name = models.CharField... | # coding: utf-8
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField('self', blank=True)
def __unicode__(self):
return self.name
class Publisher(models.Model):
name = models.CharField... |
Add paranthesis to function call | var GameController = require("./GameController");
exports.fire = function (req, res) {
var player = req.body.username;
var x = req.body.x;
var y = req.body.y;
GameController.findGame(player).then(function(game) {
if (game != null) {
// If game is over, the other player won.
// The game's fini... | var GameController = require("./GameController");
exports.fire = function (req, res) {
var player = req.body.username;
var x = req.body.x;
var y = req.body.y;
GameController.findGame(player).then(function(game) {
if (game != null) {
// If game is over, the other player won.
// The game's fini... |
Move fully qualified class name to a use statement | <?php
namespace Joindin\Model\Db;
use \Joindin\Service\Db as DbService;
class User
{
protected $keyName = 'users';
protected $db;
public function __construct()
{
$this->db = new DbService();
}
public function getUriFor($username)
{
$data = $this->db->getOneByKey($this->k... | <?php
namespace Joindin\Model\Db;
class User
{
protected $keyName = 'users';
protected $db;
public function __construct()
{
$this->db = new \Joindin\Service\Db;
}
public function getUriFor($username)
{
$data = $this->db->getOneByKey($this->keyName, 'username', $username);
... |
Include attempts when printing answer | // Package pu makes solving projecteuler problems easier and reduces boilerplate.
package pu
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// Problem is a Project Euler (.net) problem
type Problem struct {
// ID is the id of the problem on projecteuler.net
ID int
// Solver is the function whi... | // Package pu makes solving projecteuler problems easier and reduces boilerplate.
package pu
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// Problem is a Project Euler (.net) problem
type Problem struct {
// ID is the id of the problem on projecteuler.net
ID int
// Solver is the function whi... |
Use new menu contsants in home menu item
Summary: Ref T11957, just lays in some minor bug fixes. Sets correct menu, removes sidebar on edit.
Test Plan: Test /menu/ on home with Admin and Normal accounts.
Reviewers: epriestley
Reviewed By: epriestley
Subscribers: Korvin
Maniphest Tasks: T11957
Differential Revisi... | <?php
final class PhabricatorHomeMenuItemController
extends PhabricatorHomeController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$type = $request->getURIData('type');
$custom_phid = null;
$menu = PhabricatorProfileMenuEngine::MENU_GLOBAL;
if ($type... | <?php
final class PhabricatorHomeMenuItemController
extends PhabricatorHomeController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$type = $request->getURIData('type');
$custom_phid = null;
if ($type == 'personal') {
$custom_phid = $viewer->getPHID... |
Fix ReadAll to run on Windows.
filepath.Clean converts filenames to filenames with native path
separators. Use ToSlash to normalize.
Signed-off-by: Anusha Ragunathan <11258be80bf4b196e47582a3113274a53ec55793@docker.com> | package dockerignore
import (
"bufio"
"fmt"
"io"
"path/filepath"
"strings"
)
// ReadAll reads a .dockerignore file and returns the list of file patterns
// to ignore. Note this will trim whitespace from each line as well
// as use GO's "clean" func to get the shortest/cleanest path for each.
func ReadAll(reader ... | package dockerignore
import (
"bufio"
"fmt"
"io"
"path/filepath"
"strings"
)
// ReadAll reads a .dockerignore file and returns the list of file patterns
// to ignore. Note this will trim whitespace from each line as well
// as use GO's "clean" func to get the shortest/cleanest path for each.
func ReadAll(reader ... |
Add getter/setter so we can actually use this... | /*
* Copyright (C) 2016 Prowave Consulting, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This progr... | /*
* Copyright (C) 2016 Prowave Consulting, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This progr... |
Update warnings to return on null or undefined. | /**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import classnames from 'classnames';
import ErrorIcon from '../../../svg/error.svg';
const { useSelect } = Data;
/*
* A single module. Keeps track of i... | /**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import classnames from 'classnames';
import ErrorIcon from '../../../svg/error.svg';
const { useSelect } = Data;
/*
* A single module. Keeps track of i... |
Adjust maximum block size for lzo | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") )
if not os.path.isdir(build_dir):
... | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") )
if not os.path.isdir(build_dir):
... |
Fix typo win -> won | const h = require('virtual-dom/h');
module.exports = function (data) {
const {gameID, game} = data;
return h('div', {className: 'room'}, [
game.playing ? null : h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'),
game.playing ? null : h('form', {id: 'setup', method: 'post', action: `/${gameID}`},... | const h = require('virtual-dom/h');
module.exports = function (data) {
const {gameID, game} = data;
return h('div', {className: 'room'}, [
game.playing ? null : h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'),
game.playing ? null : h('form', {id: 'setup', method: 'post', action: `/${gameID}`},... |
fix: Fix syntax errors made in previous commit | import classNames from 'classnames';
import React, { PropTypes } from 'react';
const HeaderView = ({
items,
githubLink,
onLabelClick
}) => (<div className="github-embed-nav">
{items.map(({ shown, label }, index) =>
<a
className={classNames({
'github-embed-nav-link': ... | import classNames from 'classnames';
import React, { PropTypes } from 'react';
const HeaderView = ({
items,
githubLink,
onLabelClick
}) => (<div className="github-embed-nav">
{items.map(({ shown, label }, index) =>
<a
className={classNames({
'github-embed-nav-link': ... |
Add check if updates to not exist for a certain trigger | 'use strict'
const getNode = require('./getNode')
const err = require('./err')
require('setimmediate')
module.exports = (db, path) => {
let fns = db.updates.fns[path]
if (!fns) {
return
}
let len = fns.length
for (let i = 0; i < len; i += 1) {
setImmediate(() => {
let val = getNode(db, p... | 'use strict'
const getNode = require('./getNode')
const err = require('./err')
require('setimmediate')
module.exports = (db, path) => {
let fns = db.updates.fns[path]
let len = fns.length
for (let i = 0; i < len; i += 1) {
setImmediate(() => {
let val = getNode(db, path)
let cacheTest = JSON... |
Hide Nunjucks warnings from the dev console | 'use strict';
const path = require('path');
const fractal = module.exports = require('@frctl/fractal').create();
const pkg = require(path.join(__dirname, 'package.json'));
fractal.set('project.title', 'Kanbasu');
fractal.set('project.version', pkg.version);
fractal.components.set('path', path.join(__dirname, 'compon... | 'use strict';
const path = require('path');
const fractal = module.exports = require('@frctl/fractal').create();
const pkg = require(path.join(__dirname, 'package.json'));
fractal.set('project.title', 'Kanbasu');
fractal.set('project.version', pkg.version);
fractal.components.set('path', path.join(__dirname, 'compon... |
SyntaxError: Use of const in strict mode. | /* jshint node: true */
'use strict';
var BasePlugin = require('ember-cli-deploy-plugin');
module.exports = {
name: 'ember-cli-deploy-firebase',
createDeployPlugin: function(options) {
var DeployPlugin = BasePlugin.extend({
name: options.name,
upload: function(context) {
let outer = this;... | /* jshint node: true */
'use strict';
var BasePlugin = require('ember-cli-deploy-plugin');
module.exports = {
name: 'ember-cli-deploy-firebase',
createDeployPlugin: function(options) {
var DeployPlugin = BasePlugin.extend({
name: options.name,
upload: function(context) {
const outer = thi... |
Add iter task to Grunt | module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
sass: {
dist: {
files: {
'css/main.css': 'sass/main.sass'
}
}
},
cssmin: {
target: {
files: [{
expand: true,
src: ['css/*.css'],
... | module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
sass: {
dist: {
files: {
'css/main.css': 'sass/main.sass'
}
}
},
cssmin: {
target: {
files: [{
expand: true,
src: ['css/*.css'],
... |
Switch the CloudI Job API to use the binary output misultin job, instead of the list output one... both work. | # -*- coding: utf-8; Mode: python; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
# ex: set softtabstop=4 tabstop=4 shiftwidth=4 expandtab fileencoding=utf-8:
import sys, os
sys.path.append(
os.path.sep.join(
os.path.dirname(os.path.abspath(__file__))
.split(os.path.sep) + ['jso... | # -*- coding: utf-8; Mode: python; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
# ex: set softtabstop=4 tabstop=4 shiftwidth=4 expandtab fileencoding=utf-8:
import sys, os
sys.path.append(
os.path.sep.join(
os.path.dirname(os.path.abspath(__file__))
.split(os.path.sep) + ['jso... |
Add test data and Fix assertion | package container
import (
"fmt"
"github.com/stretchr/testify/assert"
"os"
"reflect"
"testing"
)
type testtype struct {
Foo string
Bar string
}
type testdata struct {
emp interface{}
val interface{}
}
var testdataSet = []testdata{
{new(string), "value"},
{new(int), 1234},
{new(float64), 12.34},
{new(te... | package container
import (
"fmt"
"github.com/stretchr/testify/assert"
"os"
"reflect"
"testing"
)
type testtype struct {
Foo string
Bar string
}
type testdata struct {
emp interface{}
val interface{}
}
var testdataSet = []testdata{
{new(string), "value"},
{new(int), 1234},
{new(float64), 12.34},
{new(te... |
Refactor to use export * from ... | import uuid from 'uuid'
export * from './picture.js'
export const reset = () => ({
type: 'RESET'
})
export const addColour = (colour) => ({
type: 'ADD_COLOUR',
id: uuid.v1(),
colour,
})
export const setPreviewColour = (colour) => ({
type: 'SET_PREVIEW_COLOUR',
colour,
})
export const setHexColour = (he... | import uuid from 'uuid'
import {
loadPictureRequest, loadPictureSuccess,
fetchPictureFromPath, fetchPictureFromUrl, fetchPictureIfNeeded
} from './pictures.js'
export { loadPictureRequest, loadPictureSuccess,
fetchPictureFromPath, fetchPictureFromUrl, fetchPictureIfNeeded }
export const reset = () => ({
type: '... |
Test - fix output dir name | # Copyright 2015 0xc0170
#
# 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, soft... | # Copyright 2015 0xc0170
#
# 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, soft... |
Use content or README.md as long_description | #!/usr/bin/env python
from setuptools import setup
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='screenplain',
version='0.... | #!/usr/bin/env python
from setuptools import setup
setup(
name='screenplain',
version='0.9.0',
description='Convert text file to viewable screenplay.',
author='Martin Vilcans',
author_email='screenplain@librador.com',
url='http://www.screenplain.com/',
project_urls={
'Web Page': 'h... |
Remove configurable Base Path for js callout proxy | /**
* 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
*
* http://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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
Fix all items needs key | import React, { PropTypes, Component } from 'react';
import { Link } from 'react-router';
import shouldPureComponentUpdate from '../../../../node_modules/react-pure-render/function';
export default class ToolBar extends Component {
static propTypes = {
links : PropTypes.array.isRequired,
a... | import React, { PropTypes, Component } from 'react';
import { Link } from 'react-router';
import shouldPureComponentUpdate from '../../../../node_modules/react-pure-render/function';
export default class ToolBar extends Component {
static propTypes = {
links: PropTypes.array.isRequired,
activeLinkI... |
Exclude Enhance-o Mechano from its own buff targets | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION... | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION... |
Introduce integration tests using DropWizards ResourceTest. Include ability to return an Invalid Request message when the DLN or EnquiryId are missing. | package uk.gov.dvla.services.enquiry;
import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;
public interface DriverEnquiry extends ManagedService
{
public static final String EXTERNAL_DRIVER_URI = "/external/driver/";
public static final Strin... | package uk.gov.dvla.services.enquiry;
import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;
public interface DriverEnquiry extends ManagedService
{
public static final String DRIVER_URI = "/driver/";
public static final String CUSTOMER_PORTAL ... |
Fix reviewer suggestions when suggestFrom > 0
RemoteSuggestOracle runs exactly one call to the
SuggestAfterTypingNCharsOracle then waits until
that completes. If SuggestAfterTypingNCharsOracle
doesn't want to send this query, it must finish
with no results to allow RemoteSuggestOracle to
unblock and consider the next ... | // Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... | // Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... |
Use `delete_all` instead of running cypher query | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Shared fixtures for :mod:`pytest`."""
from __future__ import print_function, absolute_import
import os
import pytest # noqa
import gryaml
from py2neo_compat import py2neo_ver
@pytest.fixture
def graphdb():
"""Fixture connecting to graphdb."""
if 'NEO4J_UR... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Shared fixtures for :mod:`pytest`."""
from __future__ import print_function, absolute_import
import os
import pytest # noqa
import gryaml
from py2neo_compat import py2neo_ver
@pytest.fixture
def graphdb():
"""Fixture connecting to graphdb."""
if 'NEO4J_UR... |
Handle \ on Windows, normalize to / | var es = require('event-stream');
var path = require('path');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var header = require('gulp-header');
var footer = require('gulp-footer');
var PluginError = gutil.PluginError;
var htmlJsStr = require('js-string-escape');
function templateCache(root) {... | var es = require('event-stream');
var path = require('path');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var header = require('gulp-header');
var footer = require('gulp-footer');
var PluginError = gutil.PluginError;
var htmlJsStr = require('js-string-escape');
function templateCache(root) {... |
Change import statement for external library yaml | import pathlib
import socket
import pyflare
from yaml import load
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 53))
myip = s.getsockname()[0]
s.close()
with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r:
update_list = load(r)
for account in update_list:
... | import pathlib
import socket
import pyflare
import yaml
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 53))
myip = s.getsockname()[0]
s.close()
with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r:
update_list = yaml.load(r)
for account in update_list:
r... |
Fix factory with proper variable name | <?php namespace Affinity
{
use Dotink\Flourish;
/**
*
*/
class Config implements ConfigInterface
{
/**
*
*/
static public function create($types, $data = NULL)
{
if (func_num_args() == 1) {
$types = [];
$data = func_get_arg(0);
}
return new static($types, $data);
}
/**
*... | <?php namespace Affinity
{
use Dotink\Flourish;
/**
*
*/
class Config implements ConfigInterface
{
/**
*
*/
static public function create($types, $data = NULL)
{
if (func_num_args() == 1) {
$types = [];
$resource = func_get_arg(0);
}
return new static($types, $data);
}
/*... |
Add connection source function for using this for other purposes | package edu.umass.cs.ciir.waltz.dbindex;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import java.io.File;
import java.sql.SQLException;
/**
* @author jfoley
*/
public class DBConfig {
private final String jdbcURL;
private final String password;
private... | package edu.umass.cs.ciir.waltz.dbindex;
import java.io.File;
/**
* @author jfoley
*/
public class DBConfig {
private final String jdbcURL;
private final String password;
private final String user;
public DBConfig(String jdbcURL, String user, String pass) {
this.jdbcURL = jdbcURL;
this.user = user;... |
Enable video content for cms pages
[#110289088] | from django.db import models
# Create your models here.
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.models import Page
from feincms.content.richtext.models import RichTextContent
from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.video.models im... | from django.db import models
# Create your models here.
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.models import Page
from feincms.content.richtext.models import RichTextContent
from feincms.content.medialibrary.models import MediaFileContent
# Page.register_extensions('datepub... |
Add auth header to the fixture loader
It seems to work fine with the unauthenticated es instance | """ Commands for interacting with Elastic Search """
# pylint: disable=broad-except
from os.path import join
import requests
from lib.tools import TEST_FOLDER
def es_is_available():
""" Test if Elastic Search is running """
try:
return (
requests.get("http://localhost:9200", auth=("ela... | """ Commands for interacting with Elastic Search """
# pylint: disable=broad-except
from os.path import join
import requests
from lib.tools import TEST_FOLDER
def es_is_available():
""" Test if Elastic Search is running """
try:
return (
requests.get("http://localhost:9200").json()["ta... |
Add compile_to_json invocation in Myrial test fixture |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parse... |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parser = parser.Parser()
self.processor ... |
Add another test for CallExplorer.history_glob | # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):... | # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):... |
Make user loggin as the homepage | """service_control URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | """service_control URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... |
Use more readable version for checking the final modifier is present.
git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@374 c7a0535c-eda6-11de-83d8-6d5adf01d787 | /*
* Mutability Detector
*
* Copyright 2009 Graham Allan
*
* 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... | /*
* Mutability Detector
*
* Copyright 2009 Graham Allan
*
* 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... |
Change create so it uses bulk edit, insteadt of just setAttributes | "use strict";
var domElementFactory = require( "./lib/domElementFactory" ),
domElementListFactory = require( "./lib/domElementListFactory" );
function create( tagName, args ) {
var $element = domElementFactory( document.createElement( tagName ) );
$element.bulkEdit( args );
return $element;
}
function createFr... | "use strict";
var domElementFactory = require( "./lib/domElementFactory" ),
domElementListFactory = require( "./lib/domElementListFactory" );
function create( tagName, args ) {
var $element = domElementFactory( document.createElement( tagName ) );
$element.setAttributes( args );
return $element;
}
function cre... |
Use the correct since value | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Ioannis Moutsatsos, Bruno P. Kinoshita
*
* 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 l... | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Ioannis Moutsatsos, Bruno P. Kinoshita
*
* 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 l... |
Hide notification bars after a few seconds. | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... |
Fix the extraction of the HttpServletRequest | package net.kencochrane.raven.servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
@WebListener
public class RavenServletRequestListener implements... | package net.kencochrane.raven.servlet;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
@WebListener
public class RavenServletRequestListener implements ServletRequestListener {
private... |
Revert "Use importlib instead of __import__"
This reverts commit 1c40e03b487ae3dcef9a683de960f9895936d370. | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import haas
import logging
import sys
L... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import importlib
import logging
import h... |
Change app name to Ninhursag. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Ninhursag'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
JS_LOG_L... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Skeleton'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
JS_LOG_LE... |
Terminate app if handler throws exception. | from ofp_app import ofp_app, ofp_run
import asyncio
app = ofp_app('conntest', kill_on_exception=True)
@app.event('start')
async def start(_):
while True:
await asyncio.sleep(1)
# Obtain a list of connections.
conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0)
for conn ... | from ofp_app import ofp_app, ofp_run
import asyncio
app = ofp_app('conntest')
@app.event('start')
async def start(_):
while True:
await asyncio.sleep(1)
# Obtain a list of connections.
conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0)
for conn in conns.stats:
... |
Use .reduce to filter out null flags and account for new individuals for audit via Graphiql |
// @flow
import { manager } from '../../../../core/service-providers/manager'
import { Auditor } from '../../../../core/auditor'
import { individualStore } from '../../../../core/data/individual-store'
import { groupStore } from '../../../../core/data/group-store'
import type { FlaggedInfo } from '../../../../core/typ... |
// @flow
import { manager } from '../../../../core/service-providers/manager'
import { Auditor } from '../../../../core/auditor'
import { individualStore } from '../../../../core/data/individual-store'
import { groupStore } from '../../../../core/data/group-store'
import type { FlaggedInfo } from '../../../../core/typ... |
Add exp14.GoPackageList interface for exp14.GoPackages. | package exp14
import (
. "github.com/shurcooL/go/gists/gist7480523"
. "github.com/shurcooL/go/gists/gist7802150"
"github.com/shurcooL/go/gists/gist8018045"
)
type GoPackageList interface {
List() []*GoPackage
DepNode2I
}
type GoPackages struct {
SkipGoroot bool // Currently, works on initial run only; changi... | package exp14
import (
. "github.com/shurcooL/go/gists/gist7480523"
. "github.com/shurcooL/go/gists/gist7802150"
"github.com/shurcooL/go/gists/gist8018045"
)
type GoPackages struct {
SkipGoroot bool // Currently, works on initial run only; changing its value afterwards has no effect.
Entries []*GoPackage
Dep... |
Make verify function false by default | <?php
class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread
{
protected function _getFields()
{
$fields = parent::_getFields();
$fields['xf_thread']['word_count'] = array(
'type' => self::TYPE_UNKN... | <?php
class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread
{
protected function _getFields()
{
$fields = parent::_getFields();
$fields['xf_thread']['word_count'] = array(
'type' => self::TYPE_UNKN... |
Improve http logger output filenames | 'use strict';
var fs = require( 'fs' );
var path = require( 'path' );
var fileStreamRotator = require( 'file-stream-rotator' );
// Use Morgan logger for HTTP access logging
var morgan = require( 'morgan' );
var logDirPath = path.join( process.cwd(), 'logs' );
module.exports = {
/**
* Return a configured Morgan... | 'use strict';
var fs = require( 'fs' );
var path = require( 'path' );
var fileStreamRotator = require( 'file-stream-rotator' );
// Use Morgan logger for HTTP access logging
var morgan = require( 'morgan' );
var logDirPath = path.join( process.cwd(), 'logs' );
module.exports = {
/**
* Return a configured Morgan... |
Fix double extension bug for nested files with non-pretty-URL | <?php namespace TightenCo\Jigsaw;
class BasicOutputPathResolver
{
public function link($path, $name, $type, $page = 1)
{
$extension = $type ? '.' . $type : '';
$name = basename($name, $extension);
return $page > 1 ?
$this->clean('/' . $path . '/' . $page . '/' . $name . $ex... | <?php namespace TightenCo\Jigsaw;
class BasicOutputPathResolver
{
public function link($path, $name, $type, $page = 1)
{
if ($page > 1) {
return $this->clean('/' . $path . '/' . $page . '/' . $name . '.' . $type);
}
return $this->clean('/' . $path . '/' . $name . '.' . $type... |
Update to the export file. | import EO from 'ember-orbit/main';
import Store from 'ember-orbit/store';
import Model from 'ember-orbit/model';
import RecordArrayManager from 'ember-orbit/record-array-manager';
import Schema from 'ember-orbit/schema';
import Source from 'ember-orbit/source';
import HasManyArray from 'ember-orbit/links/has-many-array... | import EO from 'ember-orbit/main';
import Store from 'ember-orbit/store';
import Model from 'ember-orbit/model';
import RecordArrayManager from 'ember-orbit/record-array-manager';
import Schema from 'ember-orbit/schema';
import Source from 'ember-orbit/source';
import attr from 'ember-orbit/fields/attr';
import hasMany... |
Set csrf header in AngularJS’ $http requests
CakePHP provides the csrf token in a cookie already.
These two lines instruct AngularJS to read the token
from that cookie and to send it as a header in all
the requests emitted by the $http service. | (function() {
'use strict';
angular
.module('app', ['ngMaterial', 'ngMessages'])
.config(['$mdThemingProvider', '$mdIconProvider', '$httpProvider', function($mdThemingProvider, $mdIconProvider, $httpProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('gre... | (function() {
'use strict';
angular
.module('app', ['ngMaterial', 'ngMessages'])
.config(['$mdThemingProvider', '$mdIconProvider', '$httpProvider', function($mdThemingProvider, $mdIconProvider, $httpProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('gre... |
Use the string module instead of string methods; this should still work
with Python 1.5.2 for now. | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Meggins... | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Meggins... |
Create line break for icons div. | import React from 'react';
import icons from '../weather_icons/WeatherIcons';
const TenDay = ({ tenDayForecast }) => {
if (!tenDayForecast) {
return null;
}
const forecastArray = tenDayForecast.simpleforecast.forecastday;
const tenDayDataLoop = forecastArray.map((day, i) => {
return (
<div classN... | import React from 'react';
import icons from '../weather_icons/WeatherIcons';
const TenDay = ({ tenDayForecast }) => {
if (!tenDayForecast) {
return null;
}
const forecastArray = tenDayForecast.simpleforecast.forecastday;
const tenDayDataLoop = forecastArray.map((day, i) => {
return (
<div classN... |
Add NFD_NFC to unicode normalization comparison. | # -*- coding: utf-8 -*-
import unicodedata
def shortest_normalization_form():
"""
Find unicode normalization that generates shortest utf8 encoded text.
Result NFKC
"""
s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky   things'
nfc = unicodedata.normalize('NFC', s)
nfd = unico... | # -*- coding: utf-8 -*-
import unicodedata
def shortest_normalization_form():
"""
Find unicode normalization that generates shortest utf8 encoded text.
Result NFKC
"""
s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky   things'
nfc = unicodedata.normalize('NFC', s)
nfd = unico... |
Add backend to register form. | package controllers
import (
"github.com/astaxie/beego"
"ustackweb/models"
)
type Registration struct {
Username string
Password string
}
type RegistrationsController struct {
BaseController
}
func (this *RegistrationsController) Prepare() {
this.PrepareXsrf()
this.PrepareLayout()
this.Layout = "layouts/def... | package controllers
import (
"github.com/astaxie/beego"
)
type Registration struct {
Username string
Password string
}
type RegistrationsController struct {
BaseController
}
func (this *RegistrationsController) Prepare() {
this.PrepareXsrf()
this.PrepareLayout()
this.Layout = "layouts/default.html.tpl"
}
fu... |
Add support for thumbs down in radio mode on Yandex.Music | controller = new BasicController({
supports: {
playpause: true,
next: true,
previous: true,
favorite: true,
thumbsDown: false // Changes dynamically
},
playPauseSelector: '.player-controls__btn_play',
previousSelector: '.player-controls__btn_prev',
nextSelect... | controller = new BasicController({
supports: {
playpause: true,
next: true,
previous: true,
favorite: true
},
playPauseSelector: '.player-controls__btn_play',
previousSelector: '.player-controls__btn_prev',
nextSelector: '.player-controls__btn_next',
titleSelector... |
Handle case of no identifiers at all in meta data | #!/usr/bin/env python
import sys
import os
import yaml
import isbnlib
metafile = sys.argv[1]
metadata = open(metafile, 'r').read()
yamldata = yaml.load(metadata)
identifier = {}
if "identifier" in yamldata:
for id in yamldata["identifier"]:
if "key" in id:
isbnlike = isbnlib.get_isbnlike(id[... | #!/usr/bin/env python
import sys
import os
import yaml
import isbnlib
metafile = sys.argv[1]
metadata = open(metafile, 'r').read()
yamldata = yaml.load(metadata)
identifier = {}
for id in yamldata["identifier"]:
if "key" in id:
isbnlike = isbnlib.get_isbnlike(id["text"])[0]
if isbnlib.is_isbn13(... |
Fix hover depth for connections | /**
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | /**
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
Change router action so it occurs on all pages rather than 404s | <?php
namespace FrontRouterPlugin;
call_user_func(function() {
// thisfile
$thisfile = basename(__FILE__, '.php');
// language
i18n_merge($thisfile) || i18n_merge($thisfile, 'en_US');
// requires
require_once(GSPLUGINPATH . $thisfile . '/php/functions.php');
require_once(GSPLUGINPATH . $thisfile . '/php/co... | <?php
namespace FrontRouterPlugin;
call_user_func(function() {
// thisfile
$thisfile = basename(__FILE__, '.php');
// language
i18n_merge($thisfile) || i18n_merge($thisfile, 'en_US');
// requires
require_once(GSPLUGINPATH . $thisfile . '/php/functions.php');
require_once(GSPLUGINPATH . $thisfile . '/php/co... |
[FEATURE] Change withdrawal status from pending to notified. | var gateway = require(__dirname+'/../');
var request = require('request');
function getQueuedWithdrawal(fn){
gateway.api.listWithdrawals(function(err, withdrawals){
if (err){
fn(err, null);
} else {
if (withdrawals && withdrawals[0]){
fn(null, withdrawals[0]);
} else {
fn(nu... | var gateway = require(__dirname+'/../');
var request = require('request');
function getQueuedWithdrawal(fn){
gateway.api.listWithdrawals(function(err, withdrawals){
if (err){
fn(err, null);
} else {
if (withdrawals && withdrawals[0]){
fn(null, withdrawals[0]);
} else {
fn(nu... |
Change Test to not mock a non existing method | <?php declare(strict_types = 1);
namespace Templado\Engine;
use DOMDocument;
use PHPUnit\Framework\TestCase;
class StripRDFaAttributesTransformationTest extends TestCase {
public function testTransformationRemovedExpectedAttributes(): void {
$transformation = new StripRDFaAttributesTransformation();
... | <?php declare(strict_types = 1);
namespace Templado\Engine;
use DOMDocument;
use PHPUnit\Framework\TestCase;
class StripRDFaAttributesTransformationTest extends TestCase {
public function testTransformationRemovedExpectedAttributes(): void {
$transformation = new StripRDFaAttributesTransformation();
... |
FIX Assert not empty on something that actually is in every composer.json | <?php
namespace BringYourOwnIdeas\Maintenance\Tests\Util;
use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use PHPUnit_Framework_TestCase;
use SapphireTest;
/**
* @mixin PHPUnit_Framework_TestCase
*/
class ComposerLoaderTest extends SapphireTest
{
public function testGetJson()
{
$loader = new... | <?php
namespace BringYourOwnIdeas\Maintenance\Tests\Util;
use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use PHPUnit_Framework_TestCase;
use SapphireTest;
/**
* @mixin PHPUnit_Framework_TestCase
*/
class ComposerLoaderTest extends SapphireTest
{
public function testGetJson()
{
$loader = new... |
Use a bigger buffer size for the ``lots of sets'' test. | package net.spy.memcached;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
* Small test program that does a bunch of sets in a tight loop.
*/
public class DoLotsOfSets {
public static void main(String[] args) throws Exception {
// Create a client with a queue big enough to hold the 300,000 it... | package net.spy.memcached;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
* Small test program that does a bunch of sets in a tight loop.
*/
public class DoLotsOfSets {
public static void main(String[] args) throws Exception {
// Create a client with a queue big enough to hold the 300,000 it... |
Fix problem with dropping Q on enc that only supports O (for example) | 'use strict';
angular.module('vleApp')
.directive('fieldDrop', function (Dataset) {
return {
templateUrl: 'templates/fielddrop.html',
restrict: 'E',
scope: {
fieldDef: '=',
types: '='
},
controller: function ($scope) {
$scope.removeField = function() {
... | 'use strict';
angular.module('vleApp')
.directive('fieldDrop', function (Dataset) {
return {
templateUrl: 'templates/fielddrop.html',
restrict: 'E',
scope: {
fieldDef: '=',
types: '='
},
controller: function ($scope) {
$scope.removeField = function() {
... |
Revert " 版本信息及地址qobx.me --> qiniu.com"
This reverts commit 118febda31caca805a1746d386cfc4f1568f5b08. | package com.qiniu.api.config;
/**
* The Config class is a global configuration file for the sdk, used for serve
* side only.
*/
public class Config {
public static final String CHARSET = "utf-8";
public static String USER_AGENT="qiniu java-sdk v6.0.0";
/**
* You can get your accesskey from <a href="https:/... | package com.qiniu.api.config;
/**
* The Config class is a global configuration file for the sdk, used for serve
* side only.
*/
public class Config {
public static final String CHARSET = "utf-8";
public static String USER_AGENT="qiniu java-sdk v6.1.2";
/**
* You can get your accesskey from <a href="https:/... |
Remove xfail from working test | # trivial_example.py
#
# Copyright 2014 BitVault.
#
# Reproduces the tests in trivial_example.rb
from __future__ import print_function
import pytest
from random import randint
from patchboard.tests.fixtures import (trivial_net_pb,
trivial_net_resources,
... | # trivial_example.py
#
# Copyright 2014 BitVault.
#
# Reproduces the tests in trivial_example.rb
from __future__ import print_function
import pytest
from random import randint
from patchboard.tests.fixtures import (trivial_net_pb,
trivial_net_resources,
... |
[Migrations] Add missing mysql check for migrations | <?php
declare(strict_types=1);
namespace Sylius\Bundle\CoreBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20220210135918 extends AbstractMigration
{
public function getDescription... | <?php
declare(strict_types=1);
namespace Sylius\Bundle\CoreBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20220210135918 extends AbstractMigration
{
public function getDescription... |
Fix linting error (import extension missing) | import Map from '../../../src/ol/Map.js';
import View from '../../../src/ol/View.js';
import Static from '../../../src/ol/source/ImageStatic.js';
import {
get as getProjection,
transformExtent
} from '../../../src/ol/proj.js';
import ImageLayer from '../../../src/ol/layer/Image.js';
const source = new Static({
u... | import Map from '../../../src/ol/Map.js';
import View from '../../../src/ol/View.js';
import Static from '../../../src/ol/source/ImageStatic.js';
import {
get as getProjection,
transformExtent
} from '../../../src/ol/proj';
import ImageLayer from '../../../src/ol/layer/Image.js';
const source = new Static({
url:... |
Edit Swewify transition to only target transform property | //@flow
import styled from "styled-components";
const random = (severity = 1): number => (Math.random() - 0.5) * severity;
const randomTranslate = (n: number, s): number => random(s) * n;
const randomRotate = (n: number, s): number => random(s) * n * 2;
const randomScale = (n = 1, s): number => random(s) * n + 1;
ex... | //@flow
import styled from "styled-components";
const random = (severity = 1): number => (Math.random() - 0.5) * severity;
const randomTranslate = (n: number, s): number => random(s) * n;
const randomRotate = (n: number, s): number => random(s) * n * 2;
const randomScale = (n = 1, s): number => random(s) * n + 1;
ex... |
Use state.single to not upgrade npm | import pytest
from salt.exceptions import CommandExecutionError
@pytest.fixture(scope="module", autouse=True)
def install_npm(sminion):
try:
sminion.functions.state.single("pkg.installed", name="npm")
# Just name the thing we're looking for
sminion.functions.npm # pylint: disable=pointles... | import pytest
from salt.exceptions import CommandExecutionError
@pytest.fixture(scope="module", autouse=True)
def install_npm(sminion):
try:
sminion.functions.pkg.install("npm")
# Just name the thing we're looking for
sminion.functions.npm # pylint: disable=pointless-statement
except ... |
Change README file format from .md to .rst | """Setup script for pygoogling."""
from codecs import open as open_codec
from os import path
from setuptools import setup
HERE = path.abspath(path.dirname(__file__))
with open_codec(path.join(HERE, 'README.rst'), encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
setup(
name='pygoogling',
version='0.0.... | """Setup script for pygoogling."""
from codecs import open as open_codec
from os import path
from setuptools import setup
HERE = path.abspath(path.dirname(__file__))
with open_codec(path.join(HERE, 'README.md'), encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
setup(
name='pygoogling',
version='0.0.2... |
Make the Bing images search pick a random top 20 image. | import random
from aiohttp import BasicAuth
from plumeria import config, scoped_config
from plumeria.command import commands, CommandError
from plumeria.config.common import nsfw
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://a... | from aiohttp import BasicAuth
from plumeria import config, scoped_config
from plumeria.command import commands, CommandError
from plumeria.config.common import nsfw
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.a... |
Synchronize access to static instance in clear() | package org.apache.lucene.spatial.base.context;
import org.apache.lucene.spatial.base.context.simple.SimpleSpatialContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO -- i think there is a more standard way to approach this problem
*/
public class SpatialContextProvider {
static final Logg... | package org.apache.lucene.spatial.base.context;
import org.apache.lucene.spatial.base.context.simple.SimpleSpatialContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO -- i think there is a more standard way to approach this problem
*/
public class SpatialContextProvider {
static final Logg... |
Revert "Simplify the use of `phutil_get_library_root`"
Summary:
This reverts commit 67a17d0efb025665237d0d174d55d1887f9a6064.
This doesn't actually work because the call to `phutil_get_current_library_name()` always occurs within `libphutil`.
Test Plan: N/A
Reviewers: epriestley, #blessed_reviewers
Reviewed By: ep... | <?php
function phutil_get_library_root($library) {
$bootloader = PhutilBootloader::getInstance();
return $bootloader->getLibraryRoot($library);
}
function phutil_get_library_root_for_path($path) {
foreach (Filesystem::walkToRoot($path) as $dir) {
if (Filesystem::pathExists($dir.'/__phutil_library_init__.php... | <?php
function phutil_get_library_root($library = null) {
if (!$library) {
$library = phutil_get_current_library_name();
}
$bootloader = PhutilBootloader::getInstance();
return $bootloader->getLibraryRoot($library);
}
function phutil_get_library_root_for_path($path) {
foreach (Filesystem::walkToRoot($pa... |
client: Add server link to thumbnails. | import React from 'react';
import { Card, CardHeader, CardMedia, CardTitle } from 'material-ui/Card';
const ServerThumbnail = ({
server,
media
}) => (
<Card className="thumb">
<a href={server.url}>
<CardHeader title={server.name} subtitle={server.description} />
{media && (
<CardMedia
... | import React from 'react';
import { Card, CardHeader, CardTitle, CardMedia } from 'material-ui/Card';
const ServerThumbnail = ({
server,
media
}) => (
<Card className="thumb">
<CardHeader title={server.name} />
{media && (
<CardMedia
overlay={(
<CardTitle
title={media.... |
Add more markdown syntax detection's
Detect 'markdown gfm', 'multimarkdown' and 'markdown extended'.
Closes #2 | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2017 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
"""Provi... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2017 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
"""Provi... |
Add method to encrypt files | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
GPG = 'gpg2'
SERVER_KEY = '' # replace with gpg key ID of server key
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.tex... | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.text.pack()
menu = Menu(master)
root.config(menu=menu)
... |
Use unresolved-incidents when page-status is empty | import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status
class StatusPagePlugin(Service):
def get_status(self):
r = requests.get(self.status_url)
if r.status_code != 200:
return Status.unavailable
b = BeautifulSoup(r.conte... | import requests
from bs4 import BeautifulSoup
from isserviceup.services.models.service import Service, Status
class StatusPagePlugin(Service):
def get_status(self):
r = requests.get(self.status_url)
if r.status_code != 200:
return Status.unavailable
b = BeautifulSoup(r.conte... |
Fix type casts and incorrect numbers
Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12. | import fileinput
weekHours = 0.0
dayHours = 0.0
def calcWorkTime(timeIn, timeOut):
inSplit = timeIn.split(':')
outSplit = timeOut.split(':')
hourIn = float(inSplit[0])
minuteIn = float(inSplit[1])
hourOut = float(outSplit[0])
minuteOut = float(outSplit[1])
if hourIn > hourOut:
newHour = (hourOut + ... | import fileinput
weekHours = 0.0
dayHours = 0.0
def calcWorkTime(timeIn, timeOut):
inSplit = timeIn.split(':')
outSplit = timeOut.split(':')
hourIn = int(inSplit[0])
minuteIn = int(inSplit[1])
hourOut = int(outSplit[0])
minuteOut = int(outSplit[1])
if hourIn > hourOut:
newHour = (hourOut + 24) - ho... |
Add __all__ in package init for the test runner | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Photutils is an Astropy affiliated package to provide tools for
detecting and performing photometry of astronomical sources. It also
has tools for background estimation, ePSF building, PSF matching,
centroiding, and morphological measurements.
"""
im... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Photutils is an Astropy affiliated package to provide tools for
detecting and performing photometry of astronomical sources. It also
has tools for background estimation, ePSF building, PSF matching,
centroiding, and morphological measurements.
"""
im... |
Use Ember.get in Object Proxy
This allows the use of POJOs | import Ember from 'ember';
import RecordKeeperMixin from 'ember-time-machine/mixins/time-machine';
import Record from 'ember-time-machine/-private/Record';
import { wrapValue, unwrapValue } from 'ember-time-machine/utils/value';
import { pathInGlobs } from 'ember-time-machine/utils/utils';
const { get } = Ember;
expo... | import Ember from 'ember';
import RecordKeeperMixin from 'ember-time-machine/mixins/time-machine';
import Record from 'ember-time-machine/-private/Record';
import { wrapValue, unwrapValue } from 'ember-time-machine/utils/value';
import { pathInGlobs } from 'ember-time-machine/utils/utils';
export default Ember.ObjectP... |
Fix issue with "password" grant type, fix map order | package lv.ctco.cukes.oauth;
import lv.ctco.cukes.core.internal.context.GlobalWorldFacade;
import java.util.HashMap;
import java.util.Map;
public enum GrantType {
client_credentials,
password(OAuthCukesConstants.USER_NAME, OAuthCukesConstants.PASSWORD);
private static final Map<String, String> attribut... | package lv.ctco.cukes.oauth;
import lv.ctco.cukes.core.internal.context.GlobalWorldFacade;
import java.util.HashMap;
import java.util.Map;
public enum GrantType {
client_credentials,
password(OAuthCukesConstants.USER_NAME, OAuthCukesConstants.PASSWORD);
private static final Map<String, String> attribut... |
Print everything on individual lines | #! /usr/bin/python
from __future__ import print_function
import db, os, sys, re
import argparse
import json
from collections import namedtuple
tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host")
# Initial setup of DB
# We keep the connection & cursor seperate so we can do commits when we... | #! /usr/bin/python
from __future__ import print_function
import db, os, sys, re
import argparse
import json
from collections import namedtuple
tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host")
# Initial setup of DB
# We keep the connection & cursor seperate so we can do commits when we... |
Document project is stable and ready for use in production | #!/usr/bin/env python
from setuptools import setup
#from distutils.core import setup
setup(name='imagesize',
version='0.7.1',
description='Getting image size from png/jpeg/jpeg2000/gif file',
long_description='''
It parses image files' header and return image size.
* PNG
* JPEG
* JPEG2000
* GIF
Th... | #!/usr/bin/env python
from setuptools import setup
#from distutils.core import setup
setup(name='imagesize',
version='0.7.1',
description='Getting image size from png/jpeg/jpeg2000/gif file',
long_description='''
It parses image files' header and return image size.
* PNG
* JPEG
* JPEG2000
* GIF
Th... |
Change copyright in Apache 2 license to 2013 | /**
* Copyright © 2011-2013 EMBL - European Bioinformatics Institute
*
* 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... | /**
* Copyright © 2011-2012 EMBL - European Bioinformatics Institute
*
* 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... |
Update the package for godns | package main
import (
"net"
"dns"
)
func main() {
// A simple example. Publish an A record for my router at 192.168.1.254.
mdns.PublishA("router.local.", 3600, net.IPv4(192, 168, 1, 254))
// A more compilcated example. Publish a SVR record for ssh running on port
// 22 for my home NAS.
// Publish an A recor... | package main
import (
"net"
"github.com/davecheney/mdns"
)
func main() {
// A simple example. Publish an A record for my router at 192.168.1.254.
mdns.PublishA("router.local.", 3600, net.IPv4(192, 168, 1, 254))
// A more compilcated example. Publish a SVR record for ssh running on port
// 22 for my home NAS.... |
Remove the (dodgy) function to convert from an image to data. | """
The FVCOM Python toolbox (PyFvcom)
"""
__version__ = '1.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import numpy so we have it across the board.
import numpy as n... | """
The FVCOM Python toolbox (PyFvcom)
"""
__version__ = '1.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import numpy so we have it across the board.
import numpy as n... |
Document prerequisites for the algorithm | package algorithms.trees;
public class TreeHeightCalculator {
private final int parents[];
/**
* @param parents
* defines index of parent for each node. Value -1 determines a root node
*/
public TreeHeightCalculator(int parents[]) {
this.parents = parents;
}
/**
* assumptions: there is exactl... | package algorithms.trees;
public class TreeHeightCalculator {
private final int parents[];
/**
* @param parents
* defines index of parent for each node. Value -1 determines a root node
*/
public TreeHeightCalculator(int parents[]) {
this.parents = parents;
}
public int computeHeight() {
TreeN... |
Add another check for missing workflow | import { expeditions } from 'constants/expeditions';
const RECENT_EXPEDITIONS_LENGTH = 4;
export function findExpedition(key) {
return expeditions[key] ? expeditions[key] : expeditions.DEFAULT;
}
export const expeditionsInGroup = (group, allWorkflows) =>
allWorkflows.filter(e => e.display_name.startsWith(group))... | import { expeditions } from 'constants/expeditions';
const RECENT_EXPEDITIONS_LENGTH = 4;
export function findExpedition(key) {
return expeditions[key] ? expeditions[key] : expeditions.DEFAULT;
}
export const expeditionsInGroup = (group, allWorkflows) =>
allWorkflows.filter(e => e.display_name.startsWith(group))... |
Add length to Buffer.concat invoke
Add length to Buffer.concat invoke.
That should increase performance according to the node documenation.
If totalLength is not provided, it is calculated from the Buffer instances in list. This however causes an additional loop to be executed in order to calculate the totalLength... | const crypto = require('crypto');
const {debugLog} = require('./utilities');
/**
* memHandler - In memory upload handler
* @param {Object} options
* @param {String} fieldname
* @param {String} filename
* @returns {Object}
*/
module.exports = (options, fieldname, filename) => {
let buffers = [];
let fileSize ... | const crypto = require('crypto');
const {debugLog} = require('./utilities');
/**
* memHandler - In memory upload handler
* @param {Object} options
* @param {String} fieldname
* @param {String} filename
* @returns {Object}
*/
module.exports = (options, fieldname, filename) => {
let buffers = [];
let fileSize ... |
Fix overshadowed tests by giving test functions unique names | """
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.shop.order.models.order import PaymentState
from testfixtures.shop_order import create_order
from testfixtures.user import create_user
def test_is_open():
payment_state = PaymentState.open
... | """
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.shop.order.models.order import PaymentState
from testfixtures.shop_order import create_order
from testfixtures.user import create_user
def test_is_open():
payment_state = PaymentState.open
... |
Rename settings' `extensions.values` to `sandbox.selectionListFetchers`. | // Register 'usergroups' special setting values fetcher.
// Allows to use `values: usergroups` in setting definitions.
'use strict';
var _ = require('lodash');
module.exports = function (N) {
function usergroups(env, callback) {
N.models.users.UserGroup
.find()
.select('_id short_name')
... | // Register 'usergroups' special setting values fetcher.
// Allows to use `values: usergroups` in setting definitions.
'use strict';
var _ = require('lodash');
module.exports = function (N) {
function usergroups(env, callback) {
N.models.users.UserGroup
.find()
.select('_id short_name')
... |
Add hooks to the right place | module.exports = {
parser: "@typescript-eslint/parser",
plugins: ["react-hooks"],
extends: [
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint", // Disables rules from @typescript-eslint that would conflict with Prettier
"plugin:prettier/recommended"... | module.exports = {
parser: "@typescript-eslint/parser",
extends: [
"plugin:react/recommended",
"plugin:react-hooks",
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint", // Disables rules from @typescript-eslint that would conflict with Prettier
"plugin:prettier/recommended" /... |
DROP DATABASE IF EXISTS in tests. |
import sys
import os
import argparse
def write_csv(filename, nb_users):
with open(filename, "w") as csv_file:
csv_file.write("SEQUENTIAL\n")
for x in xrange(nb_users):
line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x))
csv_file.write(line)
def write... |
import sys
import os
import argparse
def write_csv(filename, nb_users):
with open(filename, "w") as csv_file:
csv_file.write("SEQUENTIAL\n")
for x in xrange(nb_users):
line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x))
csv_file.write(line)
def write... |
Fix Nest Leafs on Energy page
Remove GROUP BY date(date) ORDER BY date ASC
Old sql included a group by date that resulted in there always being one leaf per day (if any) | <?php
$ini = parse_ini_file("params.ini", true);
date_default_timezone_set($ini['common']['timezone']);
$date = date('Y-m-d H:i:s', time());
$connection = mysqli_connect($ini['mysql']['mysql_hostname'],$ini['mysql']['mysql_username'],$ini['mysql']['mysql_password'],$ini['mysql']['mysql_database'])
or die("Connectio... | <?php
$ini = parse_ini_file("params.ini", true);
date_default_timezone_set($ini['common']['timezone']);
$date = date('Y-m-d H:i:s', time());
$connection = mysqli_connect($ini['mysql']['mysql_hostname'],$ini['mysql']['mysql_username'],$ini['mysql']['mysql_password'],$ini['mysql']['mysql_database'])
or die("Connectio... |
Fix incorrect column in IndexFile model
* Change `reference` to `index`.
* Removed unused import of `enum` | from sqlalchemy import Column, Enum, Integer, String
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store new index fil... | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store n... |
Fix for webpack output location on CI server (part deux) | const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
// webpack folder's entry js - excluded from jekll's build process.
entry: './webpack/entry.js',
output: {
// we're going to put the generated file in the assets folder so jekyll will grab it.
path:... | const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
// webpack folder's entry js - excluded from jekll's build process.
entry: './webpack/entry.js',
output: {
// we're going to put the generated file in the assets folder so jekyll will grab it.
path:... |
Clear payment type form data after succesfully saving a modified payment type | import { takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';
import {
MODIFY_PAYMENTTYPE_REQUEST,
MODIFY_PAYMENTTYPE_RECEIVE,
MODIFY_PAYMENTTYPE_FAILURE,
CLEAR_PAYMENT_TYPE_FORM,
} from '../actiontypes';
function doModifyPaymenttype(paymenttype) {
return axios.post('/ukelo... | import { takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';
import {
MODIFY_PAYMENTTYPE_REQUEST,
MODIFY_PAYMENTTYPE_RECEIVE,
MODIFY_PAYMENTTYPE_FAILURE,
} from '../actiontypes';
function doModifyPaymenttype(paymenttype) {
return axios.post('/ukelonn/api/admin/paymenttype/modi... |
Create tables on application start | import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
import virtool.models
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param pos... | import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_strin... |
Allow for setting path as part of options object as well as as a function parameter | var path = require('path'),
static = require('serve-static');
module.exports = {
setup: function (app, assetpath, options) {
if (arguments.length === 2 && typeof assetpath === 'object') {
options = assetpath;
assetpath = '';
}
options = options || {};
a... | var path = require('path'),
static = require('serve-static');
module.exports = {
setup: function (app, assetpath, options) {
if (arguments.length === 2 && typeof assetpath === 'object') {
options = assetpath;
assetpath = '';
}
assetpath = assetpath || '/govuk-a... |
Remove cards == [] from Deck() | var Deck = function() {
this.cards = [];
};
Deck.prototype.addCard = function(card) {
this.cards.push(card);
};
Deck.prototype.nextCard = function(card) {
return this.cards.pop();
};
Deck.prototype.fetchCards = function() {
var request = $.ajax({
method: 'POST',
url: '/decks/new',
data: $("input"... | var Deck = function(cards = []) {
this.cards = cards;
};
Deck.prototype.addCard = function(card) {
this.cards.push(card);
};
Deck.prototype.nextCard = function(card) {
return this.cards.pop();
};
Deck.prototype.fetchCards = function() {
var request = $.ajax({
method: 'POST',
url: '/decks/new',
da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.