text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix key error when no tags are specified | from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
... | from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
... |
Add pretty lib to inspect struct | package gmws
import (
"fmt"
"os"
"github.com/kr/pretty"
"github.com/svvu/gomws/mwsHttps"
)
// MwsConfig is configuraton to create the gomws base.
// AccessKey and SecretKey are optional, bette to set them in evn variables.
type MwsConfig struct {
SellerId string
AuthToken string
Region string
AccessKey s... | package gmws
import (
"os"
"github.com/svvu/gomws/mwsHttps"
)
// MwsConfig is configuraton to create the gomws base.
// AccessKey and SecretKey are optional, bette to set them in evn variables.
type MwsConfig struct {
SellerId string
AuthToken string
Region string
AccessKey string
SecretKey string
}
// M... |
Fix bug that prevented images from being stored. | <?php
namespace Nohex\Eix\Modules\Catalog\Model;
use Nohex\Eix\Services\Data\Sources\ImageStore as DataSource;
use Nohex\Eix\Modules\Catalog\Model\Image;
/**
* Representation of an image associated with a product.
*/
class ProductImage extends Image
{
const COLLECTION = 'products';
protected function getDe... | <?php
namespace Nohex\Eix\Modules\Catalog\Model;
use Nohex\Eix\Services\Data\Sources\ImageStore as DataSource;
use Nohex\Eix\Modules\Catalog\Model\Image;
/**
* Representation of an image associated with a product.
*/
class ProductImage extends Image
{
const COLLECTION = 'products';
protected function getDe... |
Fix possible issue when MD5ing multibyte strings. | package com.vaguehope.onosendai.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashHelper {
private HashHelper () {
throw new AssertionError();
}
public static BigInteger md5St... | package com.vaguehope.onosendai.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class HashHelper {
private HashHelper () {
throw new AssertionError();
}
public static BigInteger md5St... |
Add a blank line in the end | # Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4
"""
做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),
使用 Python 如何生成 200 个激活码(或者优惠券)?
"""
import uuid
def generate_key():
key_list = []
for i in range(200):
uuid_key = uuid.uuid3(uui... | # Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4
"""
做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),
使用 Python 如何生成 200 个激活码(或者优惠券)?
"""
import uuid
def generate_key():
key_list = []
for i in range(200):
uuid_key = uuid.uuid3(uui... |
Remove includes to be compatible with currently released chrome | import Image from '../image';
export default function bitDepth(newBitDepth = 8) {
this.checkProcessable('bitDepth', {
bitDepth: [8, 16]
});
if (!~[8,16].indexOf(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16');
if (this.bitDepth === newBitDepth) return this.clone(... | import Image from '../image';
export default function bitDepth(newBitDepth = 8) {
this.checkProcessable('bitDepth', {
bitDepth: [8, 16]
});
if (![8,16].includes(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16');
if (this.bitDepth === newBitDepth) return this.clone(... |
Upgrade from v4 to v5 | /**
* @author Hamza Waqas <hamzawaqas@live.com>
* @since 1/14/14
*/
(function() {
var _ = require('lodash');
var Main = function(apiKey) {
var _services = ['name', 'search', 'thumbnail']
, Inherits = require('./inherits')
, self = this;
// Make some configuratio... | /**
* @author Hamza Waqas <hamzawaqas@live.com>
* @since 1/14/14
*/
(function() {
var _ = require('lodash');
var Main = function(apiKey) {
var _services = ['name', 'search', 'thumbnail']
, Inherits = require('./inherits')
, self = this;
// Make some configuratio... |
Fix the order of the returned values from `analytic_signal`. | # -*- coding: utf-8 -*-
""" Cross Correlation
see @https://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html
"""
# Author: Avraam Marimpis <avraam.marimpis@gmail.com>
from .estimator import Estimator
from ..analytic_signal import analytic_signal
import numpy as np
def crosscorr(data, fb, fs, pair... | # -*- coding: utf-8 -*-
""" Cross Correlation
see @https://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html
"""
# Author: Avraam Marimpis <avraam.marimpis@gmail.com>
from .estimator import Estimator
from ..analytic_signal import analytic_signal
import numpy as np
def crosscorr(data, fb, fs, pair... |
Use find instead of split | import MeCab
class MeCabParser(object):
def __init__(self, arg=''):
self.model = MeCab.Model_create(arg)
def parse(self, s):
tagger = self.model.createTagger()
lattice = self.model.createLattice()
lattice.set_sentence(s)
tagger.parse(lattice)
node = latt... | import MeCab
class MeCabParser(object):
def __init__(self, arg=''):
self.model = MeCab.Model_create(arg)
def parse(self, s):
tagger = self.model.createTagger()
lattice = self.model.createLattice()
lattice.set_sentence(s)
tagger.parse(lattice)
node = latt... |
Fix allocation of points array for real | /**
* $$\\ToureNPlaner\\$$
*/
package algorithms;
import com.carrotsearch.hppc.IntArrayList;
public class Points {
private IntArrayList points;
public Points() {
points = new IntArrayList();
}
public void addPoint(int lat, int lon) {
points.add(lat);
points.add(lon);
}
public void addEmptyPoints(int ... | /**
* $$\\ToureNPlaner\\$$
*/
package algorithms;
import com.carrotsearch.hppc.IntArrayList;
public class Points {
private IntArrayList points;
public Points() {
points = new IntArrayList();
}
public void addPoint(int lat, int lon) {
points.add(lat);
points.add(lon);
}
public void addEmptyPoints(int ... |
Exit with code 0 if only warnings are present | const table = require('text-table')
const chalk = require('chalk')
class Reporter {
report (results) {
let output = '\n'
let totalErrors = 0
let totalWarnings = 0
results.forEach((result) => {
totalErrors += result.errorCount
totalWarnings += result.warningCount
output += chalk.un... | const table = require('text-table')
const chalk = require('chalk')
class Reporter {
report (results) {
let output = '\n'
let totalErrors = 0
let totalWarnings = 0
results.forEach((result) => {
totalErrors += result.errorCount
totalWarnings += result.warningCount
output += chalk.un... |
Add key to module table list item | import React, { PropTypes } from 'react';
import ActionDelete from 'material-ui/svg-icons/action/delete';
import IconButton from 'material-ui/IconButton';
import { List, ListItem } from 'material-ui/List';
import { red700 } from 'material-ui/styles/colors';
const ModuleTable = ({
modules,
removeModule,
}) => (
... | import React, { PropTypes } from 'react';
import ActionDelete from 'material-ui/svg-icons/action/delete';
import IconButton from 'material-ui/IconButton';
import { List, ListItem } from 'material-ui/List';
import { red700 } from 'material-ui/styles/colors';
const ModuleTable = ({
modules,
removeModule,
}) => (
... |
Add uploading true or false
Add uploading true or false. Use handlebar helper to show used if uploading | import Ember from 'ember';
export default Ember.View.extend({
tagName: 'input',
name: 'file',
attributeBindings: ['name', 'type', 'data-form-data'],
type: 'file',
didInsertElement: function() {
var _this = this,
controller = this.get('controller');
$.get(CatsUiENV.API_NAMESPACE + '/cloudinary... | import Ember from 'ember';
export default Ember.View.extend({
tagName: 'input',
name: 'file',
attributeBindings: ['name', 'type', 'data-form-data'],
type: 'file',
didInsertElement: function() {
var _this = this,
controller = this.get('controller');
$.get(CatsUiENV.API_NAMESPACE + '/cloudinary... |
fix(shop): Update admin order show page
Update admin order show page
see #401 | <?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Order;
class OrderController extends Controller
{
public function index()
{
$orders = Order::all();
return view('admin.orders.index')->with('orders', $orders);
}
publ... | <?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Order;
class OrderController extends Controller
{
public function index()
{
$orders = Order::all();
return view('admin.orders.index')->with('orders', $orders);
}
publ... |
Extend directly from replyable view | /* global define */
define([
'jquery',
'underscore',
'backbone',
'marionette',
'dust',
'dust.helpers',
'dust.marionette',
'views/replyable-view',
'controllers/navigation/navigator',
'content/comments/comment-template'
], function ($, _, Backbone, Marionette, dust, dustHelpers, dustMarionette, Reply... | /* global define */
define([
'jquery',
'underscore',
'backbone',
'marionette',
'dust',
'dust.helpers',
'dust.marionette',
'views/replyable-view',
'controllers/navigation/navigator',
'content/comments/comment-template'
], function ($, _, Backbone, Marionette, dust, dustHelpers, dustMarionette, Reply... |
Test functional error wrapping with ‘new’ | const { OError, isOError, unwrapOError } = _private;
describe('OError (white box test)', () => {
it('is exported as O.Error', () => {
expect(OError).toBe(O.Error);
});
});
describe('isOError (white box test)', () => {
it('returns true for wrapped functional errors (anything besides undefined)', () => {
... | const { OError, isOError, unwrapOError } = _private;
describe('OError (white box test)', () => {
it('is exported as O.Error', () => {
expect(OError).toBe(O.Error);
});
});
describe('isOError (white box test)', () => {
it('returns true for wrapped functional errors (anything besides undefined)', () => {
... |
Remove UA code from example GA call. |
<nav role="navigation" id="nav-main" class="nav-main js-nav-main">
<h2 class="is-hidden-visually">Menu</h2>
<?php wp_nav_menu(array(
'container' => false, // remove nav container
'menu' => __( 'Hoofdmenu', 'stickyricetheme' ), // nav name
'menu_class' => 'nav-main__list', ... |
<nav role="navigation" id="nav-main" class="nav-main js-nav-main">
<h2 class="is-hidden-visually">Menu</h2>
<?php wp_nav_menu(array(
'container' => false, // remove nav container
'menu' => __( 'Hoofdmenu', 'stickyricetheme' ), // nav name
'menu_class' => 'nav-main__list', ... |
Fix in link action. Remove the `_link` method and add action to `_delete`, this fix concurrency problems.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com> | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in pat... |
[Glitch] Fix not showing custom emojis in share page emoji picker
Port e02a13f64e5c2c93fa73a67a4ce32a7d1df24760 to glitch-soc | import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from 'flavours/glitch/store/configureStore';
import { hydrateStore } from 'flavours/glitch/actions/store';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from 'mas... | import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from 'flavours/glitch/store/configureStore';
import { hydrateStore } from 'flavours/glitch/actions/store';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from 'mas... |
Add a docstring for `test_rule_linenumber` | # Copyright (c) 2020 Albin Vass <albin.vass@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, m... | # Copyright (c) 2020 Albin Vass <albin.vass@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, m... |
Update method to get all Employee data | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users_model extends CI_Model {
public function get_users($email)
{
$this->db->where('Email', $email);
return $this->db->get('MsEmployee')->result();
}
public function get_users_by_emplid($emplid)
{
... | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users_model extends CI_Model {
public function get_users($email)
{
$this->db->where('Email', $email);
return $this->db->get('MsEmployee')->result();
}
public function get_users_by_emplid($emplid)
{
... |
Remove untested files from karma | // Karma configuration
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// testing frameworks to use
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser. order ma... | // Karma configuration
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// testing frameworks to use
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser. order ma... |
Normalize DOM from DOM or selector | export function regexEscape(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
export function isDOM(obj) {
if ("HTMLElement" in window) {
return (obj && obj instanceof HTMLElement);
}
return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeNa... | export function regexEscape(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
export function isDOM(obj) {
if ("HTMLElement" in window) {
return (obj && obj instanceof HTMLElement);
}
return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeNa... |
Test Class Update: Change UIScope => VaadinUIScope | package org.vaadin.spring.mvp.explicit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.vaadin.spring.annotation.EnableVaadin;
import org.vaadin.spring.annotation.VaadinUIScope;
im... | package org.vaadin.spring.mvp.explicit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.vaadin.spring.UIScope;
import org.vaadin.spring.annotation.EnableVaadin;
import org.vaadin.s... |
Fix to work on new strings database. | <?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_GET['param'])) {
$db = new PDO('sqlite:strings.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->query("PRAGMA case_sensitive_like = ON");
$q = $db->prepare("
SELECT
strings.str,
... | <?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_GET['param'])) {
$db = new PDO('sqlite:strings.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->query("PRAGMA case_sensitive_like = ON");
$q = $db->prepare("
SELECT
strings.str,
... |
Fix URL of question link | "use strict";
var QAService = require("../services/QAService");
var notFound = require("../notFound");
module.exports = [{
method: "GET",
path: "/{qaid}",
handler: function hander(request, reply) {
QAService.getQaidById(request.params.qaid, function getData(error, data) {
if (error || !data || !data.q... | "use strict";
var QAService = require("../services/QAService");
var notFound = require("../notFound");
module.exports = [{
method: "GET",
path: "/{qaid}",
handler: function hander(request, reply) {
QAService.getQaidById(request.params.qaid, function getData(error, data) {
if (error || !data || !data.q... |
Fix path name for angular component | // Testacular configuration
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/angular/angular.js',
'test/vendor/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'... | // Testacular configuration
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/AngularJS/angular.js',
'test/vendor/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
... |
Add peewee dependency for simpledb. | from setuptools import setup, find_packages
setup(
name='weaveserver',
version='0.8',
author='Srivatsan Iyer',
author_email='supersaiyanmode.rox@gmail.com',
packages=find_packages(),
license='MIT',
description='Library to interact with Weave Server',
long_description=open('README.md').r... | from setuptools import setup, find_packages
setup(
name='weaveserver',
version='0.8',
author='Srivatsan Iyer',
author_email='supersaiyanmode.rox@gmail.com',
packages=find_packages(),
license='MIT',
description='Library to interact with Weave Server',
long_description=open('README.md').r... |
Update version of Wikidata dump to 20150126 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import wikidata
# The data (= ID) of the Wikidata dump
dump_id = '20150126'
# The files to download
download_urls = [
"https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-terms.nt.gz" % dump_id,
"https://tools.wmflabs.org/wikidata-exports/rdf/expo... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import wikidata
# The data (= ID) of the Wikidata dump
dump_id = '20150105'
# The files to download
download_urls = [
"https://tools.wmflabs.org/wikidata-exports/rdf/exports/%s/wikidata-terms.nt.gz" % dump_id,
"https://tools.wmflabs.org/wikidata-exports/rdf/expo... |
Fix not loggin on empty routes | <?php
/**
* Part of the Tracker package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/li... | <?php
/**
* Part of the Tracker package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/li... |
Return 0 if a shortname equals to "cu.l"
"cu.l" can't be converted to double | package ca.etsmtl.applets.etsmobile.util;
import java.util.Comparator;
import ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCourse;
/**
* Created by Steven on 2016-01-14.
*/
public class CourseComparator implements Comparator<MoodleCourse> {
@Override
public int compare(MoodleCourse course1, MoodleCourse... | package ca.etsmtl.applets.etsmobile.util;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Comparator;
import ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCourse;
import ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCourses;... |
Remove @Component for optional encoder
Instantiation is optional as to avoid introducing a hard dependency on spring-security. | package org.jasig.cas.authentication.handler;
import javax.validation.constraints.NotNull;
/**
* Pass the encode/decode responsibility to a delegated Spring Security
* password encoder.
*
* @author Joe McCall
* @since 4.3
*/
public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder {
... | package org.jasig.cas.authentication.handler;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
/**
* Pass the encode/decode responsibility to a delegated Spring Security
* password encoder.
*
* @author Joe McCall
* @since 4.3
*/
@Component("springSecurityDelegatingP... |
Change the library export name. | const fs = require('fs');
const merge = require('webpack-merge');
const path = require('path');
const webpack = require('webpack');
const common = {
entry: './src/index.js',
output: {
library: 'Wargamer',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true,
},
modu... | const fs = require('fs');
const merge = require('webpack-merge');
const path = require('path');
const webpack = require('webpack');
const common = {
entry: './src/index.js',
output: {
library: 'wargamer',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true,
},
modu... |
Change controller service to controller server in config. | package core.ipc;
import core.languageHandler.Language;
public enum IPCServiceName {
CONTROLLER_SERVER(0, "controller_server"),
PYTHON(1, Language.PYTHON.toString()),
CSHARP(2, Language.CSHARP.toString()),
SCALA(3, Language.SCALA.toString()),
;
private final int index;
private final String n... | package core.ipc;
import core.languageHandler.Language;
public enum IPCServiceName {
CONTROLLER_SERVER(0, "controller_service"),
PYTHON(1, Language.PYTHON.toString()),
CSHARP(2, Language.CSHARP.toString()),
SCALA(3, Language.SCALA.toString()),
;
private final int index;
private final String ... |
Use topk in the click model | from math import exp
class ClickModel(object):
'''
Simple Position-biased Model:
P(C_r=1) = P(A_r=1|E_r=1)P(E_r=1),
where
C_r is click on the r-th document,
A_r is being attracted by the r-th document, and
E_r is examination of the r-th document.
In this simple model, the e... | from math import exp
class ClickModel(object):
'''
Simple Position-biased Model:
P(C_r=1) = P(A_r=1|E_r=1)P(E_r=1),
where
C_r is click on the r-th document,
A_r is being attracted by the r-th document, and
E_r is examination of the r-th document.
In this simple model, the e... |
Migrate ScrollView fake type to ReactNative.NativeComponent
Reviewed By: yungsters
Differential Revision: D7985122
fbshipit-source-id: b78fc6ad84485e8aa42657c2b21d70c9f3a271d6 | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
const ReactNative = require('ReactNative');
// This class is purely a facsimile of ScrollView so that we can
// ... | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
const React = require('React');
// This class is purely a facsimile of ScrollView so that we can
// properly typ... |
Change upload path for images | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified,... | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified,... |
Swap the order for my most favorite languages | var express = require('express');
var router = express.Router();
// GET home page
router.get('/', function(req, res) {
res.render('index', {
meta: {
title: 'Rollie Ma - Polyglot Developer from Vancouver, BC',
description: 'Hi, I\'m Rollie Ma. A Linux lover and LEGO bricks enthusiast... | var express = require('express');
var router = express.Router();
// GET home page
router.get('/', function(req, res) {
res.render('index', {
meta: {
title: 'Rollie Ma - Polyglot Developer from Vancouver, BC',
description: 'Hi, I\'m Rollie Ma. A Linux lover and LEGO bricks enthusiast... |
[validation] Use exceptions to get the error message. | package edu.kit.iti.formal.pse.worthwhile.validation;
import org.antlr.runtime.EarlyExitException;
import org.eclipse.xtext.nodemodel.SyntaxErrorMessage;
import org.eclipse.xtext.parser.antlr.SyntaxErrorMessageProvider;
/**
* This class provides the correct syntax error messages.
*
* @author matthias
*
*/
publ... | package edu.kit.iti.formal.pse.worthwhile.validation;
import org.eclipse.xtext.nodemodel.SyntaxErrorMessage;
import org.eclipse.xtext.parser.antlr.SyntaxErrorMessageProvider;
/**
* This class provides the correct syntax error messages.
*
* @author matthias
*
*/
public class WorthwhileSyntaxErrorMessageProvider... |
Sort movies list by released year | import React from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'react-router';
import { ListGroup, ListGroupItem, Alert } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import Documents from '../../api/documents/documents';
import container from '../../modules/container';... | import React from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'react-router';
import { ListGroup, ListGroupItem, Alert } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import Documents from '../../api/documents/documents';
import container from '../../modules/container';... |
Add an ID to join component | const Join = () => {
return (
<div id="join" className="component">
<h1>Bli med i linjeforeningen!</h1>
<p>Alle informatikere er med i linjeforeningen. Gå videre til <a href="https://online.ntnu.no/">hovedsiden</a> for å lage din brukerkonto på Online sine systemer.</p>
<p>Har du lyst til å gjør... | const Join = () => {
return (
<div className="component">
<h1>Bli med i linjeforeningen!</h1>
<p>Alle informatikere er med i linjeforeningen. Gå videre til <a href="https://online.ntnu.no/">hovedsiden</a> for å lage din brukerkonto på Online sine systemer.</p>
<p>Har du lyst til å gjøre studieti... |
Change for fixing session ID fixation problem. | package gov.nih.nci.nbia.beans.basket;
import gov.nih.nci.nbia.zip.ZipManager;
import com.icesoft.faces.async.render.SessionRenderer;
/**
* This listens to zip progress and tell ICEfaces to push a change
* to the UI as progress increases.
*
* <p>This object is a result of switching to ICEfaces which
... | package gov.nih.nci.nbia.beans.basket;
import gov.nih.nci.nbia.zip.ZipManager;
import com.icesoft.faces.async.render.SessionRenderer;
/**
* This listens to zip progress and tell ICEfaces to push a change
* to the UI as progress increases.
*
* <p>This object is a result of switching to ICEfaces which
* ... |
Change d to v, add verbose alias | #!/usr/bin/env node
const yargs = require('yargs');
// ./modules
const rocketLaunch = require('./modules/rocketLaunch');
const info = require('./modules/info');
const settings = require('./modules/settings');
const argv = yargs // eslint-disable-line
.usage('Usage: space <command> [options]')
.demandCommand(1)
... | #!/usr/bin/env node
const yargs = require('yargs');
// ./modules
const rocketLaunch = require('./modules/rocketLaunch');
const info = require('./modules/info');
const settings = require('./modules/settings');
const argv = yargs // eslint-disable-line
.usage('Usage: space <command> [options]')
.demandCommand(1)
... |
Make pytest-runner and sphinx optionlly required. | #!/usr/bin/env python
# Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop)
import io
import sys
import setuptools
with io.open('README.txt', encoding='utf-8') as readme:
long_description = readme.read()
with io.open('CHANGES.txt', encoding='utf-8') as changes:
long_description += '\n\n' + cha... | #!/usr/bin/env python
# Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop)
import io
import setuptools
with io.open('README.txt', encoding='utf-8') as readme:
long_description = readme.read()
with io.open('CHANGES.txt', encoding='utf-8') as changes:
long_description += '\n\n' + changes.read()... |
Remove hard code of date while testing | import ATV from 'atvjs';
import template from './template.hbs';
let Page = ATV.Page.create({
name: 'list-games',
template: template,
ready(options, resolve, reject) {
ATV.Navigation.showLoading("Loading Games…");
let heheGames = 'http://hehestreams.xyz/api/v1/nba/games';
ATV
.... | import ATV from 'atvjs';
import template from './template.hbs';
let Page = ATV.Page.create({
name: 'list-games',
template: template,
ready(options, resolve, reject) {
ATV.Navigation.showLoading("Loading Games…");
let heheGames = 'http://hehestreams.xyz/api/v1/nba/games?date=2016-11-05';
... |
Fix creation of BOM when create Variant | # -*- coding: utf-8 -*-
from odoo import models, api
class ProductTemplate(models.Model):
_inherit = 'product.template'
@api.multi
def create_get_variant(self, value_ids, custom_values=None):
"""Add bill of matrials to the configured variant."""
if custom_values is None:
cust... | # -*- coding: utf-8 -*-
from odoo import models, api
class ProductTemplate(models.Model):
_inherit = 'product.template'
@api.multi
def create_variant(self, value_ids, custom_values=None):
"""Add bill of matrials to the configured variant."""
if custom_values is None:
custom_v... |
Return the result of defineProperty | const FIRST_ROW = 0;
const FIRST_COL = 0;
const CHAR_CODE_OFFSET = 65;
const LABEL_OFFSET = 1;
const calculateLabel = function calculateLabel(row, col) {
const rowLabel = String.fromCharCode(CHAR_CODE_OFFSET + row);
const colLabel = col + LABEL_OFFSET;
return colLabel + rowLabel;
};
const constAttr = function... | const FIRST_ROW = 0;
const FIRST_COL = 0;
const CHAR_CODE_OFFSET = 65;
const LABEL_OFFSET = 1;
const calculateLabel = function calculateLabel(row, col) {
const rowLabel = String.fromCharCode(CHAR_CODE_OFFSET + row);
const colLabel = col + LABEL_OFFSET;
return colLabel + rowLabel;
};
const constAttr = function... |
Read in README.md as long description | # Copyright 2019 The resource-policy-evaluation-library Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | # Copyright 2019 The resource-policy-evaluation-library Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... |
Use dash to be compliant with XXX-devel pattern. | from __future__ import print_function
import subprocess
def get_version_from_git():
cmd = ["git", "describe", "--tags", "--long", "--always"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
code = proc.wait()
if code != 0:
print("Failed to run: %s" % " ".join(cmd))
sys.exit(1)
... | from __future__ import print_function
import subprocess
def get_version_from_git():
cmd = ["git", "describe", "--tags", "--long", "--always"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
code = proc.wait()
if code != 0:
print("Failed to run: %s" % " ".join(cmd))
sys.exit(1)
... |
Move the privacy config portlet to the Configuration section | package it.smc.liferay.privacy.web.application.list;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.liferay.application.list.BasePanelApp;
import com.liferay.application.list.PanelApp;
import com.liferay.application.list.constants.PanelCate... | package it.smc.liferay.privacy.web.application.list;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.liferay.application.list.BasePanelApp;
import com.liferay.application.list.PanelApp;
import com.liferay.application.list.constants.PanelCate... |
Correct type comment for table columns | """Collection of Models used in blogsite."""
from . import db
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : SQLAlchemy.Column
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
"""
# Columns
id = db.Column(db... | """Collection of Models used in blogsite."""
from . import db
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : db.Column
Autogenerated primary key
title : db.Column
body : db.Column
"""
# Columns
id = db.Column(db.Integer, primary_key=Tr... |
Fix URL patterns for ManufacturerPart and SupplierPart | """
URL lookup for Company app
"""
from django.conf.urls import url, include
from . import views
company_detail_urls = [
url(r'^thumb-download/', views.CompanyImageDownloadFromURL.as_view(), name='company-image-download'),
# Any other URL
url(r'^.*$', views.CompanyDetail.as_view(), name='company-detai... | """
URL lookup for Company app
"""
from django.conf.urls import url, include
from . import views
company_detail_urls = [
url(r'^thumb-download/', views.CompanyImageDownloadFromURL.as_view(), name='company-image-download'),
# Any other URL
url(r'^.*$', views.CompanyDetail.as_view(), name='company-detai... |
Copy gtml file to dist directory | module.exports = {
all: {
files: [
{ expand: true, src: ['config.json'], dest: 'dist' },
{ expand: true, src: ['javascript.json'], dest: 'dist' },
{ expand: true, cwd: 'src/config/', src: ['**'], dest: 'dist/config/' },
{ expand: true, cwd: 'src/images/', src:... | module.exports = {
all: {
files: [
{ expand: true, src: ['config.json'], dest: 'dist' },
{ expand: true, src: ['javascript.json'], dest: 'dist' },
{ expand: true, cwd: 'src/config/', src: ['**'], dest: 'dist/config/' },
{ expand: true, cwd: 'src/images/', src:... |
Fix phapp update commant to build regardless from environment mode, as documented since 0.6.0-beta2. | <?php
namespace drunomics\Phapp\Commands;
use drunomics\Phapp\PhappCommandBase;
use drunomics\Phapp\ServiceUtil\BuildCommandsTrait;
/**
* Updates the app.
*/
class UpdateCommands extends PhappCommandBase {
use BuildCommandsTrait;
/**
* Updates the app.
*
* @option bool $build Build before running a... | <?php
namespace drunomics\Phapp\Commands;
use drunomics\Phapp\PhappCommandBase;
use drunomics\Phapp\ServiceUtil\BuildCommandsTrait;
/**
* Updates the app.
*/
class UpdateCommands extends PhappCommandBase {
use BuildCommandsTrait;
/**
* Updates the app.
*
* @option bool $build Build before running a... |
Remove Mutation mock, which breaks in node 6.11.1 | const Relay = jest.genMockFromModule('react-relay');
class MockStore {
reset() {
this.successResponse = undefined;
}
succeedWith(response) {
this.reset();
this.successResponse = response;
}
failWith(response) {
this.reset();
this.failureResponse = response;
}
update(callbacks) {
... | const Relay = jest.genMockFromModule('react-relay');
class Mutation extends Relay.Mutation {
_resolveProps(props) {
this.props = props;
}
}
class MockStore {
reset() {
this.successResponse = undefined;
}
succeedWith(response) {
this.reset();
this.successResponse = response;
}
failWith(... |
Revert "I don't know what changed"
This reverts commit d58deaaa289b4d641fc2d845ab063daad31d34e4. | <?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 8]>
<div class="alert alert-warning">
<?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'roots'); ?>
</di... | <?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 8]>
<div class="alert alert-warning">
<?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'roots'); ?>
</di... |
Handle sleeping in main loop | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
... | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
... |
Change div to p when creating new logs | /**
* public/src/js/logger.js - delish
*
* Licensed under MIT license.
* Copyright (C) 2017 Karim Alibhai.
*/
const util = require('util')
, debounce = require('debounce')
let currentLog = document.querySelector('.lead')
, nextLog = document.querySelector('.lead.next')
/**
* Updates the current log stat... | /**
* public/src/js/logger.js - delish
*
* Licensed under MIT license.
* Copyright (C) 2017 Karim Alibhai.
*/
const util = require('util')
, debounce = require('debounce')
let currentLog = document.querySelector('.lead')
, nextLog = document.querySelector('.lead.next')
/**
* Updates the current log stat... |
Fix error with undeclared variable
Looks like a simple missprint for me |
exports.init = init;
function init(genericAWSClient) {
return createSimpleQueueServiceClient;
function createSimpleQueueServiceClient(accessKeyId, secretAccessKey, options) {
options = options || {};
var client = genericAWSClient({
host: options.host || "sqs.us-east-1.amazonaws.com",
path: op... |
exports.init = init;
function init(genericAWSClient) {
return createSimpleQueueServiceClient;
function createSimpleQueueServiceClient(accessKeyId, secretAccessKey, options) {
options = options || {};
var client = genericAWSClient({
host: options.host || "sqs.us-east-1.amazonaws.com",
path: op... |
Update the docblock of the example | """`Factory` providers - building a complex object graph with deep init injections example."""
from dependency_injector import providers
class Regularizer:
def __init__(self, alpha):
self.alpha = alpha
class Loss:
def __init__(self, regularizer):
self.regularizer = regularizer
class Class... | """`Factory` providers deep init injections example."""
from dependency_injector import providers
class Regularizer:
def __init__(self, alpha):
self.alpha = alpha
class Loss:
def __init__(self, regularizer):
self.regularizer = regularizer
class ClassificationTask:
def __init__(self, l... |
Add .html extension to generated URLs | <?php
namespace FrozenSilex;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
/**
* URL Generator which intercepts calls and passes the generated
* URLs to the Freezer
*
* @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com>
*/
class Freez... | <?php
namespace FrozenSilex;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
/**
* URL Generator which intercepts calls and passes the generated
* URLs to the Freezer
*
* @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com>
*/
class Freez... |
Fix issue with smoothscroll pattern | """
Smooth scroll pattern
"""
from .pattern import Pattern
import time
import math
# fast linear sin approx
def fastApprox(val):
return 1.0 - math.fabs( math.fmod(val, 2.0) - 1.0)
def constrain_int(value):
return int(min(255, max(value, 0)))
class ScrollSmooth(Pattern):
def __init__(self):
supe... | """
Smooth scroll pattern
"""
from .pattern import Pattern
import time
import math
# fast linear sin approx
def fastApprox(val):
return 1.0 - math.fabs( math.fmod(val, 2.0) - 1.0)
def constrain_int(value):
return int(min(255, max(value, 0)))
class ScrollSmooth(Pattern):
def __init__(self):
supe... |
Fix issue when server changed and connection failed | import {
DB_CONNECT_REQUEST,
DB_CONNECT_SUCCESS,
DB_CONNECT_FAILURE,
} from '../actions/connections';
import { SAVE_SERVER_SUCCESS } from '../actions/servers';
const initialState = {
didInvalidate: true,
};
export default function (state = initialState, action) {
switch (action.type) {
case SAVE_SERVER_... | import {
DB_CONNECT_REQUEST,
DB_CONNECT_SUCCESS,
DB_CONNECT_FAILURE,
} from '../actions/connections';
import { UPDATE_SERVER_SUCCESS } from '../actions/servers';
const initialState = {
didInvalidate: true,
};
export default function (state = initialState, action) {
switch (action.type) {
case UPDATE_SER... |
Test changing file path for nosetests | import unittest
import src
import resources.Constants as const
class TestAssignments(unittest.TestCase):
string_file = ''
int_file = ''
@classmethod
def setUpClass(cls):
cls.string_file = src.main("./resources/BasicStringAssignment.txt")
cls.int_file = src.main("./resources/BasicInte... | import unittest
import src
import resources.Constants as const
class TestAssignments(unittest.TestCase):
string_file = ''
int_file = ''
@classmethod
def setUpClass(cls):
cls.string_file = src.main("../resources/BasicStringAssignment.txt")
cls.int_file = src.main("../resources/BasicIn... |
Remove code no longer required | package org.realityforge.arez.gwt.examples;
import elemental2.dom.DomGlobal;
import org.realityforge.arez.Arez;
import org.realityforge.arez.extras.WhyRun;
final class ExampleUtil
{
private ExampleUtil()
{
}
static void jsonLogSpyEvents()
{
Arez.context().getSpy().addSpyEventHandler( new JsonLogSpyEven... | package org.realityforge.arez.gwt.examples;
import elemental2.dom.DomGlobal;
import org.realityforge.arez.Arez;
import org.realityforge.arez.browser.extras.spy.ConsoleSpyEventProcessor;
import org.realityforge.arez.extras.WhyRun;
final class ExampleUtil
{
private ExampleUtil()
{
}
static void spyEvents()
{... |
Rewrite the script in a package fasshion. | # coding=utf-8
from urllib2 import urlopen, Request
import json
import re
class XmlyDownloader(object):
def __init__(self):
self.headers = {'User-Agent': 'Safari/537.36'}
def getIDs(self, url):
resp = urlopen(Request(url, headers=self.headers))
return re.search('sound_ids=\"(.*)\"', ... | # coding=utf-8
import urllib2
import json
import re
# album_url = 'http://www.ximalaya.com/7712455/album/6333174'
album_url = 'http://www.ximalaya.com/7712455/album/4474664'
headers = {'User-Agent': 'Safari/537.36'}
resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers))
ids = re.search('sound_ids=\"(.*)\... |
Add get route for / | // Dependencies
var express = require('express');
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var exphbs = require("express-handlebars");
// Sets up the Express App
var app = express();
var PORT = process.env.PORT || 8080;
// Models to sync
var db = require("./models");
... | // Dependencies
var express = require('express');
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var exphbs = require("express-handlebars");
// Sets up the Express App
var app = express();
var PORT = process.env.PORT || 8080;
// Models to sync
var db = require("./models");
... |
Fix add Ember Try config for 1.12.X | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-1.12.X',
dependencies: {
'ember': '1.12.1'
}
},
{
name: 'ember-1.13.X',
dependencies: {
'ember': '1.13.10'
}
},
{
name: 'ember-releas... | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-1.13.X',
dependencies: {
'ember': '1.13.10'
}
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions:... |
Update - Starting Date First Semester | package utils;
public class SemesterInfo {
public static final int NO_OF_WEEKS_FIRST_SEMESTER = 16;
public static final int CHRISTMAS_HOLIDAY = 12;
public static final int CHRISTMAS_HOLIDAY_LENGTH = 2;
public static final int NO_OF_WEEKS_SECOND_SEMESTER = 15;
public static final int EASTER_HOLIDAY... | package utils;
public class SemesterInfo {
public static final int NO_OF_WEEKS_FIRST_SEMESTER = 16;
public static final int CHRISTMAS_HOLIDAY = 12;
public static final int CHRISTMAS_HOLIDAY_LENGTH = 2;
public static final int NO_OF_WEEKS_SECOND_SEMESTER = 15;
public static final int EASTER_HOLIDAY... |
Use es6 promises instead of Q | const JSONPUtil = {
/**
* Request JSONP data
*
* @todo: write test to verify this util is working properly
*
* @param {string} url
* @returns {Promise} promise
*/
request(url) {
return new Promise(function (resolve, reject) {
var callback = `jsonp_${Date.now().toString(16)}`;
va... | import Q from "q";
const JSONPUtil = {
/**
* Request JSONP data
*
* @todo: write test to verify this util is working properly
*
* @param {string} url
* @returns {Q.promise} promise
*/
request(url) {
var deferred = Q.defer();
var callback = `jsonp_${Date.now().toString(16)}`;
var sc... |
Remove Latin so Chrome stops trying to translate | @extends('admin.layouts.master')
@section('main_content')
{{-- @TODO: likely a better way to split this out in Blade! --}}
@include('admin.layouts.partials.subnav-settings')
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1... | @extends('admin.layouts.master')
@section('main_content')
{{-- @TODO: likely a better way to split this out in Blade! --}}
@include('admin.layouts.partials.subnav-settings')
<div class="container">
<div class="row">
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1... |
Remove pointless @method annotations from MockInterface | <?php
/**
* Mockery
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://github.com/padraic/mockery/blob/master/LICENSE
* If you did not receive a copy of the lice... | <?php
/**
* Mockery
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://github.com/padraic/mockery/blob/master/LICENSE
* If you did not receive a copy of the lice... |
Fix position of todos app | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import injectSheet from 'react-jss';
import Webview from 'react-electron-web-view';
import * as environment from '../../../environment';
const styles = theme => ({
root: {
background: theme.colorB... | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import injectSheet from 'react-jss';
import Webview from 'react-electron-web-view';
import * as environment from '../../../environment';
const styles = theme => ({
root: {
background: theme.colorB... |
Change to how we rectify the "IPv6 bug". | <?php
/**
* Class to interact with a cisco router.
*/
class CiscoRouter extends Router {
use CiscoTrait;
/* {@inheritDoc} */
function getPrefixList($name, $type = 'ipv4') {
$type = ($type == 'ipv4' ? 'ip' : 'ipv6');
$data = $this->exec('show ' . $type . ' prefix-list ' . $name);
$entries = array(... | <?php
/**
* Class to interact with a cisco router.
*/
class CiscoRouter extends Router {
use CiscoTrait;
/* {@inheritDoc} */
function getPrefixList($name, $type = 'ipv4') {
$type = ($type == 'ipv4' ? 'ip' : 'ipv6');
$data = $this->exec('show ' . $type . ' prefix-list ' . $name);
$entries = array(... |
Implement range of possible values with clamping if values are outside range | #/usr/bin/env python
# -*- coding: utf-8 -*-
import click
import requests
import requests_cache
# Cache the API calls and expire after 12 hours
requests_cache.install_cache(expire_after=43200)
url = 'http://ben-major.co.uk/labs/top40/api/singles/'
@click.command()
@click.option('--count',
type=click.IntRange(1,... | #/usr/bin/env python
# -*- coding: utf-8 -*-
import click
import requests
import requests_cache
# Cache the API calls and expire after 12 hours
requests_cache.install_cache(expire_after=43200)
url = 'http://ben-major.co.uk/labs/top40/api/singles/'
@click.command()
@click.option('--count',
default=10,
help='... |
Divide changelog and readme when uploading | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
with open('json2parquet/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
i... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
with open('json2parquet/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
i... |
Configure Celery correctly in smoketest | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... |
Apply extension's enhancer to saga-counter example | /*eslint-disable no-unused-vars*/
import "babel-polyfill"
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
// import sagaMonitor from './sagaMonitor'
import Counter from './components/Counter'
import ... | /*eslint-disable no-unused-vars*/
import "babel-polyfill"
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
// import sagaMonitor from './sagaMonitor'
import Counter from './components/Counter'
import reducer f... |
Fix path handling for db-password | 'use strict';
const fs = require('fs');
const path = require('path');
const escape = require('pg-escape');
const hasDBAvailable = Boolean(process.env.DB);
if (!hasDBAvailable) {
module.exports = {};
return;
}
const pgPass = fs.readFileSync(path.join(__dirname, 'db-password'), {encoding: 'utf8'});
const pgConfig... | 'use strict';
const fs = require('fs');
const escape = require('pg-escape');
const hasDBAvailable = Boolean(process.env.DB);
if (!hasDBAvailable) {
module.exports = {};
return;
}
const pgConfig = {
host: 'localhost',
user: process.env.PGUSER || 'hmbserver',
password: process.env.PGPASSWORD || fs.readFileS... |
Fix data type of shipment point id for /api/v5/integration-modules/{code}/edit | <?php
/**
* PHP version 7.3
*
* @category ShipmentPoint
* @package RetailCrm\Api\Model\Entity\Integration\Delivery
*/
namespace RetailCrm\Api\Model\Entity\Integration\Delivery;
use RetailCrm\Api\Component\Serializer\Annotation as JMS;
/**
* Class ShipmentPoint
*
* @category ShipmentPoint
* @package Retai... | <?php
/**
* PHP version 7.3
*
* @category ShipmentPoint
* @package RetailCrm\Api\Model\Entity\Integration\Delivery
*/
namespace RetailCrm\Api\Model\Entity\Integration\Delivery;
use RetailCrm\Api\Component\Serializer\Annotation as JMS;
/**
* Class ShipmentPoint
*
* @category ShipmentPoint
* @package Retai... |
Replace .call with a normal method call (faster)
It's faster to call methods directly instead of using `.call` and assigning a scope yourself | var EngineIO = require("engine.io")
var EventEmitter = require("events").EventEmitter
var EngineStream = require("./eiostream")
module.exports = EngineServer
function EngineServer(onConnection) {
var engine = new EventEmitter
var servers = []
engine.attach = attach
engine.close = close
if (onCo... | var EngineIO = require("engine.io")
var EventEmitter = require("events").EventEmitter
var EngineStream = require("./eiostream")
module.exports = EngineServer
function EngineServer(onConnection) {
var engine = new EventEmitter
var servers = []
engine.attach = attach
engine.close = close
if (onCo... |
Fix typo in use statement | <?php
namespace Drubo\Robo\Task\Filesystem;
use Drubo\Robo\Task\Filesystem\Clean\Directories as CleanDirectories;
use Drubo\Robo\Task\Filesystem\Prepare\Directories as PrepareDicrectories;
use Drubo\Robo\Task\Filesystem\Prepare\Files;
trait loadTasks {
/**
* Clean filesystem directories.
*
* @return \Dru... | <?php
namespace Drubo\Robo\Task\Filesystem;
use Drubo\Robo\Task\Filesystem\Clean\Directories as CleanDicrectories;
use Drubo\Robo\Task\Filesystem\Prepare\Directories as PrepareDicrectories;
use Drubo\Robo\Task\Filesystem\Prepare\Files;
trait loadTasks {
/**
* Clean filesystem directories.
*
* @return \Dr... |
:art: Create untested (so far) task spy | // Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
const Scheduler = require("../../lib/scheduler");
const fsWatcher = require("../../lib/fs-watcher");
const MockInspector = require("../moc... | // Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
const Scheduler = require("../../lib/scheduler");
const fsWatcher = require("../../lib/fs-watcher");
const MockInspector = require("../moc... |
Reorder routes, put i18n route first | <?php
namespace Umpirsky\I18nRoutingBundle\Routing\Strategy;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Umpirsky\I18nRoutingBundle\Routing\Generator\LocaleRequirementGeneratorInterface;
class PrefixExceptDefaultStrategy extends AbstractStrategy
{
private $routeNameSuf... | <?php
namespace Umpirsky\I18nRoutingBundle\Routing\Strategy;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Umpirsky\I18nRoutingBundle\Routing\Generator\LocaleRequirementGeneratorInterface;
class PrefixExceptDefaultStrategy extends AbstractStrategy
{
private $routeNameSuf... |
Remove old views and replace with new PasswordResetConfirmView | from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.... | from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.... |
Add --tasklist (no dash) and better description | package forager.ui;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import forager.server.Overlord;
@Parameters(separators = "=",
commandDescription = "Starts a forager master server")
public class Server implements CommandLauncher {
public static final int DEFAULT_PORT = ... | package forager.ui;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import forager.server.Overlord;
@Parameters(separators = "=",
commandDescription = "Starts a forager master server")
public class Server implements CommandLauncher {
public static final int DEFAULT_PORT = ... |
Fix searchForm JS in headerbar | /**
* @class Denkmal_Component_HeaderBar
* @extends Denkmal_Component_Abstract
*/
var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_HeaderBar',
/** @type Denkmal_Form_SearchContent|Null */
_searchForm: null,
events: {
'click .showSearch': '... | /**
* @class Denkmal_Component_HeaderBar
* @extends Denkmal_Component_Abstract
*/
var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_HeaderBar',
events: {
'click .showSearch': 'showSearch'
},
childrenEvents: {
'CM_FormField_Text focus': fu... |
Update comments about Bulk Send Job List | <?php
/**
* HelloSign PHP SDK (https://github.com/hellosign/hellosign-php-sdk/)
*/
/**
* The MIT License (MIT)
*
* Copyright (C) 2014 hellosign.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
*... | <?php
/**
* HelloSign PHP SDK (https://github.com/hellosign/hellosign-php-sdk/)
*/
/**
* The MIT License (MIT)
*
* Copyright (C) 2014 hellosign.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
*... |
Add comments lost by converting to JS | 'use babel';
/* eslint-disable no-multi-str, prefer-const, func-names */
let linkPaths;
const regex = new RegExp('((?:\\w:)?/?(?:[-\\w.]+/)*[-\\w.]+):(\\d+)(?::(\\d+))?', 'g');
// ((?:\w:)?/? # Prefix of the path either '/' or 'C:/' (optional)
// (?:[-\w.]+/)*[-\w.]+) # The path of the file some/file/path.... | 'use babel';
/* eslint-disable no-multi-str, prefer-const, func-names */
let linkPaths;
const regex = new RegExp('\
((?:\\w:)?/?\
(?:[-\\w.]+/)*[-\\w.]+)\
:(\\d+)\
(?::(\\d+))?\
', 'g');
const template = '<a class="-linked-path" data-path="$1" data-line="$2" data-column="$3">$&</a>';
export default linkPaths = lines ... |
Modify utli.go writeStringColumn to overwrite existing columns | package dsbldr
import (
"fmt"
)
// BasicOAuthHeader spits out a basic OAuth Header based on access token
func BasicOAuthHeader(consumerKey, nonce, signature, signatureMethod,
timestamp, token string) string {
return fmt.Sprintf(`OAuth oauth_consumer_key="%s",
oauth_nonce="%s",
oauth_signature="%s",
oauth_sig... | package dsbldr
import (
"fmt"
)
// BasicOAuthHeader spits out a basic OAuth Header based on access token
func BasicOAuthHeader(consumerKey, nonce, signature, signatureMethod,
timestamp, token string) string {
return fmt.Sprintf(`OAuth oauth_consumer_key="%s",
oauth_nonce="%s",
oauth_signature="%s",
oauth_sig... |
Add missing find_spec for import hook, to avoid issues when trying to set colormap | class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backen... | class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backen... |
Improve performance of Skeleton func | //go:generate go run maketables.go > tables.go
package confusables
import (
"bytes"
"golang.org/x/text/unicode/norm"
)
// TODO: document casefolding approaches
// (suggest to force casefold strings; explain how to catch paypal - pAypal)
// TODO: DOC you might want to store the Skeleton and check against it later
... | //go:generate go run maketables.go > tables.go
package confusables
import (
"unicode/utf8"
"golang.org/x/text/unicode/norm"
)
// TODO: document casefolding approaches
// (suggest to force casefold strings; explain how to catch paypal - pAypal)
// TODO: DOC you might want to store the Skeleton and check against it... |
Fix new form confirm code
@atfornes please note that this code is common for the + buttons
of project and community
Fixes #249 | 'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window', '$rootScope',
function($location, $window, $rootScope) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
... | 'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window', '$rootScope',
function($location, $window, $rootScope) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
... |
Use let in the detect test suite | 'use strict';
let bluebird = require('bluebird');
let fs = bluebird.promisifyAll(require('fs'));
let hljs = require('../../build');
let path = require('path');
let utility = require('../utility');
function testAutoDetection(language) {
let languagePath = utility.buildPath('detect', language);
it(`... | 'use strict';
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var hljs = require('../../build');
var path = require('path');
var utility = require('../utility');
function testAutoDetection(language) {
var languagePath = utility.buildPath('detect', language);
it(`... |
Remove path attribute from PostMapping | package nl.ekholabs.nlp.controller;
import java.io.IOException;
import nl.ekholabs.nlp.model.TextResponse;
import nl.ekholabs.nlp.service.SpeechToTextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.... | package nl.ekholabs.nlp.controller;
import java.io.IOException;
import nl.ekholabs.nlp.model.TextResponse;
import nl.ekholabs.nlp.service.SpeechToTextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.... |
Reorder the flag checks so version can be shown | #!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')(process.argv.slice(2));
var printHelp = function() {
console.log([
'oust',
pkg.description,
'',
'Usage:',
' $ oust <filename>... | #!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')(process.argv.slice(2));
var printHelp = function() {
console.log([
'oust',
pkg.description,
'',
'Usage:',
' $ oust <filename>... |
Add validation rule for status_code | "use strict";
const valid_uri = require("valid-url").isUri;
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;
module.exports = mongoose.model("Shortlink", new Schema({
path: {
type: String,
required: true,
minlength: 1,
index: true,
uniqu... | "use strict";
const valid_uri = require("valid-url").isUri;
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;
module.exports = mongoose.model("Shortlink", new Schema({
path: {
type: String,
required: true,
minlength: 1,
index: true,
uniqu... |
Remove not used extConfig setting
this gets changed few lines below and defined class doesn't even
exist. | <?php
class Kwc_Advanced_IntegratorTemplate_Component extends Kwc_Abstract
{
public static function getSettings($param = null)
{
$ret = parent::getSettings($param);
$ret['componentName'] = trlKwfStatic('Integrator Template');
$ret['dataClass'] = 'Kwc_Advanced_IntegratorTemplate_Data';
... | <?php
class Kwc_Advanced_IntegratorTemplate_Component extends Kwc_Abstract
{
public static function getSettings($param = null)
{
$ret = parent::getSettings($param);
$ret['componentName'] = trlKwfStatic('Integrator Template');
$ret['dataClass'] = 'Kwc_Advanced_IntegratorTemplate_Data';
... |
Increase quality of (default) figure image. | <?php snippet_detect('html_head', array(
'criticalcss' => false,
'prev_next' => false,
'prerender' => false
)); ?>
<?php snippet('banner'); ?>
<main role="main" class="Contain Copy">
<h1><?php echo $page->title()->smartypants()->widont(); ?></h1>
<?php echo figure($page->images()->first(), array(
'crop'... | <?php snippet_detect('html_head', array(
'criticalcss' => false,
'prev_next' => false,
'prerender' => false
)); ?>
<?php snippet('banner'); ?>
<main role="main" class="Contain Copy">
<h1><?php echo $page->title()->smartypants()->widont(); ?></h1>
<?php echo figure($page->images()->first(), array(
'crop'... |
Remove todo, 1.8 can use 40 symbols scoreboard score names. | package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_8__1_9_r1__1_9_r2;
import java.io.IOException;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleScoreboardScore;
import prot... | package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_8__1_9_r1__1_9_r2;
import java.io.IOException;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleScoreboardScore;
import prot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.