text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Store the time of login.
var TopLevelView = require('ui/common/components/TopLevelView'); var NetworkHelper = require('helpers/NetworkHelper'); function LoginView() { var loginUrl = Ti.App.Properties.getString('server_url') + '/api/login'; var self = new TopLevelView('Login'); var emailField = Ti.UI.createTextField({ width : '80%...
var TopLevelView = require('ui/common/components/TopLevelView'); var NetworkHelper = require('helpers/NetworkHelper'); function LoginView() { var loginUrl = Ti.App.Properties.getString('server_url') + '/api/login'; var self = new TopLevelView('Login'); var emailField = Ti.UI.createTextField({ width : '80%...
Enhance GAE compat by removing some realpath()
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Resource; /** * FileResource represents a res...
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Resource; /** * FileResource represents a res...
Use last hour to avoid empty interval
// Delete these three lines once you have your environment variables set // The environment-configured 'keen' variable is set in layout.erb Keen.ready(function(){ // ---------------------------------------- // Pageviews Area Chart // ---------------------------------------- var repos_timeline = new Keen.Query...
// Delete these three lines once you have your environment variables set // The environment-configured 'keen' variable is set in layout.erb Keen.ready(function(){ // ---------------------------------------- // Pageviews Area Chart // ---------------------------------------- var repos_timeline = new Keen.Query...
Refactor simple arrow head to use two lines instead of path
package SW9.model_canvas.arrow_heads; import javafx.scene.shape.Line; public class SimpleArrowHead extends ArrowHead { private static final double TRIANGLE_LENGTH = 20d; private static final double TRIANGLE_WIDTH = 15d; public SimpleArrowHead() { super(); addChildren(initializeLeftArrow...
package SW9.model_canvas.arrow_heads; import javafx.scene.paint.Color; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; public class SimpleArrowHead extends ArrowHead { private static final double TRIANGLE_LENGTH = 20d; private static final double TRIANGLE_W...
Allow fuzzy searches to be combined Ie. v1/jsdelivr/libraries?name=jq*&lastversion=*.0.1 .
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields...
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields...
Add support for observing an SNS topic.
var Rx = require('rx'), _ = require('lodash'); function receiveMessage(sqs, params, callback) { sqs.receiveMessage(params, function (err, data) { callback(err, data); receiveMessage(sqs, params, callback); }); } exports.observerFromTopic = function (sns, params) { return Rx.Observer.cr...
var Rx = require('rx'), _ = require('lodash'); function receiveMessage(sqs, params, callback) { sqs.receiveMessage(params, function (err, data) { callback(err, data); receiveMessage(sqs, params, callback); }); } exports.observerFromQueue = function (sqs, params) { return Rx.Observer.cr...
Disable select2 on mobile devices
$(document).ready(function() { if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) { $('select[multiple]').each(function() { var select = $(this), search = $('<button/>', { 'class': 'btn' }).append( $('<...
$(document).ready(function() { $('select[multiple]').each(function() { var select = $(this), search = $('<button/>', { 'class': 'btn' }).append( $('<span/>', { 'class': 'icon-search' })); select.removeAttr('required');...
Change from map to forEach.
(() => { 'use strict'; var player = "O"; var moves = []; var winningCombos = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["1", "5", "9"], ["3", "5", "7"], ["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]; window.play = (sq)...
(() => { 'use strict'; var player = "O"; var moves = []; var winningCombos = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["1", "5", "9"], ["3", "5", "7"], ["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]; window.play = (sq)...
Add test helper for creating users
import ujson import unittest from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from interrogate import Builder class InterrogateTestCase(unittest.TestCase): def valid_builder_args(self): model = se...
import ujson import unittest from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.pool import NullPool from interrogate import Builder class InterrogateTestCase(unittest.TestCase): def valid_b...
Add bullet to world when it's created
package edu.stuy.starlorn.entities; import edu.stuy.starlorn.upgrades.GunUpgrade; import java.util.LinkedList; public class Ship extends Entity { protected LinkedList<GunUpgrade> _gunupgrades; protected int _baseDamage, _baseShotSpeed, _health; protected double _baseAim; public Ship() { supe...
package edu.stuy.starlorn.entities; import edu.stuy.starlorn.upgrades.GunUpgrade; import java.util.LinkedList; public class Ship extends Entity { protected LinkedList<GunUpgrade> _gunupgrades; protected int _baseDamage, _baseShotSpeed, _health; protected double _baseAim; public Ship() { supe...
Fix filter for Ticket Admin
<?php namespace Stfalcon\Bundle\EventBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Show\ShowMapper; class TicketAdmin extends Admin { protected function ...
<?php namespace Stfalcon\Bundle\EventBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Show\ShowMapper; class TicketAdmin extends Admin { protected function ...
Fix import order in tests.
import imp import os import sys # Import from kolibri first to ensure Kolibri's monkey patches are applied. from kolibri import dist as kolibri_dist # noreorder from django.test import TestCase # noreorder dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase...
import imp import os import sys from django.test import TestCase from kolibri import dist as kolibri_dist dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0]...
Fix style nit, line end for test file
""" SoftLayer.tests.CLI.modules.subnet_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer import testing import json class SubnetTests(testing.TestCase): def test_detail(self): result = self.run_command(['subnet', 'detail', '1234'])...
""" SoftLayer.tests.CLI.modules.subnet_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer import testing import json class SubnetTests(testing.TestCase): def test_detail(self): result = self.run_command(['subnet', 'detail', '1234'])...
Use login instead of user's name.
package org.crunchytorch.coddy.snippet.service; import org.crunchytorch.coddy.application.exception.EntityNotFoundException; import org.crunchytorch.coddy.application.service.AbstractService; import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity; import org.crunchytorch.coddy.snippet.elasticsearch.r...
package org.crunchytorch.coddy.snippet.service; import org.crunchytorch.coddy.application.exception.EntityNotFoundException; import org.crunchytorch.coddy.application.service.AbstractService; import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity; import org.crunchytorch.coddy.snippet.elasticsearch.r...
Fix the order currency listener spec
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\CoreBundle\EventListener; use PhpSpec\ObjectBehavior; class OrderCurren...
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\CoreBundle\EventListener; use PhpSpec\ObjectBehavior; class OrderCurren...
Update regex to fit DD/MM/YYYY format
package seedu.ezdo.model.todo; import seedu.ezdo.commons.exceptions.IllegalValueException; /** * Represents the due date of a todo. */ public class DueDate { public static final String MESSAGE_DUEDATE_CONSTRAINTS = "Due dates should be in the format DD/MM/YYYY, and it should not be blank"; p...
package seedu.ezdo.model.todo; import seedu.ezdo.commons.exceptions.IllegalValueException; /** * Represents the due date of a todo. */ public class DueDate { public static final String MESSAGE_DUEDATE_CONSTRAINTS = "Due dates should be in the format DD/MM/YYYY, and it should not be blank"; p...
Truncate target table before creating division items
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_d...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_d...
Add info about crop gravity options in config example
module.exports = { variants: { items: { // keepNames: true, resize: { mini : "300x200", preview: "800x600" }, crop: { thumb: "200x200", // Sets the crop position, or "gravity". Default is NorthWest. // See http://www.graphicsmagick.org/GraphicsMagick...
module.exports = { variants: { items: { // keepNames: true, resize: { mini : "300x200", preview: "800x600" }, crop: { thumb: "200x200" }, resizeAndCrop: { large: {resize: "1000x1000", crop: "900x900"} } }, gallery: { rename: ...
Use version alias for jasmine-jquery
/* * debugger.io: An interactive web scripting sandbox */ (function() { 'use strict'; var SRC = '../../src'; var TEST = '../../test'; // relative to SRC require([SRC + '/js/require.config'], function() { requirejs.config({ baseUrl: SRC + '/js', urlArgs: ('v=' + (new Date()).getTime()), ...
/* * debugger.io: An interactive web scripting sandbox */ (function() { 'use strict'; var SRC = '../../src'; var TEST = '../../test'; // relative to SRC require([SRC + '/js/require.config'], function() { requirejs.config({ baseUrl: SRC + '/js', urlArgs: ('v=' + (new Date()).getTime()), ...
Remove weird duplication of removal of destroyed entity from updater.
;(function(exports) { function Entities() { this._entities = []; }; Entities.prototype = { all: function(clazz) { if (clazz === undefined) { return this._entities; } else { var entities = []; for (var i = 0; i < this._entities.length; i++) { if (this._entitie...
;(function(exports) { function Entities() { this._entities = []; }; Entities.prototype = { all: function(clazz) { if (clazz === undefined) { return this._entities; } else { var entities = []; for (var i = 0; i < this._entities.length; i++) { if (this._entitie...
Fix docblock @covers class path
<?php use Illuminate\Http\Response; use Illuminate\Support\Facades\Session; class LanguageSwitchTest extends TestCase { /** * Test switch language to English * @covers \App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToEnglish() { $applocale ...
<?php use Illuminate\Http\Response; use Illuminate\Support\Facades\Session; class LanguageSwitchTest extends TestCase { /** * Test switch language to English * @covers App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToEnglish() { $applocale =...
Fix for rethrowing mysql.connector.Error as IOError
import sys class PlayoffDB(object): db_cursor = None DATABASE_NOT_CONFIGURED_WARNING = 'WARNING: database not configured' def __init__(self, settings): reload(sys) sys.setdefaultencoding("latin1") import mysql.connector self.database = mysql.connector.connect( ...
import sys class PlayoffDB(object): db_cursor = None DATABASE_NOT_CONFIGURED_WARNING = 'WARNING: database not configured' def __init__(self, settings): reload(sys) sys.setdefaultencoding("latin1") import mysql.connector self.database = mysql.connector.connect( ...
Fix serialization of form errors
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) def get_data(error): if isinstance(error, (di...
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) class JSONMixin(object): def as_json(self): ...
Use room name as string, instead as object for key value
'use strict'; var all = false; var cache = {}; function getCache(room) { if (all === false) { all = []; for (var i in Game.creeps) { if (!Game.creeps.spawning) { if (cache[Game.creeps[i].room.name] === undefined) { cache[Game.creeps[i].room.name] = [...
'use strict'; var all = false; var cache = {}; function getCache(room) { if (all === false) { all = []; for (var i in Game.creeps) { if (!Game.creeps.spawning) { if (cache[Game.creeps[i].room] === undefined) { cache[Game.creeps[i].room] = [Game.creep...
Return its argument in validators
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, ...
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, ...
Switch from old to current method `$this->app->bindShared()` was deprecated in Laravel 5.1, and removed in 5.2. It has been replaced by the (identical in all but name) `->singleton()` method. This PR addresses this change.
<?php namespace Rokde\LaravelBootstrap\Html; use Collective\Html\HtmlBuilder; use Illuminate\Support\ServiceProvider; /** * Class HtmlServiceProvider * * @package Rokde\LaravelBootstrap\Html */ class HtmlServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. ...
<?php namespace Rokde\LaravelBootstrap\Html; use Collective\Html\HtmlBuilder; use Illuminate\Support\ServiceProvider; /** * Class HtmlServiceProvider * * @package Rokde\LaravelBootstrap\Html */ class HtmlServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. ...
Add a short alias for bin/openprocurement_tests Alias is: bin/op_tests
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email...
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email...
Replace name, surname concatenation with getFullName
package by.triumgroup.recourse.document.model.provider.impl; import by.triumgroup.recourse.document.model.provider.ContentProvider; import by.triumgroup.recourse.entity.dto.Student; import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark; import java.util.*; import java.util.stream.Collectors; public class...
package by.triumgroup.recourse.document.model.provider.impl; import by.triumgroup.recourse.document.model.provider.ContentProvider; import by.triumgroup.recourse.entity.dto.Student; import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark; import java.util.*; import java.util.stream.Collectors; public class...
Remove if that was making the view to behave unexpectedly
'use strict'; angular.module('eMarketApp') .directive('itemView', function(User) { return { templateUrl: 'views/itemView.html', restrict: 'E', scope: { item: '=' }, replace: true, link: function(scope, elem) { var page = $(elem[0]); ...
'use strict'; angular.module('eMarketApp') .directive('itemView', function (User) { return { templateUrl: 'views/itemView.html', restrict: 'E', scope: { item: '=' }, replace: true, link: function (scope, elem) { var page = $(elem[0]); ...
Add stop method, fix dangerous args.
#! /usr/bin/env python3 """Main XOInvader module, that is entry point to game. Prepare environment for starting game and start it.""" import curses from xoinvader.menu import MainMenuState from xoinvader.ingame import InGameState from xoinvader.render import Renderer from xoinvader.common import Settings from xoin...
#! /usr/bin/env python3 """Main XOInvader module, that is entry point to game. Prepare environment for starting game and start it.""" import curses from xoinvader.menu import MainMenuState from xoinvader.ingame import InGameState from xoinvader.render import Renderer from xoinvader.common import Settings from xoin...
Use dynamic self.__class__ and not name directly
import logging import yaml l = logging.getLogger(__name__) def _replace_with_type(type_, replace_type, data): if isinstance(data, type_): return replace_type(data) return data class Config(dict): def __init__(self, items=None): if items is not None: if hasattr(items, 'ite...
import logging import yaml l = logging.getLogger(__name__) def _replace_with_type(type_, replace_type, data): if isinstance(data, type_): return replace_type(data) return data class Config(dict): def __init__(self, items=None): if items is not None: if hasattr(items, 'ite...
Change password reset error message
'use strict'; angular.module('arachne.controllers') /** * Set new password. * * @author: Daniel M. de Oliveira */ .controller('PwdActivationController', ['$scope', '$stateParams', '$filter', '$location', 'PwdActivation', 'messageService', function ($scope, $stateParams, $filter, $location,...
'use strict'; angular.module('arachne.controllers') /** * Set new password. * * @author: Daniel M. de Oliveira */ .controller('PwdActivationController', ['$scope', '$stateParams', '$filter', '$location', 'PwdActivation', 'messageService', function ($scope, $stateParams, $filter, $location,...
Enable placeholder to be docked
Ext.define('Slate.ui.mixin.PlaceholderItem', { extend: 'Ext.Mixin', requires: [ 'Slate.ui.Placeholder' ], mixinConfig: { after: { initItems: 'initPlaceholderItem' } }, config: { /** * @cfg {Slate.ui.Placeholder|Object|string|boolean} ...
Ext.define('Slate.ui.mixin.PlaceholderItem', { extend: 'Ext.Mixin', requires: [ 'Slate.ui.Placeholder' ], mixinConfig: { after: { initItems: 'initPlaceholderItem' } }, config: { /** * @cfg {Slate.ui.Placeholder|Object|string|boolean} ...
Fix wrong key in websocket message
from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from info_internet_connection.models import Internet import datetime import huawei_b593_status import json import redis #{'WIFI': 'off', 'SIG': '5', 'Mode': '4g', 'Roam': 'home', 'SIM': 'normal', 'Connect': 'connec...
from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from info_internet_connection.models import Internet import datetime import huawei_b593_status import json import redis #{'WIFI': 'off', 'SIG': '5', 'Mode': '4g', 'Roam': 'home', 'SIM': 'normal', 'Connect': 'connec...
Remove default classifier path from default config
""" Base line settings """ CONFIG = { 'input_path': None, 'backup_path': None, 'dest_path': None, 'life_all': None, 'db': { 'host': None, 'port': None, 'name': None, 'user': None, 'pass': None }, # 'preprocess': { # 'max_acc': 30.0 # }, ...
""" Base line settings """ CONFIG = { 'input_path': None, 'backup_path': None, 'dest_path': None, 'life_all': None, 'db': { 'host': None, 'port': None, 'name': None, 'user': None, 'pass': None }, # 'preprocess': { # 'max_acc': 30.0 # }, ...
Test that .info() and .warn() set the correct event type. Former-commit-id: 17449ebde702c82594b0d592047ae7c684f14fc9
package org.gem.log; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; public class AMQPApp...
package org.gem.log; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; public class AMQPApp...
Convert settings.INSTALLED_APPS to list before concatenating django. According to the Django documentation settings.INSTALLED_APPS is a tuple. To go for sure that only list + list are concatenated, settings.INSTALLED_APPS is converted to list type before adding ['django'].
import sys import django from django.conf import settings from django.utils.translation import ugettext_lazy as _ from debug_toolbar.panels import DebugPanel class VersionDebugPanel(DebugPanel): """ Panel that displays the Django version. """ name = 'Version' template = 'debug_toolbar/panels/ver...
import sys import django from django.conf import settings from django.utils.translation import ugettext_lazy as _ from debug_toolbar.panels import DebugPanel class VersionDebugPanel(DebugPanel): """ Panel that displays the Django version. """ name = 'Version' template = 'debug_toolbar/panels/ver...
Set the autocomplete list size to 10 elements maximum.
var autocomplete = { // options for the EasyAutocomplete API setUp: function(input) { $input = $(input); options = { adjustWidth: false, data: autocompleteDict[$input.attr('name')], getValue: 'name', template: { type: 'custom', method: function(value, item) { ...
var autocomplete = { // options for the EasyAutocomplete API setUp: function(input) { $input = $(input); options = { adjustWidth: false, data: autocompleteDict[$input.attr('name')], getValue: 'name', template: { type: 'custom', method: function(value, item) { ...
Fix redirect generation for reverse proxied solutions
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app....
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app....
Change name: logged_in => check_online
import subprocess import requests def check_online(): """Check whether the device has logged in. Return a dictionary containing: username byte duration (in seconds) Return False if no logged in """ r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login', ...
import subprocess import requests def logged_in(): """Check whether the device has logged in. Return a dictionary containing: username byte duration (in seconds) Return False if no logged in """ r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login', ...
Add interims link and reword narratives
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.view.progress.NavPanel', { extend: 'SlateAdmin.view.LinksNavPanel', xtype: 'progress-navpanel', //TODO: Delete extra link when nav panel arrow collapse is fixed title: 'Student Progress', data: true, applyData: function(da...
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.view.progress.NavPanel', { extend: 'SlateAdmin.view.LinksNavPanel', xtype: 'progress-navpanel', //TODO: Delete extra link when nav panel arrow collapse is fixed title: 'Student Progress', data: true, applyData: function(da...
Fix accidental typo that snuck in
(function (window){ requirejs([ 'underscore', 'backbone', 'BB' ], function(_, Backbone, BB) { BB.model_definitions.search = Backbone.Model.extend({ defaults: {}, initialize: function(){ if(BB.bootstrapped.filters){ this...
(function (window){ requirejs([ 'underscore', 'backbone', 'BB' ], function(_, Backbone, BB) { BB.model_definitions.search = Backbone.Model.extend({ defaults: {}, initialize: function(){ if(BB.bootstrapped.filters4){ thi...
Fix approximate count double test Use DoubleType instead of BigintType
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distribut...
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distribut...
Establish new session upon login.
package controllers; import play.*; import play.data.*; import play.mvc.*; import views.html.*; import static play.data.Form.*; public class Application extends Controller { public static Result home() { return ok(home.render("Hi! This is Ode.")); } public static Result login() { retu...
package controllers; import play.*; import play.data.*; import play.mvc.*; import views.html.*; import static play.data.Form.*; public class Application extends Controller { public static Result home() { return ok(home.render("Hi! This is Ode.")); } public static Result login() { retu...
Fix token getter and improve error reporting
import React, {Component, PropTypes} from 'react'; import lodash from 'lodash'; export function listeningTo(storeTokens = [], getter) { if (storeTokens.some(token => token === undefined)) { throw new TypeError('@listeningTo cannot handle undefined tokens'); } return decorator; function decora...
import React, {Component, PropTypes} from 'react'; import lodash from 'lodash'; export function listeningTo(storeTokens, getter) { return decorator; function decorator(ChildComponent) { class ListeningContainerComponent extends Component { static contextTypes = { dependency...
BB-4780: Convert Organization scope to Global in NavigationBundle, remove Website and AccountUser scope from FrontendNavigationBundle - removed unused constant
<?php namespace Oro\Bundle\NavigationBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class MenuUpdateProviderPass implements CompilerPassInte...
<?php namespace Oro\Bundle\NavigationBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class MenuUpdateProviderPass implements CompilerPassInte...
Change string formating for Credential
import os class Credential(object): def __init__(self, name, login, password, comments): self.name = name self.login = login self.password = password self.comments = comments def save(self, database_path): credential_path = os.path.join(database_path, self.name) ...
import os class Credential(object): def __init__(self, name, login, password, comments): self.name = name self.login = login self.password = password self.comments = comments def save(self, database_path): credential_path = os.path.join(database_path, self.name) ...
Fix casting in form to_python() method NetAddressFormField.to_python() was calling "self.python_type()" to cast the form value to an IP() object. Unfortunately, for is no such method defined here, or in the Django forms.Field() class, at least in 1.4 and up
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP...
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP...
Fix repeated prompt bug in keep run
import json import os import re import click from keep import cli, utils @click.command('run', short_help='Executes a saved command.') @click.argument('pattern') @cli.pass_context def cli(ctx, pattern): """Executes a saved command.""" json_path = os.path.join(os.path.expanduser('~'), '.keep', 'commands.json')...
import json import os import re import click from keep import cli, utils @click.command('run', short_help='Executes a saved command.') @click.argument('pattern') @cli.pass_context def cli(ctx, pattern): """Executes a saved command.""" json_path = os.path.join(os.path.expanduser('~'), '.keep', 'commands.json')...
Write db errors to error.log
import threading import time import accounts import args import config import log as _log MAX_TEXT_LENGTH = 1024 enabled = bool(args.args['database']) if enabled: import MySQLdb connected = False conn = None cur = None db_lock = threading.RLock() def _connect(): global conn, cur, connected if not conne...
import threading import time import accounts import args import config MAX_TEXT_LENGTH = 1024 enabled = bool(args.args['database']) if enabled: import MySQLdb connected = False conn = None cur = None db_lock = threading.RLock() def _connect(): global conn, cur, connected if not connected: conn ...
Comment out fix_fee_product_index from migration
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): try: schema_editor.execute( 'DROP INDEX idx_16977_product_id;' ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): table_name = 'cfpb.ratechecker_fee' index_name = 'idx_16977_product_id' try...
Test port change for hapi-auth-hawk plugin
/** * Created by Omnius on 6/15/16. */ 'use strict'; const Boom = require('boom'); exports.register = (server, options, next) => { server.auth.strategy('hawk-login-auth-strategy', 'hawk', { getCredentialsFunc: (sessionId, callback) => { const redis = server.app.redis; const met...
/** * Created by Omnius on 6/15/16. */ 'use strict'; const Boom = require('boom'); exports.register = (server, options, next) => { server.auth.strategy('hawk-login-auth-strategy', 'hawk', { getCredentialsFunc: (sessionId, callback) => { const redis = server.app.redis; const met...
9397: Fix warning when rendering null value
import React from 'react'; import PropTypes from 'prop-types'; class FormSelect extends React.Component { static propTypes = { id: PropTypes.string, includeBlank: PropTypes.bool, name: PropTypes.string, options: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, name: PropTypes.str...
import React from 'react'; import PropTypes from 'prop-types'; class FormSelect extends React.Component { static propTypes = { id: PropTypes.string, includeBlank: PropTypes.bool, name: PropTypes.string, options: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, name: PropTypes.str...
Update ethereum tokens limit to 50
'use strict'; var axios = require('axios'); var db = require('./db'); var limit = 50; function save(tokens) { var operations = tokens.map(function(token) { return {replaceOne: {filter: {_id: token._id}, replacement: token, upsert: true}}; }); var collection = db().collection('ethereum_tokens'); return co...
'use strict'; var axios = require('axios'); var db = require('./db'); var limit = 100; function save(tokens) { var operations = tokens.map(function(token) { return {replaceOne: {filter: {_id: token._id}, replacement: token, upsert: true}}; }); var collection = db().collection('ethereum_tokens'); return c...
Use the same vocabulary to make a findDate as well as retrieving it
<?php namespace App\Models; class FindEvent extends Base { public static $NODE_TYPE = 'E10'; public static $NODE_NAME = 'findEvent'; protected $has_unique_id = true; protected $related_models = [ 'P12' => [ 'key' => 'object', 'model_name' => 'Object', 'cas...
<?php namespace App\Models; class FindEvent extends Base { public static $NODE_TYPE = 'E10'; public static $NODE_NAME = 'findEvent'; protected $has_unique_id = true; protected $related_models = [ 'P12' => [ 'key' => 'object', 'model_name' => 'Object', 'cas...
Change iteritems to items, as it was breaking tests
from functools import wraps __version__ = '0.2.0' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): ...
from functools import wraps __version__ = '0.2.0' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): ...
Fix Bitbucket Server appearing twice in the repository list. When Power Pack is installed, Bitbucket Server appears twice in the repository form's hosting list. This is because the fake entry was using the wrong module path for Bitbucket Server. This fixes that to use the right path, showing only a single entry. Test...
from __future__ import unicode_literals from reviewboard.hostingsvcs.service import HostingService class FakeHostingService(HostingService): """A hosting service that is not provided by Review Board. Fake hosting services are intended to be used to advertise for Beanbag, Inc.'s Power Pack extension. ...
from __future__ import unicode_literals from reviewboard.hostingsvcs.service import HostingService class FakeHostingService(HostingService): """A hosting service that is not provided by Review Board. Fake hosting services are intended to be used to advertise for Beanbag, Inc.'s Power Pack extension. ...
Unify cases of create and no create
import { select, local } from "d3-selection"; var componentLocal = local(), noop = function (){}; export default function (tagName, className){ var create, render = noop, destroy = noop, selector = className ? "." + className : tagName; function component(selection, props){ var update =...
import { select, local } from "d3-selection"; var componentLocal = local(), noop = function (){}; export default function (tagName, className){ var create, render = noop, destroy = noop, selector = className ? "." + className : tagName; function component(selection, props){ var update =...
Use ->exec for generating the test SQL database from setup/
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <cogo@starzinger.net> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ namespace ImboBehatFeatureContext\DatabaseTest; use ImboBehatFeatureContext\Adapte...
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <cogo@starzinger.net> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ namespace ImboBehatFeatureContext\DatabaseTest; use ImboBehatFeatureContext\Adapte...
Fix Events mixin callbacks binding.
define([ 'fossil/core', 'underscore', 'backbone' ], function (Fossil, _, Backbone) { var Events = Fossil.Mixins.Events = _.extend({}, Backbone.Events, { registerEvents: function () { var events = _.extend( {}, _.result(this, 'events'), ...
define([ 'fossil/core', 'underscore', 'backbone' ], function (Fossil, _, Backbone) { var Events = Fossil.Mixins.Events = _.extend({}, Backbone.Events, { registerEvents: function () { var events = _.extend( {}, _.result(this, 'events'), ...
Fix select outside code area.
$(function () { function restore() { $(".ghs-highlight").removeClass("ghs-highlight"); $(".ghs-partial-highlight").contents().unwrap(); } $("body").mouseup(function (e) { restore(); var selection = $.trim(window.getSelection()); if (selection) { var code...
$(function () { function restore() { $(".ghs-highlight").removeClass("ghs-highlight"); $(".ghs-partial-highlight").contents().unwrap(); } $("body").mouseup(function (e) { restore(); var selection = $.trim(window.getSelection()); if (selection) { var code...
Fix slug unicode on template tag article get ArticleBox
# -*- coding: utf-8 -*- from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = ...
# -*- coding: utf-8 -*- from django import template from django.conf import settings from django.utils import timezone from .models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = "{0}-{1}".for...
Use canvas width/height for futureproofing
const jpegThumbnail = dataUrl => new Promise((resolve, reject) => { const image = new Image(); image.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const maxDimension = 96; // 3x the maximum displayed size of 32px if (imag...
const jpegThumbnail = dataUrl => new Promise((resolve, reject) => { const image = new Image(); image.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const maxDimension = 96; // 3x the maximum displayed size of 32px if (imag...
Fix bug in abort functionality. We stored the deferred object instead of the complete XHR object, so attempting an xhr.abort() caused a fatal
(function($) { // jQuery on an empty object, we are going to use this as our Queue var ajaxQueue = $({}); $.ajaxQueue = function( ajaxOpts ) { var jqXHR, dfd = $.Deferred(), promise = dfd.promise(); // run the actual query function doRequest( next ) { jqXHR = $.ajax( ajaxOpts ); ...
(function($) { // jQuery on an empty object, we are going to use this as our Queue var ajaxQueue = $({}); $.ajaxQueue = function( ajaxOpts ) { var jqXHR, dfd = $.Deferred(), promise = dfd.promise(); // run the actual query function doRequest( next ) { jqXHR = $.ajax( ajaxOpts ) ...
Use the `@Timed` annotation on SQLObjects Looks more reasonable to me this way instead logging everything by default.
package com.github.arteam.jdbi3; import com.codahale.metrics.annotation.Timed; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.stringtemplate4.UseStringTempla...
package com.github.arteam.jdbi3; import com.codahale.metrics.annotation.Timed; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.stringtemplate4.UseStringTempla...
Revert "Zastąpienie findAll generowaniem pustej listy" This reverts commit b28c03003ff556dd56690ba848062505f951476d.
package org.pwd.web.websites; import org.pwd.domain.websites.Website; import org.pwd.domain.websites.WebsiteRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; impo...
package org.pwd.web.websites; import org.pwd.domain.websites.Website; import org.pwd.domain.websites.WebsiteRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; impo...
Change recursive call to private function
/* * deep-clone * @author Garrett Reed <garrett@garrettreed.co> 2016 * MIT Licensed * * Suports: * Primitives: null, string, number, function (inherits prototype) * Collections: object, array * * @param {object} target Receiving object * @param {object/array} obj Object to clone * @return {object/array} ...
/* * deep-clone * @author Garrett Reed <garrett@garrettreed.co> 2016 * MIT Licensed * * Suports: * Primitives: null, string, number, function (inherits prototype) * Collections: object, array * * @param {object} target Receiving object * @param {object/array} obj Object to clone * @return {object/array} ...
Make raw_data and data as properties
#!/usr/bin/env python # -*- coding: utf-8 -*- """utils for data crunching, saving. """ import numpy as np class ScanDataFactory(object): """Post processor of data from scan server. Parameters ---------- data : dict Raw data retrieving from scan server regarding scan ID, after comple...
#!/usr/bin/env python # -*- coding: utf-8 -*- """utils for data crunching, saving. """ import numpy as np class ScanDataFactory(object): """Post processor of data from scan server. Parameters ---------- data : dict Raw data retrieving from scan server regarding scan ID, after comple...
Make main link go to dashboard for election
<?php require_once('config.php'); global $config; $userid = session_get_user_id(); $stmt = $pdo->prepare("SELECT `election` FROM `access` WHERE `user`= ?"); $stmt->bindParam(1, $userid); $stmt->execute(); $elections = $stmt->fetchAll(); ?> <aside class="main-sidebar"> <section class="sidebar">...
<?php require_once('config.php'); global $config; $userid = session_get_user_id(); $stmt = $pdo->prepare("SELECT `election` FROM `access` WHERE `user`= ?"); $stmt->bindParam(1, $userid); $stmt->execute(); $elections = $stmt->fetchAll(); ?> <aside class="main-sidebar"> <section class="sidebar">...
feat(plugins): Add moduleURLs in addition to scriptURLs
export class OHIFPlugin { // TODO: this class is still under development and will // likely change in the near future constructor () { this.name = "Unnamed plugin"; this.description = "No description available"; } // load an individual script URL static loadScript(scriptURL, typ...
export class OHIFPlugin { // TODO: this class is still under development and will // likely change in the near future constructor () { this.name = "Unnamed plugin"; this.description = "No description available"; } // load an individual script URL static loadScript(scriptURL) { ...
Refresh iframe on "RENDERING" change
AV.VisualizationView = Backbone.View.extend({ el: '#visualization', initialize: function() { this.$el.load(_.bind(function(){ console.log("it did a reload"); console.log(this.$el.contents()[0].title); if (!(this.$el.contents()[0].title)) { console.log...
AV.VisualizationView = Backbone.View.extend({ el: '#visualization', // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. render: function() { this.model.url = this.model.urlRoot + this.model.id + ...
Fix encoding (thanks to Yasushi Masuda) git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@433 3777fadb-0f44-0410-9e7f-9d8fa6171d72
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can...
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): ...
BB-7489: Test & Merge - moved FrontendBundle files from commerce package to customer-portal - removed test page templates
<?php namespace Oro\Bundle\EntityBundle\Form\DataTransformer; use Symfony\Component\Form\DataTransformerInterface; use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue; class EntityFieldFallbackTransformer implements DataTransformerInterface { /** * {@inheritdoc} */ public function transfor...
<?php namespace Oro\Bundle\EntityBundle\Form\DataTransformer; use Symfony\Component\Form\DataTransformerInterface; use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue; class EntityFieldFallbackTransformer implements DataTransformerInterface { /** * {@inheritdoc} */ public function transfor...
Make CLI linter messages a bit easier to read
'use strict'; var configLoader = require('./config-loader'); var LessHint = require('./lesshint'); var exit = require('exit'); var Vow = require('vow'); module.exports = function (program) { var lesshint = new LessHint(); var exitDefer = Vow.defer(); var exitPromise = exitDefer.promise(); var promises...
'use strict'; var configLoader = require('./config-loader'); var LessHint = require('./lesshint'); var exit = require('exit'); var Vow = require('vow'); module.exports = function (program) { var lesshint = new LessHint(); var exitDefer = Vow.defer(); var exitPromise = exitDefer.promise(); var promises...
Fix page where site key is entered
<?php $themeManager = $this->website->getThemeManager(); $theme = $themeManager->getCurrentTheme(); $stylesheet = $themeManager->getUrlTheme($theme) . $theme->getErrorPageStylesheet(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html>...
<?php $themeManager = $this->getThemeManager(); $theme = $themeManager->getCurrentTheme(); $stylesheet = $themeManager->getUrlTheme($theme) . $theme->getErrorPageStylesheet(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <hea...
Fix href for filter lists items
var React = require('react'); var classNames = require('classnames'); var FilterItem = React.createClass({ propTypes: { selected: React.PropTypes.bool, href: React.PropTypes.string, className: React.PropTypes.string, count: React.PropTypes.number, onClick: React....
var React = require('react'); var classNames = require('classnames'); var FilterItem = React.createClass({ propTypes: { selected: React.PropTypes.bool, href: React.PropTypes.string, className: React.PropTypes.string, count: React.PropTypes.number, onClick: React....
Tweak to migration so it is a bit faster for future migraters
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('msgs', '0033_exportmessagestask_uuid'), ] def move_recording_domains(apps, schema_editor): M...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('msgs', '0033_exportmessagestask_uuid'), ] def move_recording_domains(apps, schema_editor): M...
Fix a bug where widgets wouldn't be rendered w/ their themes in wysiwyg
import React from 'react'; import PropTypes from 'prop-types'; import { VegaChart } from 'widget-editor'; // /widget_data.json?widget_id= class WidgetBlock extends React.Component { constructor(props) { super(props); this.widgetConfig = null; this.state = { loading: true, widget: null };...
import React from 'react'; import PropTypes from 'prop-types'; import { VegaChart, getVegaTheme } from 'widget-editor'; // /widget_data.json?widget_id= class WidgetBlock extends React.Component { constructor(props) { super(props); this.widgetConfig = null; this.state = { loading: true, widge...
Refactor spec with a let/letgo. chdiring to fixtures dir
<?php namespace spec\MageTest\PHPSpec2\MagentoExtension\Loader; use PHPSpec2\ObjectBehavior; use PHPSpec2\Loader\Node\Specification as NodeSpecification; use ReflectionClass; class SpecificationsClassLoader extends ObjectBehavior { function it_loads_controller_specs() { $specification = $this->load...
<?php namespace spec\MageTest\PHPSpec2\MagentoExtension\Loader; use PHPSpec2\ObjectBehavior; use PHPSpec2\Loader\Node\Specification as NodeSpecification; use ReflectionClass; class SpecificationsClassLoader extends ObjectBehavior { function it_loads_controller_specs() { $currentWorkingDirectory = g...
Add bots with no games to the leaderboard
import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank, BotIdentity class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( BotIdentity.id, func.coalesce(fun...
import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( MatchResult.bot, func.sum(MatchResult.delta_ch...
Make search results more clickable Refs #148.
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import { getAvailableTime, getCaption, getMainImage, getName, getOpeningHours, } from 'utils/DataUtils'; class SearchResult extends Component { renderImage(image) { if (image && image.url) { const src = `${...
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import { getAvailableTime, getCaption, getMainImage, getName, getOpeningHours, } from 'utils/DataUtils'; class SearchResult extends Component { renderImage(image) { if (image && image.url) { const src = `${...
Fix invalid bitmask for release archives
var eventStream = require('event-stream'), gulp = require('gulp'), chmod = require('gulp-chmod'), zip = require('gulp-zip'), tar = require('gulp-tar'), gzip = require('gulp-gzip'), rename = require('gulp-rename'); gulp.task('prepare-release', function() { var version = require('./package.js...
var eventStream = require('event-stream'), gulp = require('gulp'), chmod = require('gulp-chmod'), zip = require('gulp-zip'), tar = require('gulp-tar'), gzip = require('gulp-gzip'), rename = require('gulp-rename'); gulp.task('prepare-release', function() { var version = require('./package.js...
Use hooks for progress updates
import os, youtube_dl from youtube_dl import YoutubeDL from multiprocessing.pool import ThreadPool from youtube_dl.utils import DownloadError from datetime import datetime from uuid import uuid4 class Download: link = '' done = False error = False started = None uuid = '' total = 0 finishe...
import youtube_dl, os from multiprocessing.pool import ThreadPool from youtube_dl.utils import DownloadError from datetime import datetime from uuid import uuid4 class Download: link = "" done = False error = False started = None uuid = "" total = 0 finished = 0 title = "" def __i...
Add titles to columns and use write instead of print
# -*- encoding: utf-8 -*- from django.core.management.base import BaseCommand from django.apps import apps # from reversion import revisions as reversion from reversion.models import Version from reversion.errors import RegistrationError class Command(BaseCommand): help = "Count reversion records for each mode...
# -*- encoding: utf-8 -*- from django.core.management.base import BaseCommand from django.apps import apps # from reversion import revisions as reversion from reversion.models import Version from reversion.errors import RegistrationError class Command(BaseCommand): help = "Count reversion records for each mode...
Fix filename instead of path in meta
import os import hashlib import magic from datetime import datetime from .settings import METADATA_PATH from .meta import get_meta from .encryption import copy_and_encrypt, decrypt_blob from .utils import dumps hashing = hashlib.sha256 def save_metadata(meta): destination = os.path.join(METADATA_PATH, meta['id...
import os import hashlib import magic from datetime import datetime from .settings import METADATA_PATH from .meta import get_meta from .encryption import copy_and_encrypt, decrypt_blob from .utils import dumps hashing = hashlib.sha256 def save_metadata(meta): destination = os.path.join(METADATA_PATH, meta['id...
Put hero text more to the right
import React from 'react'; import Hero from 'grommet/components/Hero'; import Image from 'grommet/components/Image'; import Box from 'grommet/components/Box'; import Heading from 'grommet/components/Heading'; import Carousel from 'grommet/components/Carousel'; import styles from './MyHero.module.scss'; class MyHero e...
import React from 'react'; import Hero from 'grommet/components/Hero'; import Image from 'grommet/components/Image'; import Box from 'grommet/components/Box'; import Heading from 'grommet/components/Heading'; import Carousel from 'grommet/components/Carousel'; import styles from './MyHero.module.scss'; class MyHero e...
Update user provider to expect model.
<?php namespace Aurora\Auth; use GuzzleHttp\Exception\ClientException; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Auth\EloquentUserProvider; class NorthstarUserProvider extends EloquentUserProvider implements UserProvider { /** * Retrieve a user...
<?php namespace Aurora\Auth; use GuzzleHttp\Exception\ClientException; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Auth\EloquentUserProvider; class NorthstarUserProvider extends EloquentUserProvider implements UserProvider { /** * Retrieve a user...
Move ITEM_MAP to method variable
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger("%s.%s" % ("homecontroller", __name__)) class Command(BaseCommand): args = '' help ...
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger("%s.%s" % ("homecontroller", __name__)) class Command(BaseCommand): args = '' help ...
Make the message nicer with a picture of jen
@extends('layouts.master') @section('main_content') @include('layouts.header', ['header' => 'Upload a CSV for import']) <div class="container -padded"> <div class="wrapper"> <div class="container__block -narrow"> <article class="figure margin-bottom-none -left -small"> ...
@extends('layouts.master') @section('main_content') @include('layouts.header', ['header' => 'Upload a CSV for import']) <div class="container -padded"> <div class="wrapper"> <div class="container__block -narrow"> <p>For the time being, This feature should only be used by J...
Use 'open' to open about dialog URLs on OS X
import gtk import os import sys def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_...
import gtk import os def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_pr...
feature/oop-api-refactoring: Remove unused imports and `pass` keywords
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimato...
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Method, Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter....
Add full image url to Station serializer
from django.conf import settings from django.contrib.sites.models import Site from rest_framework import serializers from base.models import (Antenna, Data, Observation, Satellite, Station, Transponder) class AntennaSerializer(serializers.ModelSerializer): class Meta: model = Ant...
from rest_framework import serializers from base.models import (Antenna, Data, Observation, Satellite, Station, Transponder) class AntennaSerializer(serializers.ModelSerializer): class Meta: model = Antenna fields = ('frequency', 'band', 'antenna_type') class StationSer...
Move GC collect after loading unit test function.
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, passed): s = ...
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, passed): s = ...
Add return statent to 'run' method
<?php declare(strict_types=1); namespace Onion\Framework\Application; use Interop\Http\Middleware\DelegateInterface; use Interop\Http\Middleware\ServerMiddlewareInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\EmitterInterface; class Applicati...
<?php declare(strict_types=1); namespace Onion\Framework\Application; use Interop\Http\Middleware\DelegateInterface; use Interop\Http\Middleware\ServerMiddlewareInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\EmitterInterface; class Applicati...
Fix bug with list formatting Before it would completely fail to format any list of strings
from enum import Enum, unique from inspect import signature, isclass from mycroft.plugin.base_plugin import BasePlugin from mycroft.util import log @unique class Format(Enum): speech = 1 text = 2 class FormatterPlugin(BasePlugin): and_ = 'and' def __init__(self, rt): super().__init__(rt) ...
from enum import Enum, unique from inspect import signature, isclass from mycroft.plugin.base_plugin import BasePlugin from mycroft.util import log @unique class Format(Enum): speech = 1 text = 2 class FormatterPlugin(BasePlugin): and_ = 'and' def __init__(self, rt): super().__init__(rt) ...
Handle empty cells in the spreadsheet
# -*- coding: utf-8 -*- import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeri...
# -*- coding: utf-8 -*- import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeri...
Update default background color & formatting updates
import React, { Component, PropTypes, View, Image } from 'react-native'; import Icon from './Icon'; import { getColor } from './helpers'; export default class Avatar extends Component { static propTypes = { icon: PropTypes.string, src: PropTypes.string, size: PropTypes.number, colo...
import React, { Component, PropTypes, View, Image } from 'react-native'; import Icon from './Icon'; import { ICON_NAME } from './config'; export default class Avatar extends Component { static propTypes = { icon: PropTypes.string, src: PropTypes.string, size: PropTypes.number, colo...
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, ...
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, ...
Support both Python 2 and 3
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() PACKAGE = "phileo" NAME = "phileo" DESCRIPTION = "a liking app" AUTHOR = "Pinax T...
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() PACKAGE = "phileo" NAME = "phileo" DESCRIPTION = "a liking app" AUTHOR = "Pinax T...
Update JSMA test tutorial constant
import unittest class TestMNISTTutorialJSMA(unittest.TestCase): def test_mnist_tutorial_jsma(self): from tutorials import mnist_tutorial_jsma # Run the MNIST tutorial on a dataset of reduced size # and disable visualization. jsma_tutorial_args = {'train_start': 0, ...
import unittest class TestMNISTTutorialJSMA(unittest.TestCase): def test_mnist_tutorial_jsma(self): from tutorials import mnist_tutorial_jsma # Run the MNIST tutorial on a dataset of reduced size # and disable visualization. jsma_tutorial_args = {'train_start': 0, ...