text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add method to get the right block type from a module extra | <?php
namespace Backend\Modules\Pages\Domain\ModuleExtra;
use Backend\Modules\Pages\Domain\PageBlock\Type;
use Common\Exception\InvalidModuleExtraType;
use JsonSerializable;
final class ModuleExtraType implements JsonSerializable
{
private const BLOCK = 'block';
private const WIDGET = 'widget';
public co... | <?php
namespace Backend\Modules\Pages\Domain\ModuleExtra;
use Common\Exception\InvalidModuleExtraType;
use JsonSerializable;
final class ModuleExtraType implements JsonSerializable
{
private const BLOCK = 'block';
private const WIDGET = 'widget';
public const POSSIBLE_TYPES = [
self::BLOCK,
... |
Fix bad encoding in boilerplate | # Copyright 2015 IBM Corp. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2015 IBM Corp. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
Fix Django version check for 1.10 | # -*- encoding: utf-8 -*-
import django
from django.test import TestCase
from django.core.management import call_command
if django.VERSION >= (1, 7):
from django.test import override_settings
from django.apps import apps
initial_data_fixture = 'initial_data_modern'
clear_app_cache = apps.clear_cache
e... | # -*- encoding: utf-8 -*-
from django import get_version
from django.test import TestCase
from django.core.management import call_command
if get_version().split('.') >= ['1', '7']:
from django.test import override_settings
from django.apps import apps
initial_data_fixture = 'initial_data_modern'
clear... |
Remove unused variables and fields | package io.tracee.contextlogger.jaxws.container;
import io.tracee.Tracee;
import io.tracee.TraceeBackend;
import io.tracee.TraceeLogger;
import io.tracee.jaxws.container.TraceeServerHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
/**
* JaxWs client side handler that detects uncaught exceptions and out... | package io.tracee.contextlogger.jaxws.container;
import io.tracee.Tracee;
import io.tracee.TraceeBackend;
import io.tracee.TraceeLogger;
import io.tracee.jaxws.container.TraceeServerHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
/**
* JaxWs client side handler that detects uncaught exceptions and out... |
Update Fasttext pretrained vectors location | import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.current... | import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.current... |
Fix bug of ssm parameter ls when name is empty | package myaws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/pkg/errors"
)
// SSMParameterLsOptions customize the behavior of the ParameterGet command.
type SSMParameterLsOptions struct {
Name string
}
// SSMParameterLs get values from SSM parameter store wit... | package myaws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/pkg/errors"
)
// SSMParameterLsOptions customize the behavior of the ParameterGet command.
type SSMParameterLsOptions struct {
Name string
}
// SSMParameterLs get values from SSM parameter store wit... |
Add mapping for age covariate. | 'use strict';
const { DEFAULT_LAMBDA } = require('../src/constants.js');
const path = require('path');
module.exports = {
/**
* This property is used to pass computation input values from the
* declaration into the computation.
*
* @todo Don't require `covariates` computation input
*
* {@link http... | 'use strict';
const { DEFAULT_LAMBDA } = require('../src/constants.js');
const path = require('path');
module.exports = {
/**
* This property is used to pass computation input values from the
* declaration into the computation.
*
* @todo Don't require `covariates` computation input
*
* {@link http... |
Update post-back script for Braintree | #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from decimal import Decimal as D
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchange... | #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
db = wi... |
Fix evaluation query on report | from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not req... | from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not req... |
Print a warning if your king is checked | package main
import (
"board"
"color"
"fmt"
"point"
)
func scanMove() (*point.Move, error) {
var file byte
var rank int
_, err := fmt.Scanf("%c%d", &file, &rank)
return point.NewMove(file, rank), err
}
func main() {
chessboard := board.NewBoard()
finish := false
now := color.White
for finish == false {... | package main
import (
"board"
"color"
"fmt"
"point"
)
func scanMove() (*point.Move, error) {
var file byte
var rank int
_, err := fmt.Scanf("%c%d", &file, &rank)
return point.NewMove(file, rank), err
}
func main() {
chessboard := board.NewBoard()
finish := false
now := color.White
for finish == false {... |
Fix picked color sometimes undefined |
var squares = document.querySelectorAll(".square");
var colors = [];
for (var i = squares.length - 1; i >= 0; i--) {
colors.push(getRandomRGB());
}
var pickedColor = colors[getRandomInt(0, colors.length)];
var h1 = document.querySelector('h1');
var t = document.createTextNode(' ' + pickedColor);
h1.appendChild(t);... |
var squares = document.querySelectorAll(".square");
var colors = [];
for (var i = squares.length - 1; i >= 0; i--) {
colors.push(getRandomRGB());
}
var pickedColor = colors[getRandomInt(0, colors.length + 1)];
var h1 = document.querySelector('h1');
var t = document.createTextNode(' ' + pickedColor);
h1.appendChild... |
Check before calling a function | module.exports = {
add: add,
get: get,
isSupported: isSupported
};
var rules = {};
// Functions should return the string to be appended to a key to find the pluralized
// form for the count given.
function add(lng, fn) {
fn.memo = [];
rules[lng] = function(count) {
return fn.memo[count] ||... | module.exports = {
add: add,
get: get,
isSupported: isSupported
};
var rules = {};
// Functions should return the string to be appended to a key to find the pluralized
// form for the count given.
function add(lng, fn) {
fn.memo = [];
rules[lng] = function(count) {
return fn.memo[count] ||... |
Raise TypeError instead of returning | #!/usr/bin/env python
class RequiresType(object):
"""
Checks that the first (or position given by the keyword argument 'position'
argument to the function is an instance of one of the types given in the
positional decorator arguments
"""
def __init__(self, *types, **kwargs):
self.type... | #!/usr/bin/env python
class RequiresType(object):
"""
Checks that the first (or position given by the keyword argument 'position'
argument to the function is an instance of one of the types given in the
positional decorator arguments
"""
def __init__(self, *types, **kwargs):
self.type... |
Remove Fork cms copyright comment | <?php
namespace Frontend\Modules\Instagram\Engine;
use Frontend\Core\Engine\Model as FrontendModel;
/**
* The frontend Instagram Model
*
* @author Jesse Dobbelaere <jesse@dobbelae.re>
*/
class Model
{
/**
* Fetches a certain item
*
* @param string $id
* @return array
*/
public st... | <?php
namespace Frontend\Modules\Instagram\Engine;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Frontend\Core\Engine\Model as FrontendModel;
/**
* The frontend Instagram Model
*
* @au... |
Tidy up info a little for the PluginModule popup edit form
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40384 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to... | <?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to... |
Change logging to use standard logging library. | __author__ = 'Matt Stibbs'
__version__ = '1.27.00'
target_schema_version = '1.25.00'
from flask import Flask
import logging
logger = logging.getLogger(__name__)
app = Flask(__name__)
import blockbuster.bb_auditlogger as audit
def startup():
import blockbuster.bb_dbconnector_factory
blockbuster.app.debug =... | __author__ = 'Matt Stibbs'
__version__ = '1.27.00'
target_schema_version = '1.25.00'
from flask import Flask
app = Flask(__name__)
def startup():
import blockbuster.bb_dbconnector_factory
import blockbuster.bb_logging as log
import blockbuster.bb_auditlogger as audit
blockbuster.app.debug = blockbus... |
Set code push install mode to immediate | // @flow
import CodePush from 'react-native-code-push';
import { AppRegistry, YellowBox } from 'react-native';
import {
SingleHotelStandalonePackage,
NewHotelsStandAlonePackage,
} from '@kiwicom/react-native-app-hotels';
// TODO: please check if it's still needed
YellowBox.ignoreWarnings([
// react-native-share... | // @flow
import CodePush from 'react-native-code-push';
import { AppRegistry, YellowBox } from 'react-native';
import {
SingleHotelStandalonePackage,
NewHotelsStandAlonePackage,
} from '@kiwicom/react-native-app-hotels';
// TODO: please check if it's still needed
YellowBox.ignoreWarnings([
// react-native-share... |
Use tempdir to ensure there will always be a directory which can be accessed. | '''
Tests for the file state
'''
# Import python libs
# Import salt libs
import integration
import tempfile
class CMDTest(integration.ModuleCase):
'''
Validate the cmd state
'''
def test_run(self):
'''
cmd.run
'''
ret = self.run_state('cmd.run', name='ls', cwd=tempfil... | '''
Tests for the file state
'''
# Import python libs
import os
#
# Import salt libs
from saltunittest import TestLoader, TextTestRunner
import integration
from integration import TestDaemon
class CMDTest(integration.ModuleCase):
'''
Validate the cmd state
'''
def test_run(self):
'''
c... |
Make version format PEP 440 compatible | import re
import sys
from collections import namedtuple
from .client import Elasticsearch
__all__ = ('Elasticsearch',)
__version__ = '0.1.0a'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_v... | import re
import sys
from collections import namedtuple
from .client import Elasticsearch
__all__ = ('Elasticsearch',)
__version__ = '0.1.0a'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_v... |
Increment version for memory stores | from os import path
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(path.join(pa... | from os import path
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(path.join(pa... |
Add specific Resource bundle management | package woko.actions;
import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class WokoResourceBundle extends ResourceBundle {
private static final String WOKO_RESOURCES_BUNDLE = "WokoResources";
private static final String AP... | package woko.actions;
import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class WokoResourceBundle extends ResourceBundle {
private Locale locale;
public WokoResourceBundle(Locale locale) {
this.locale = locale;
}
@Ov... |
Use the proper temp dir
closes #964 | package steps
import (
"log"
"os"
"path"
"regexp"
"github.com/Originate/git-town/src/git"
)
// Step represents a dedicated activity within a Git Town command.
// Git Town commands are comprised of a number of steps that need to be executed.
type Step interface {
CreateAbortStep() Step
CreateContinueStep() Ste... | package steps
import (
"fmt"
"log"
"regexp"
"github.com/Originate/git-town/src/git"
)
// Step represents a dedicated activity within a Git Town command.
// Git Town commands are comprised of a number of steps that need to be executed.
type Step interface {
CreateAbortStep() Step
CreateContinueStep() Step
Crea... |
Add complexity in tilde notation. | package com.jeffreydiaz.search;
/**
* Implementation of the classic Linear Search algorithm.
* Complexity: ~N
* @author Jeffrey Diaz
*/
public class LinearSearch {
/**
* Linearly search for item elem in array items.
* @param items an array of Item objects who've implemented the equals method.
* @param elem... | package com.jeffreydiaz.search;
/**
* Implementation of the classic Linear Search algorithm.
* @author Jeffrey Diaz
*/
public class LinearSearch {
/**
* Linearly search for item elem in array items.
* @param items an array of Item objects who've implemented the equals method.
* @param elem item to search ar... |
[Telemetry] Fix profile generation after r275633.
TBR=dtu@chromium.org
NOTRY=True
BUG=
Review URL: https://codereview.chromium.org/323703003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@275689 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.
from telemetry.page import profile_creator
import page_sets
class SmallProfileCreator(profile_creator.ProfileCreator):
"""
Runs a browser through a se... | # 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.
from telemetry.page import profile_creator
import page_sets
class SmallProfileCreator(profile_creator.ProfileCreator):
"""
Runs a browser through a se... |
Make the website nav header's hysteresis a bit more robust
In particular, this prevents the nav header from reappearing all the
time while scrolling down on Firefox. | //- ----------------------------------
//- 💫 MAIN JAVASCRIPT
//- ----------------------------------
'use strict'
{
const nav = document.querySelector('.js-nav')
const fixedClass = 'is-fixed'
let vh, scrollY = 0, scrollUp = false
const updateVh = () => Math.max(document.documentElement.clientHeight, ... | //- ----------------------------------
//- 💫 MAIN JAVASCRIPT
//- ----------------------------------
'use strict'
{
const nav = document.querySelector('.js-nav')
const fixedClass = 'is-fixed'
let vh, scrollY = 0, scrollUp = false
const updateVh = () => Math.max(document.documentElement.clientHeight, ... |
FIX typo error on comments | package villa;
// CmpFunc is the function compares two elements.
type CmpFunc func(interface{}, interface{}) int
// IntCmpFunc is the function compares two int elements.
type IntCmpFunc func(int, int) int
// FloatCmpFunc is the function compares two float elements.
type FloatCmpFunc func(float64, float64) int
// Co... | package villa;
// CmpFunc is the function compares two elements.
type CmpFunc func(interface{}, interface{}) int
// IntCmpFunc is the function compares two int elements.
type IntCmpFunc func(int, int) int
// FloatCmpFunc is the function compares two float elements.
type FloatCmpFunc func(float64, float64) int
// Co... |
Change to avoid "DeprecationWarning: invalid escape sequence" | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._base import VarNameSanitizer
class ElasticsearchIndexNameSanitizer(VarNameSanitizer):
__RE_INVALID_INDEX_NAME = re.compile("[" + re.escape('\\/*?... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._base import VarNameSanitizer
class ElasticsearchIndexNameSanitizer(VarNameSanitizer):
__RE_INVALID_INDEX_NAME = re.compile("[" + re.escape('\\/*?... |
Update Group API
- ADD type hints
- Remove unused imports | # stdlib
from typing import Any
from typing import Callable
# syft relative
from ...messages.group_messages import CreateGroupMessage
from ...messages.group_messages import DeleteGroupMessage
from ...messages.group_messages import GetGroupMessage
from ...messages.group_messages import GetGroupsMessage
from ...messages... | # stdlib
from typing import Any
from typing import Dict
# third party
from pandas import DataFrame
# syft relative
from ...messages.group_messages import CreateGroupMessage
from ...messages.group_messages import DeleteGroupMessage
from ...messages.group_messages import GetGroupMessage
from ...messages.group_messages ... |
Fix number going outside of level issue | function LevelController(onComplete, level) {
this.onComplete = onComplete;
this.level = level;
};
LevelController.prototype.left = function() {
if(this.level.index === 0) {
return;
}
this.level.index -= 1;
};
LevelController.prototype.right = function() {
if(this.level.index === this.level.puzzle.boa... | function LevelController(onComplete, level) {
this.onComplete = onComplete;
this.level = level;
};
LevelController.prototype.left = function() {
if( this.index === 0 ) {
return;
}
this.level.index -= 1;
};
LevelController.prototype.right = function() {
if(this.index === this.level.puzzle.board.columns... |
Set ptm return pointer to nil if it is closed. | // © 2012 Jay Weisskopf
package pty
// #include <stdlib.h>
// #include <fcntl.h>
import "C"
import "os"
func Open() (ptm *os.File, ptsName string, err error) {
ptmFd, err := C.posix_openpt(C.O_RDWR | C.O_NOCTTY)
if err != nil {
return nil, "", err
}
ptm = os.NewFile(uintptr(ptmFd), "")
defer func() {
if e... | // © 2012 Jay Weisskopf
package pty
// #include <stdlib.h>
// #include <fcntl.h>
import "C"
import "os"
func Open() (ptm *os.File, ptsName string, err error) {
ptmFd, err := C.posix_openpt(C.O_RDWR | C.O_NOCTTY)
if err != nil {
return nil, "", err
}
ptm = os.NewFile(uintptr(ptmFd), "")
defer func() {
if e... |
Fix for tests breaking on keep-alive | package android.net;
import io.reon.test.support.LocalWire;
import java.io.*;
public class LocalSocket {
private InputStream inputStream;
private OutputStream outputStream;
public LocalSocket() {
this(null, null);
}
public LocalSocket(InputStream inputStream, OutputStream outputStream) {
this.inputStrea... | package android.net;
import io.reon.test.support.LocalWire;
import java.io.*;
public class LocalSocket {
private InputStream inputStream;
private OutputStream outputStream;
public LocalSocket() {
this(null, null);
}
public LocalSocket(InputStream inputStream, OutputStream outputStream) {
this.inputStrea... |
Work around slack message limits | 'use strict';
var
bole = require('bole'),
restify = require('restify')
;
var slackClient;
var logger = bole('slack');
exports.createClient = function createClient(opts)
{
slackClient = restify.createJSONClient({ url: opts.slack });
logger.info('Slack client created')
};
exports.report = funct... | 'use strict';
var
bole = require('bole'),
restify = require('restify')
;
var slackClient;
var logger = bole('slack');
exports.createClient = function createClient(opts)
{
slackClient = restify.createJSONClient({ url: opts.slack });
logger.info('Slack client created')
};
exports.report = funct... |
Switch order (again) of legend for example | """
QuadTree: Hanging Nodes
=======================
You can give the refine method a function, which is evaluated on every
cell of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
import d... | """
QuadTree: Hanging Nodes
=======================
You can give the refine method a function, which is evaluated on every
cell of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
import d... |
Add setting of undefined rather than an empty string | import React from 'react';
import PropTypes from 'prop-types';
import { TextInput, StyleSheet } from 'react-native';
import { DARKER_GREY, LIGHT_GREY } from '../../../globalStyles/colors';
import { APP_FONT_FAMILY } from '../../../globalStyles/fonts';
import { useJSONFormOptions } from '../JSONFormContext';
export con... | import React from 'react';
import PropTypes from 'prop-types';
import { TextInput, StyleSheet } from 'react-native';
import { DARKER_GREY, LIGHT_GREY } from '../../../globalStyles/colors';
import { APP_FONT_FAMILY } from '../../../globalStyles/fonts';
import { useJSONFormOptions } from '../JSONFormContext';
export con... |
Use reflect to test time access methods on Document | package asciidocgo
import (
"fmt"
"reflect"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
var dm = new(Document).Monitor()
var dnm = new(Document)
var notMonitoredError = &NotMonitoredError{"test"}
var monitorFNames = [1]string{"ReadTime"}
func TestDocumentMonitor(t *testing.T) {
Convey("A Document c... | package asciidocgo
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
var dm = new(Document).Monitor()
var dnm = new(Document)
var notMonitoredError = &NotMonitoredError{"test"}
func TestDocumentMonitor(t *testing.T) {
Convey("A Document can be monitored", t, func() {
Convey("By default, a Docume... |
sdack-1: Add classes for simplified building of process UIs | //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complia... | //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complia... |
Move webui optional config file to the same directory DNSCheck Lib uses. | <?php
require_once('IP2Country.php');
define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'dnscheckng');
define('DB_USER', 'dnscheckng');
define('DB_PASS', 'dnscheckng');
define('STATUS_OK', 'OK');
define('STATUS_WARN', 'WARNING');
define('STATUS_ERROR', 'ERROR');
define... | <?php
require_once('IP2Country.php');
define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'dnscheckng');
define('DB_USER', 'dnscheckng');
define('DB_PASS', 'dnscheckng');
define('STATUS_OK', 'OK');
define('STATUS_WARN', 'WARNING');
define('STATUS_ERROR', 'ERROR');
define... |
Update the PyPI version to 0.2.5. | # -*- 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.5',
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.4',
packages=['todoist', 'todoist.managers'],
author='Doist Team'... |
Add directory (auto-populates if running in a sub-directory) to assets path in main template | <?php
namespace CRD\Core;
$resources = $template->resources;
$html = $template->html;
$app = $template->view->app;
$router = $app->router;
?><!doctype html>
<html lang="<?= $html->entities($resources->locale) ?>">
<head>
<meta charset="utf-8">
<title><?= $html->entities(((!empty($template->title... | <?php
namespace CRD\Core;
$resources = $template->resources;
$html = $template->html;
$app = $template->view->app;
?><!doctype html>
<html lang="<?= $html->entities($resources->locale) ?>">
<head>
<meta charset="utf-8">
<title><?= $html->entities(((!empty($template->title))? $template->title . ' —... |
Add hostname to avahi_pub advertisement method | var os = require('os'),
hostname = os.hostname(),
serviceName = 'radiodan-http';
if(process.platform === 'linux') {
var avahi = require('avahi_pub');
module.exports.advertise = function(radiodan, port) {
radiodan.create().player.discover().then(function(players) {
var txtRecord = { players: JSON... | var serviceName = 'radiodan-http';
if(process.platform === 'linux') {
var avahi = require('avahi_pub');
module.exports.advertise = function(radiodan, port) {
radiodan.create().player.discover().then(function(players) {
var txtRecord = { players: JSON.stringify(players) },
service = {
... |
Fix destination at create account | var baseUrl = "http://marihachi.php.xdomain.jp/crystal-resonance";
$(function() {
// ログイン処理
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/login", {
type: 'post',
data: $('#login-form').serialize(),
dataType: 'json',
}).done(function() {
location.reload();
... | var baseUrl = "http://marihachi.php.xdomain.jp/crystal-resonance";
$(function() {
// ログイン処理
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax(baseUrl + "/api/account/login", {
type: 'post',
data: $('#login-form').serialize(),
dataType: 'json',
}).done(function() {
location.reload();
... |
Add class to footer widget headings. | <?php
/**
* Register widget areas
*
* @package FoundationPress
* @since FoundationPress 1.0.0
*/
if ( ! function_exists( 'foundationpress_sidebar_widgets' ) ) :
function foundationpress_sidebar_widgets() {
register_sidebar(array(
'id' => 'sidebar-widgets',
'name' => __( 'Sidebar widgets', 'foundationpress'... | <?php
/**
* Register widget areas
*
* @package FoundationPress
* @since FoundationPress 1.0.0
*/
if ( ! function_exists( 'foundationpress_sidebar_widgets' ) ) :
function foundationpress_sidebar_widgets() {
register_sidebar(array(
'id' => 'sidebar-widgets',
'name' => __( 'Sidebar widgets', 'foundationpress'... |
Return ok for favicon requests | package main
import (
"log"
"net/http"
"os"
)
type Config struct {
port string
allowedContentTypes string // uncompiled regex
}
func envOrDefault(key string, default_value string) string {
env := os.Getenv(key)
if env != "" {
return env
} else {
return default_value
}
}
func main() {
co... | package main
import (
"log"
"net/http"
"os"
)
type Config struct {
port string
allowedContentTypes string // uncompiled regex
}
func envOrDefault(key string, default_value string) string {
env := os.Getenv(key)
if env != "" {
return env
} else {
return default_value
}
}
func main() {
co... |
Use customElement in chatOutput component | "use strict";
let element = require("../../lib/customElement");
let ChatOutput = element.define("chat-output", {
style: require("./chatOutput.styl"),
template: require("./chatOutput.mustache"),
scope: {
log: [],
debug: false
},
helpers: {
renderEntryGroup: renderEntryGroup
}
});
let entryTemp... | "use strict";
let can = require("../../shims/can");
let style = require("../../lib/ensureStyle"),
viewCss = require("./chatOutput.styl");
let chatTemplate = require("./chatOutput.mustache");
let entryTemplates = {
system: require("./entries/system.mustache"),
dialogue: require("./entries/dialogue.mustache"),... |
Test case for Mapper injection (fail) | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless req... | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless req... |
Check if deletedDocument are same than the original document | 'use strict';
var async = require('async');
var crypto = require('crypto');
var Anyfetch = require('anyfetch');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} original document
* @param {object} changes object provided by anyFetch's API. Update this object to send ... | 'use strict';
var async = require('async');
var crypto = require('crypto');
var Anyfetch = require('anyfetch');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} original document
* @param {object} changes object provided by anyFetch's API. Update this object to send ... |
Add support for new(er) smartCampaigns endpoints. | var _ = require('lodash'),
Promise = require('bluebird'),
util = require('../util'),
log = util.logger();
function Campaign(marketo, connection) {
this._marketo = marketo;
this._connection = connection;
}
Campaign.prototype = {
request: function(campaignId, leads, tokens, options) {
if (!_.isArr... | var _ = require('lodash'),
Promise = require('bluebird'),
util = require('../util'),
log = util.logger();
function Campaign(marketo, connection) {
this._marketo = marketo;
this._connection = connection;
}
Campaign.prototype = {
request: function(campaignId, leads, tokens, options) {
if (!_.isArr... |
Add try-catch as safeguard against potentionally misbehaving parser | /*
* Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
*
* 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 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
*
* 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... |
Add a 'b()' utility for forcing encoding to bytes.
In Python2, the 'bytes()' builtin doesn't take an encoding argument. | try:
TEXT = unicode
except NameError: #pragma NO COVER Py3k
TEXT = str
STRING_TYPES = (str, bytes)
def b(x, encoding='ascii'):
return bytes(x, encoding)
else: #pragma NO COVER Python2
STRING_TYPES = (unicode, bytes)
def b(x, encoding='ascii'):
if isinstance(x, unicode):
... | try:
TEXT = unicode
except NameError: #pragma NO COVER Py3k
TEXT = str
STRING_TYPES = (str, bytes)
else: #pragma NO COVER Python2
STRING_TYPES = (unicode, bytes)
def u(x, encoding='ascii'):
if isinstance(x, TEXT): #pragma NO COVER
return x
try:
return x.decode(encoding)
exce... |
Update test files to remove in teardown script
Drops HDF5 files that are no longer generated during routine testing
from teardown. Also adds Dask's workspace directory for cleanup. | #!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"data.tif",
"data.h5",
"data_traces.h5",
"data_rois.h5",
"data.zarr",
"data_trim.zarr",
"data_dn.zarr",
"data_reg.zarr",
"data_sub... | #!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"data.tif",
"data.h5",
"data_trim.h5",
"data_dn.h5",
"data_reg.h5",
"data_sub.h5",
"data_f_f0.h5",
"data_wt.h5",
"data_norm.h5",
... |
Add Search form for mobile devices | <?php get_header(); ?>
<head><title><?php bloginfo('name'); echo ' - '; bloginfo('description');?></title></head>
<div class="container">
<div class="col-md-9">
<div class = "hidden-lg hidden-md"> <?php get_search_form(); ?> </div>
<?php if (have_posts()) : while(have_posts()) : the_post();?>
<div class="ro... | <?php get_header(); ?>
<head><title><?php bloginfo('name'); echo ' - '; bloginfo('description');?></title></head>
<div class="container">
<div class="col-md-9">
<?php if (have_posts()) : while(have_posts()) : the_post();?>
<div class="row shadow-box">
<a href="<?php the_permalink();?>" title = "<?php the_... |
Allow active element selection for REST routing. | $(function() {
$('#side-menu').metisMenu();
});
//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
$(window).bind("load resize", function() {
topOffset = 50;
width = (this.window.innerWidt... | $(function() {
$('#side-menu').metisMenu();
});
//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
$(window).bind("load resize", function() {
topOffset = 50;
width = (this.window.innerWidt... |
HTCONDOR-1028: Allow Jira tickets over 1000
This used to double check between GitTrac and Jira ticket numbers.
I was tempted to remove the check altogether. However, it would
guard against and unfortunate key bounce. The change is going into
stable, so adding a digit to the number is a minimal change. | import os
import sys
from docutils import nodes
from docutils.parsers.rst import Directive
def make_link_node(rawtext, app, type, slug, options):
"""Create a link to a JIRA ticket.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issue... | import os
import sys
from docutils import nodes
from docutils.parsers.rst import Directive
def make_link_node(rawtext, app, type, slug, options):
"""Create a link to a JIRA ticket.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issue... |
Fix py3 x64 crash thread related
Change-Id: Iac00ea2463df4346ad60a17d0ba9a2af089c87cd | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... |
Add CORS headers to js files for local dev | """
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers imp... | """
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers imp... |
Correct demo so it actually works | /*
Examples
Author: Addy Osmani
See: http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders
for more information on the module loader proposal
*/
//Module: Define a new module
var module = new Module({test:'hello'});
console.log(module);
//System (pre-configured Loader)
System.import('js/test1', function(t... | /*
Examples
Author: Addy Osmani
See: http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders
for more information on the module loader proposal
*/
//Module: Define a new module
var module = new Module({test:'hello'});
console.log(module);
//System (pre-configured Loader)
System.import('js/test1.js', functio... |
Copy the node options too. | 'use strict'
const common = require('./webpack.common')
const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const config = {
devtool: 'cheap-module-source-map',
entry: common.entry,
... | 'use strict'
const common = require('./webpack.common')
const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const config = {
devtool: 'cheap-module-source-map',
entry: common.entry,
... |
Fix class name in test file | from robot.conf import Language
class Custom(Language):
setting_headers = {'H 1'}
variable_headers = {'H 2'}
test_case_headers = {'H 3'}
task_headers = {'H 4'}
keyword_headers = {'H 5'}
comment_headers = {'H 6'}
library = 'L'
resource = 'R'
variables = 'V'
documentation = 'S 1'... | from robot.conf import Language
class Fi(Language):
setting_headers = {'H 1'}
variable_headers = {'H 2'}
test_case_headers = {'H 3'}
task_headers = {'H 4'}
keyword_headers = {'H 5'}
comment_headers = {'H 6'}
library = 'L'
resource = 'R'
variables = 'V'
documentation = 'S 1'
... |
Add fix for period syncing | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Methods to create internal records from a requested
* sync/external record. Used primarily by
* createOrUpdateRecord in incomingSyncUtils.
*/
import { parseBoolean, parseDate } from './incomingSyncUtils';
export const createPeriodInternalRec... | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Methods to create internal records from a requested
* sync/external record. Used primarily by
* createOrUpdateRecord in incomingSyncUtils.
*/
import { parseBoolean, parseDate } from './incomingSyncUtils';
export const createPeriodInternalRec... |
Add more databases for transaction thingy | <?php
/**
* Copyright 2015-2017 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero G... | <?php
/**
* Copyright 2015-2017 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero G... |
CC-5781: Upgrade script for new storage quota implementation | <?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(... | <?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(... |
Copy arguments only when necessary | import _isArray from './_isArray.js';
import _isTransformer from './_isTransformer.js';
/**
* Returns a function that dispatches with different strategies based on the
* object in list position (last argument). If it is an array, executes [fn].
* Otherwise, if it has a function with one of the given method names, ... | import _isArray from './_isArray.js';
import _isTransformer from './_isTransformer.js';
/**
* Returns a function that dispatches with different strategies based on the
* object in list position (last argument). If it is an array, executes [fn].
* Otherwise, if it has a function with one of the given method names, ... |
Add lazy loading also to pills | /**
* Lazy-loaded tabs
*/
jQuery(function() {
$('.nav.nav-tabs, .nav.nav-pills').on('click', '[data-url]', function(event) {
var loader = $(this);
if (loader.data('loaded'))
return;
var target = $(loader.attr('href')); // It's an #anchor
$.ajax({
url: loader.data('url'),
be... | /**
* Lazy-loaded tabs
*/
jQuery(function() {
$('.nav.nav-tabs').on('click', '[data-url]', function(event) {
var loader = $(this);
if (loader.data('loaded'))
return;
var target = $(loader.attr('href')); // It's an #anchor
$.ajax({
url: loader.data('url'),
beforeSend: functi... |
Add error message for " | 'use strict';
var kmp = require('kmp-matcher').kmp;
module.exports = function (query) {
if (!query.length) {
return [];
}
if (query.indexOf('"') >= 0) {
throw new Error('Unimplemented: can\'t match "');
}
var xpathResult = document.evaluate('//text()[contains(.,"' + query + '")]',
... | 'use strict';
var kmp = require('kmp-matcher').kmp;
module.exports = function (query) {
if (!query.length) {
return [];
}
var xpathResult = document.evaluate('//text()[contains(.,"' + query + '")]',
document, null, XPathResult.ANY_TYPE, null);
var result = [];
var... |
Add method to get AttributeReader for specific attribute as well as ability to determine namespaces for a given prefix
git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@888 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba | package org.codehaus.xfire.aegis;
import javax.xml.namespace.QName;
/**
* A MessageReader. You must call getNextChildReader() until hasMoreChildReaders()
* returns false.
*
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public interface MessageReader
{
public String getValue();
... | package org.codehaus.xfire.aegis;
import javax.xml.namespace.QName;
/**
* A MessageReader. You must call getNextChildReader() until hasMoreChildReaders()
* returns false.
*
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public interface MessageReader
{
public String getValue();
... |
Make it work with VIM | // Native
const fs = require('fs')
const path = require('path')
const styles = fs.readFileSync(path.join(__dirname, 'styles.css'), 'utf8')
const colors = {
yellow: '#afaf00',
lightGreen: '#30de04'
}
exports.decorateConfig = config => Object.assign({}, config, {
padding: '7px 7px',
backgroundColor: '#fff',
... | // Native
const fs = require('fs')
const path = require('path')
const styles = fs.readFileSync(path.join(__dirname, 'styles.css'), 'utf8')
const colors = {
yellow: '#afaf00',
lightGreen: '#30de04'
}
exports.decorateConfig = config => Object.assign({}, config, {
padding: '7px 7px',
backgroundColor: '#fff',
... |
Make GPU mem split optional | #!/usr/bin/env python
from utils import file_templates
from utils.validation import is_valid_gpu_mem
def main():
user_input = raw_input("Want to change the GPU memory split? (Y/N): ")
if user_input == 'Y':
gpu_mem = 0
while gpu_mem == 0:
mem_split = raw_input("Enter GPU memory in MB (16/32/64/128/256): ")
... | #!/usr/bin/env python
from utils import file_templates
from utils.validation import is_valid_gpu_mem
def main():
gpu_mem = 0
while gpu_mem == 0:
user_input = raw_input("Enter GPU memory in MB (16/32/64/128/256): ")
if is_valid_gpu_mem(user_input):
gpu_mem = user_input
else:
print("Acceptable memory valu... |
Use new-password as autocomplete on share auth page
Fixes #6821
This makes sure that (supported) browsers will not prefill the password
field if a user has a password saved for that nextcloud.
Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl> | <?php
/** @var $_ array */
/** @var $l \OCP\IL10N */
style('files_sharing', 'authenticate');
script('files_sharing', 'authenticate');
?>
<form method="post">
<fieldset class="warning">
<?php if (!isset($_['wrongpw'])): ?>
<div class="warning-info"><?php p($l->t('This share is password-protected')); ?></div>
... | <?php
/** @var $_ array */
/** @var $l \OCP\IL10N */
style('files_sharing', 'authenticate');
script('files_sharing', 'authenticate');
?>
<form method="post">
<fieldset class="warning">
<?php if (!isset($_['wrongpw'])): ?>
<div class="warning-info"><?php p($l->t('This share is password-protected')); ?></div>
... |
Added: Support for the GitHub Updater. | <?php
/**
* Plugin Name: Geo Query
* Description: Modify the WP_Query to support the geo_query parameter. Uses the Haversine SQL implementation by Ollie Jones.
* Plugin URI: https://github.com/birgire/geo-query
* GitHub Plugin URI: https://github.com/birgire/geo-query.git
* Author: Birgir ... | <?php
/**
* Plugin Name: Geo Query
* Description: Modify the WP_Query to support the geo_query parameter. Uses the Haversine SQL implementation by Ollie Jones.
* Plugin URI: https://github.com/birgire/geo-query
* Author: Birgir Erlendsson (birgire)
* Version: 0.0.1
* Licence: MIT
*/
namespace Birgir\Ge... |
Make fastboot transform actually work | /* eslint-env node */
'use strict';
const fastbootTransform = require('fastboot-transform');
const filesToImport = [
'dependencyLibs/inputmask.dependencyLib.js',
'inputmask.js',
'inputmask.extensions.js',
'inputmask.date.extensions.js',
'inputmask.numeric.extensions.js',
'inputmask.phone.extensions.js'
];... | /* eslint-env node */
'use strict';
const fastbootTransform = require('fastboot-transform');
const filesToImport = [
'dependencyLibs/inputmask.dependencyLib.js',
'inputmask.js',
'inputmask.extensions.js',
'inputmask.date.extensions.js',
'inputmask.numeric.extensions.js',
'inputmask.phone.extensions.js'
];... |
Print a nicer error messages on startup | package main
import (
"log"
"os"
"github.com/arachnist/gorepost/bot"
"github.com/arachnist/gorepost/config"
"github.com/arachnist/gorepost/irc"
)
func main() {
var exit chan struct{}
if len(os.Args) < 2 {
log.Fatalln("Usage:", os.Args[0], "<config-file.json>")
}
config, err := config.ReadConfig(os.Args[1... | package main
import (
"fmt"
"log"
"os"
"github.com/arachnist/gorepost/bot"
"github.com/arachnist/gorepost/config"
"github.com/arachnist/gorepost/irc"
)
func main() {
var exit chan struct{}
config, err := config.ReadConfig(os.Args[1])
if err != nil {
fmt.Println("Error reading configuration from", os.Args... |
Switch from render to hydrate on the client side | import React from 'react';
import {
ApolloClient,
ApolloProvider,
createNetworkInterface,
} from 'react-apollo';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import initStore from '../shared/store';
import Routes from './routes';
require('offline-plugin/runtime').ins... | import React from 'react';
import {
ApolloClient,
ApolloProvider,
createNetworkInterface,
} from 'react-apollo';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import initStore from '../shared/store';
import Routes from './routes';
require('offline-plugin/runtime').ins... |
Fix object subkeys, make tests pass | /**
* Filters out all duplicate items from an array by checking the specified key
* @param [key] {string} the name of the attribute of each object to compare for uniqueness
if the key is empty, the entire object will be compared
if the key === false then no filtering will be performed
* @return {array}
*/
angular... | /**
* Filters out all duplicate items from an array by checking the specified key
* @param [key] {string} the name of the attribute of each object to compare for uniqueness
if the key is empty, the entire object will be compared
if the key === false then no filtering will be performed
* @return {array}
*/
angular... |
Call _super in beforeModel hook | import Ember from 'ember';
const {
Route,
inject: {
service
}
} = Ember;
export default Route.extend({
logger: service(),
smt: service(),
beforeModel() {
this._super(...arguments);
// See a list of allowed types in logger.js
// Add or remove all your log types here:
// this.get('logge... | import Ember from 'ember';
const {
Route,
inject: {
service
}
} = Ember;
export default Route.extend({
logger: service(),
smt: service(),
beforeModel() {
// See a list of allowed types in logger.js
// Add or remove all your log types here:
// this.get('logger').addToLogs('message');
/... |
Remove space from blank line for unit-tests | import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'un... | import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'un... |
Set default default number of items to 0 (ignore) | public function getPaginationCustomPageSize()
{
return <?php echo $this->asPhp(isset($this->config['get']['pagination_custom_page_size']) ? $this->config['get']['pagination_custom_page_size'] : false) ?>;
<?php unset($this->config['get']['pagination_custom_page_size']) ?>
}
public function getPaginationEna... | public function getPaginationCustomPageSize()
{
return <?php echo $this->asPhp(isset($this->config['get']['pagination_custom_page_size']) ? $this->config['get']['pagination_custom_page_size'] : false) ?>;
<?php unset($this->config['get']['pagination_custom_page_size']) ?>
}
public function getPaginationEna... |
Make proud topbar id unique | <?php if ( $topbar_logo || $topbar_title ): ?>
<ul class="logo-menu list-unstyled clearfix">
<?php if ( $topbar_logo ): ?>
<li class="h3">
<a href="<?php echo get_logo_link_url(); ?>" title="Home" rel="home" id="header-logo-topbar" class="nav-logo same-window">
... | <?php if ( $topbar_logo || $topbar_title ): ?>
<ul class="logo-menu list-unstyled clearfix">
<?php if ( $topbar_logo ): ?>
<li class="h3">
<a href="<?php echo get_logo_link_url(); ?>" title="Home" rel="home" id="header-logo" class="nav-logo same-window">
<?php... |
Include a nonce in the reply address.
We'll probably want to use just hashes here instead of nonces. Actually, come to think of it, we don't need time-based hashes at all, since email is presumed secure and we're not preventing CSRF.
I'll change this. :) | <?php
class bbSubscriptions_Handler_Lamson implements bbSubscriptions_Handler {
public function __construct() {
}
public static function send_mail($user, $subject, $content, $headers, $attrs) {
extract($attrs);
// For some stupid reason, a lot of plugins override 'From:'
// without checking if it's the d... | <?php
class bbSubscriptions_Handler_Lamson implements bbSubscriptions_Handler {
public function __construct() {
}
public static function send_mail($user, $subject, $content, $headers, $attrs) {
extract($attrs);
// For some stupid reason, a lot of plugins override 'From:'
// without checking if it's the d... |
Fix the examples and use the same names
Signed-off-by: Fabio José <34f3a7e4e4d9fe971c99ebc4af947a5309eca653@gmail.com> | var express = require("express");
var app = express();
const Unmarshaller02 = require("cloudevents-sdk/http/unmarshaller/v02");
var unmarshaller = new Unmarshaller02();
app.use((req, res, next) => {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
... | var express = require("express");
var app = express();
const Unmarshaller02 = require("cloudevents-sdk/http/unmarshaller/v02");
var unmarshaller = new Unmarshaller02();
app.use((req, res, next) => {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
... |
Use authorize instead of enforce for policies
After fully implementing policies in code, the authorize method
can be safely used and its a safeguard against introducing
policies for some API which are not properly defined in the code.
Change-Id: I499f13c34027b217bf1de905f829f36ef919e3b8 | #
# Copyright (c) 2014 Mirantis 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 applicable law o... | #
# Copyright (c) 2014 Mirantis 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 applicable law o... |
Normalize emiited peerjs id's with a plus sign | 'use strict';
import { log, LOG_TYPES } from './log';
import config from './config';
import { io, EVENT_TYPES } from './socketIO';
let peerJSOptions = config.peerJSOptions;
export default function (server, app) {
let ExpressPeerServer = require('peer').ExpressPeerServer(server, peerJSOptions);
ExpressPeer... | 'use strict';
import { log, LOG_TYPES } from './log';
import config from './config';
import { io, EVENT_TYPES } from './socketIO';
let peerJSOptions = config.peerJSOptions;
export default function (server, app) {
let ExpressPeerServer = require('peer').ExpressPeerServer(server, peerJSOptions);
ExpressPeer... |
Revert "increasing result queue TTL"
This reverts commit 488a377b9702090275a33a335ceb90a89e6ed6f5. | package xing
// Constants
const (
// Type
Command = "command"
Event = "event"
Result = "result"
// Event
Register = "Register"
// Exchanges
RPCExchange = "xing.rpc"
EventExchange = "xing.event"
// Client Types
ProducerClient = "producer"
ServiceClient = "service"
EventHandlerClient = "... | package xing
// Constants
const (
// Type
Command = "command"
Event = "event"
Result = "result"
// Event
Register = "Register"
// Exchanges
RPCExchange = "xing.rpc"
EventExchange = "xing.event"
// Client Types
ProducerClient = "producer"
ServiceClient = "service"
EventHandlerClient = "... |
Allow use of a custom environment for tests. | # -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.party.models import Party
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self, env='test'):
self.app = c... | # -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.party.models import Party
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self):
self.app = create_app('t... |
Rename function for generating query string. | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var api = require('../api');
function queryStringFromArgs(args) {
var searchString = '?q=' + args._.join('+');
if (args.user) {
searchString = searchString.concat('+user:' + args.user);
}
if (args.language) {
... | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var api = require('../api');
function arrayToQueryString(args) {
var searchString = '?q=' + args._.join('+');
if (args.user) {
searchString = searchString.concat('+user:' + args.user);
}
if (args.language) {
s... |
Include arch in dependency cache key | const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
const CONFIG = require('../config')
const FINGERPRINT_PATH = path.join(CONFIG.repositoryRootPath, 'node_modules', '.dependencies-fingerprint')
module.exports = {
write: function () {
const fingerprint = this.compute()
fs.... | const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
const CONFIG = require('../config')
const FINGERPRINT_PATH = path.join(CONFIG.repositoryRootPath, 'node_modules', '.dependencies-fingerprint')
module.exports = {
write: function () {
const fingerprint = this.compute()
fs.... |
Set q2 field as disabled when invisible | $(function() {
$("#class-table tr td:first-child").each(function() {
var t = this.textContent;
if (t.length > 30) {
var elipsized = t.substring(0, 16) + "..." + t.substring(t.length - 13, t.length);
$(this).html($("<span/>").attr({"title": t}).html(elipsized));
}
... | $(function() {
$("#class-table tr td:first-child").each(function() {
var t = this.textContent;
if (t.length > 30) {
var elipsized = t.substring(0, 16) + "..." + t.substring(t.length - 13, t.length);
$(this).html($("<span/>").attr({"title": t}).html(elipsized));
}
... |
Add isRoleOfGuild service, add null check to getRole | const RedisRole = require('../../structs/db/Redis/Role.js')
/**
* @param {string} roleID
*/
async function getRole (roleID) {
const role = await RedisRole.fetch(roleID)
return role ? role.toJSON() : null
}
/**
* @param {Object<string, any>} roleData
*/
async function formatRole (roleData) {
return {
..... | const RedisRole = require('../../structs/db/Redis/Role.js')
async function getRole (roleID) {
const role = await RedisRole.fetch(roleID)
return role.toJSON()
}
async function formatRole (roleData) {
return {
...roleData,
hexColor: roleData.hexColor === '#000000' ? '' : roleData.hexColor
}
}
/**
* @p... |
Check that `document` is defined
Check that document is defined before determining browser
capabilities. Otherwise this fails inside a web worker context.
FIX: The package can now be loaded in a web worker context (where
`navigator` is defined but `document` isn't) without crashing. | const result = {}
export default result
if (typeof navigator != "undefined" && typeof document != "undefined") {
const ie_edge = /Edge\/(\d+)/.exec(navigator.userAgent)
const ie_upto10 = /MSIE \d/.test(navigator.userAgent)
const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent)
resul... | const result = {}
export default result
if (typeof navigator != "undefined") {
const ie_edge = /Edge\/(\d+)/.exec(navigator.userAgent)
const ie_upto10 = /MSIE \d/.test(navigator.userAgent)
const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent)
result.mac = /Mac/.test(navigator.platf... |
Fix HardwareDevice constructor to provide 'description' argument | """
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types... | """
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types... |
Revert "flush and close writer"
This reverts commit f3db49d08480fa1b5d3a493469c8990b04b0a524. | package com.pengyifan.pubtator.io;
import com.google.common.base.Joiner;
import com.pengyifan.pubtator.PubTatorDocument;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
public class PubTatorIO {
public static List<PubTato... | package com.pengyifan.pubtator.io;
import com.google.common.base.Joiner;
import com.pengyifan.pubtator.PubTatorDocument;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
public class PubTatorIO {
public static List<PubTato... |
Add pretty printing for API | from django.template import RequestContext
from website.models import Restaurant, OpenTime, BaseModel
from website.api import export_data
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.http import condition
import hashlib
import json
def restaurant_gr... | from django.template import RequestContext
from website.models import Restaurant, OpenTime, BaseModel
from website.api import export_data
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.http import condition
import hashlib
import json
def restaurant_gr... |
Tidy up whitespace and line-endings | $(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
... | $(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
... |
Introduce an active prop for filters | import React, { Component } from 'react';
import classnames from 'classnames';
class Filter extends Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
active: React.PropTypes.bool,
};
static defaultProps = {
active: false,
};
... | import React, { Component } from 'react';
import classnames from 'classnames';
class Filter extends Component {
constructor(props) {
super(props);
this.state = {
active: false,
};
}
render() {
return (
<div
className={classnames('ui-filter')}
onClick={() => {
... |
Use typeof to test for function |
var hasOwn = Object.prototype.hasOwnProperty;
module.exports = function forEach (obj, fn, ctx) {
if (typeof obj !== 'object' || obj === null) {
throw new TypeError('can only iterate over objects or arrays');
}
if (typeof fn !== 'function') {
throw new TypeError('iterator must be a function... |
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (typeof obj !== 'object' || obj === null) {
throw new TypeError('can only iterate over objects or arrays');
}
if (toStr.call(fn) !== '[object Function]') {
... |
Throw an error if we attempt to modify a different version of Leaflet. | // Make sure we're modifying the correct version of Leaflet
if (L.version !== '0.7.2') {
throw new Error('Attempting to patch Leaflet ' + L.version + '. Only 0.7.2 is supported');
}
// Modify Draggable to ignore shift key.
L.Draggable.prototype._onDown = function(e) {
this._moved = false;
if ((e.which !== 1) &... | // Modify Draggable to ignore shift key.
L.Draggable.prototype._onDown = function(e) {
this._moved = false;
if ((e.which !== 1) && (e.button !== 1) && !e.touches) { return; }
L.DomEvent.stopPropagation(e);
if (L.Draggable._disabled) { return; }
L.DomUtil.disableImageDrag();
L.DomUtil.disableTextSelecti... |
Add an option to also return intermediate example norms | import numpy as np
def hyperplanes(means, stds, n_planes):
if len(means) != len(stds):
raise ValueError('means and stds must have the same length')
n_features = len(means)
a = np.random.normal(means, stds, (n_planes, n_features))
b = np.random.normal(means, stds, (n_planes, n_features))
p... | import numpy as np
def hyperplanes(means, stds, n_planes):
if len(means) != len(stds):
raise ValueError('means and stds must have the same length')
n_features = len(means)
a = np.random.normal(means, stds, (n_planes, n_features))
b = np.random.normal(means, stds, (n_planes, n_features))
p... |
Make transformations apply correctly to the matrix | /**
* @depends App.js
* @depends BasicRenderer.js
* @depends Framebuffer.js
*/
var FramebufferRenderer = new Class({
Extends: BasicRenderer,
initialize: function(width, height, vertexShader, fragmentShader,
options) {
this.parent(vertexShader, fragmentShader, options);
... | /**
* @depends App.js
* @depends BasicRenderer.js
* @depends Framebuffer.js
*/
var FramebufferRenderer = new Class({
Extends: BasicRenderer,
initialize: function(width, height, vertexShader, fragmentShader,
options) {
this.parent(vertexShader, fragmentShader, options);
... |
Add support for 2020 ECMAScript version | 'use strict';
module.exports = {
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module'
},
plugins: ['import'],
rules: {
'prefer-object-spread': 1,
'prefer-named-capture-group': 1,
// "import" and "require"
'import/no-absolute-path': 2,
'import/no-dynamic-require': 2,
'import/no-webpack-loader... | 'use strict';
module.exports = {
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
plugins: ['import'],
rules: {
'prefer-object-spread': 1,
'prefer-named-capture-group': 1,
// "import" and "require"
'import/no-absolute-path': 2,
'import/no-dynamic-require': 2,
'import/no-webpack-loader... |
Update again to cause purge hopefully | importScripts('/importme.mjs');
const CACHE_NAME = 'ROOT_CACHE';
async function cacheAllThings() {
const cache = await caches.open(CACHE_NAME);
cache.addAll([
'./index.html',
'./app.js',
'./app.css',
]);
}
self.addEventListener('install', async (event) => {
consoleTheLogs('ROO... | importScripts('/importme.mjs');
const CACHE_NAME = 'ROOT_CACHE';
async function cacheAllThings() {
const cache = await caches.open(CACHE_NAME);
cache.addAll([
'./index.html',
'./app.js',
'./app.css',
]);
}
self.addEventListener('install', async (event) => {
consoleTheLogs('R... |
Add functions to add shapes and iterate over each shape to render. | #Imports
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
sel... | #Imports
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.