text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Order feedback by most recent
from django import forms from django.contrib import admin from feedback.models import Feedback class FeedbackAdminForm(forms.ModelForm): class Meta: model = Feedback fields = '__all__' widgets = { 'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}), 'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}), 'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}), } class FeedbackAdmin(admin.ModelAdmin): model = Feedback form = FeedbackAdminForm list_display = ( 'player', 'get_type', 'created', 'comments', ) list_filter = ( 'type', 'created', ) search_fields = ( 'comments', 'user_agent', 'redux_state', 'player__username', ) ordering = ( '-created', ) def get_type(self, obj): return obj.get_type_display() get_type.short_description = 'Type' get_type.admin_order_field = 'type' admin.site.register(Feedback, FeedbackAdmin)
from django import forms from django.contrib import admin from feedback.models import Feedback class FeedbackAdminForm(forms.ModelForm): class Meta: model = Feedback fields = '__all__' widgets = { 'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}), 'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}), 'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}), } class FeedbackAdmin(admin.ModelAdmin): model = Feedback form = FeedbackAdminForm list_display = ( 'player', 'get_type', 'created', 'comments', ) list_filter = ( 'type', 'created', ) search_fields = ( 'comments', 'user_agent', 'redux_state', 'player__username', ) def get_type(self, obj): return obj.get_type_display() get_type.short_description = 'Type' get_type.admin_order_field = 'type' admin.site.register(Feedback, FeedbackAdmin)
Make the room and teacher columns of TEXT type
package com.satsumasoftware.timetable.db; import android.provider.BaseColumns; import com.satsumasoftware.timetable.db.util.SchemaUtilsKt; public final class ClassDetailsSchema implements BaseColumns { public static final String TABLE_NAME = "class_details"; public static final String COL_CLASS_ID = "class_id"; public static final String COL_ROOM = "room"; public static final String COL_BUILDING = "building"; public static final String COL_TEACHER = "teacher"; protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " + _ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.PRIMARY_KEY_AUTOINCREMENT + SchemaUtilsKt.COMMA_SEP + COL_CLASS_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP + COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP + COL_BUILDING + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP + COL_TEACHER + SchemaUtilsKt.TEXT_TYPE + " )"; protected static final String SQL_DELETE = "DROP TABLE IF EXISTS " + TABLE_NAME; }
package com.satsumasoftware.timetable.db; import android.provider.BaseColumns; import com.satsumasoftware.timetable.db.util.SchemaUtilsKt; public final class ClassDetailsSchema implements BaseColumns { public static final String TABLE_NAME = "class_details"; public static final String COL_CLASS_ID = "class_id"; public static final String COL_ROOM = "room"; public static final String COL_BUILDING = "building"; public static final String COL_TEACHER = "teacher"; protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " + _ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.PRIMARY_KEY_AUTOINCREMENT + SchemaUtilsKt.COMMA_SEP + COL_CLASS_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP + COL_ROOM + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP + COL_BUILDING + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP + COL_TEACHER + SchemaUtilsKt.INTEGER_TYPE + " )"; protected static final String SQL_DELETE = "DROP TABLE IF EXISTS " + TABLE_NAME; }
Fix syncdb in database router
from .settings import CONNECTION_NAME class Log4DjangoRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def db_for_write(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'log4django' or obj2._meta.app_label == 'log4django': return True return None def allow_syncdb(self, db, model): if db == CONNECTION_NAME and model._meta.app_label == 'log4django': return True return None
from .settings import CONNECTION_NAME class Log4DjangoRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def db_for_write(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'log4django' or obj2._meta.app_label == 'log4django': return True return None def allow_syncdb(self, db, model): if db == CONNECTION_NAME: return model._meta.app_label == 'log4django' elif model._meta.app_label == 'log4django': return False return None
Handle when no moduleDependencies delcared.
'use strict'; module.exports = function (gulp, gutil) { var scripts = require('../lib/scripts.js')(gulp, gutil); gulp.task('scripts', ['scripts-main', 'scripts-tpls', 'scripts-deps', 'scripts-deps-metadata']); gulp.task('scripts-main', function () { return scripts.processScripts(scripts.JS_MAIN_PATTERN, scripts.PLUGIN_SCRIPTS_PATH, undefined, false, true); }); gulp.task('scripts-tpls', function () { return scripts.processTpls(scripts.TPL_MAIN_PATTERN, scripts.PLUGIN_SCRIPTS_PATH, undefined, false); }); gulp.task('scripts-deps', function (cb) { if (gutil.env.ng.moduleDependencies) { return gulp.src(gutil.env.ng.moduleDependencies, {base: './bower_components'}) .pipe(gulp.dest(scripts.SCRIPTS_DEPS_PATH)); } else { cb(); } }); gulp.task('scripts-deps-metadata', ['scripts-main'], function () { return scripts.createDepsMetadata(scripts.PLUGIN_SCRIPTS_PATH, scripts.SCRIPTS_DEPS_METADATA_PATH); }); gulp.task('jshint', function () { return gulp.src(scripts.JS_MAIN_PATTERN).pipe(scripts.jshint(true)); }); gulp.task('jscs', function () { gulp.src(scripts.JS_MAIN_PATTERN).pipe(scripts.jscs(true)); }); };
'use strict'; module.exports = function (gulp, gutil) { var scripts = require('../lib/scripts.js')(gulp, gutil); gulp.task('scripts', ['scripts-main', 'scripts-tpls', 'scripts-deps', 'scripts-deps-metadata']); gulp.task('scripts-main', function () { return scripts.processScripts(scripts.JS_MAIN_PATTERN, scripts.PLUGIN_SCRIPTS_PATH, undefined, false, true); }); gulp.task('scripts-tpls', function () { return scripts.processTpls(scripts.TPL_MAIN_PATTERN, scripts.PLUGIN_SCRIPTS_PATH, undefined, false); }); gulp.task('scripts-deps', function () { return gulp.src(gutil.env.ng.moduleDependencies, { base: './bower_components' }) .pipe(gulp.dest(scripts.SCRIPTS_DEPS_PATH)); }); gulp.task('scripts-deps-metadata', ['scripts-main'], function () { return scripts.createDepsMetadata(scripts.PLUGIN_SCRIPTS_PATH, scripts.SCRIPTS_DEPS_METADATA_PATH); }); gulp.task('jshint', function () { return gulp.src(scripts.JS_MAIN_PATTERN).pipe(scripts.jshint(true)); }); gulp.task('jscs', function () { gulp.src(scripts.JS_MAIN_PATTERN).pipe(scripts.jscs(true)); }); };
Remove a fixed module ID
<?php namespace filsh\yii2\oauth2server; /** * Instead use bootstrap module * should be removed in v2.1 version * * @deprecated v2.0.1 */ class Bootstrap implements \yii\base\BootstrapInterface { use BootstrapTrait; /** * @inheritdoc */ public function bootstrap($app) { /** @var $module Module */ if ($app->hasModule('oauth2') && ($module = $app->getModule('oauth2')) instanceof Module) { $this->initModule($module); if ($app instanceof \yii\console\Application) { $module->controllerNamespace = 'filsh\yii2\oauth2server\commands'; } } } }
<?php namespace filsh\yii2\oauth2server; /** * Instead use bootstrap module * must be removed in v2.1 * * @deprecated v2.0.1 */ class Bootstrap implements \yii\base\BootstrapInterface { use BootstrapTrait; /** * @inheritdoc */ public function bootstrap($app) { /** @var $module Module */ if ($app->hasModule('oauth2') && ($module = $app->getModule('oauth2')) instanceof Module) { $this->initModule($module); if ($app instanceof \yii\console\Application) { $module->controllerNamespace = 'filsh\yii2\oauth2server\commands'; } } } }
Add support for --token in login command This can be used when you already have the token and do not want to open the browser.
import click import webbrowser import floyd from floyd.client.auth import AuthClient from floyd.manager.auth_config import AuthConfigManager from floyd.model.access_token import AccessToken from floyd.log import logger as floyd_logger @click.command() @click.option('--token', is_flag=True, default=False, help='Just enter token') def login(token): """ Log into Floyd via Auth0. """ if not token: cli_info_url = "{}/welcome".format(floyd.floyd_web_host) click.confirm('Authentication token page will now open in your browser. Continue?', abort=True, default=True) webbrowser.open(cli_info_url) access_code = click.prompt('Please copy and paste the token here', type=str, hide_input=True) user = AuthClient().get_user(access_code) access_token = AccessToken(username=user.username, token=access_code) AuthConfigManager.set_access_token(access_token) floyd_logger.info("Login Successful") @click.command() def logout(): """ Logout of Floyd. """ AuthConfigManager.purge_access_token()
import click import webbrowser import floyd from floyd.client.auth import AuthClient from floyd.manager.auth_config import AuthConfigManager from floyd.model.access_token import AccessToken from floyd.log import logger as floyd_logger @click.command() def login(): """ Log into Floyd via Auth0. """ cli_info_url = "{}/welcome".format(floyd.floyd_web_host) click.confirm('Authentication token page will now open in your browser. Continue?', abort=True, default=True) webbrowser.open(cli_info_url) access_code = click.prompt('Please copy and paste the token here', type=str, hide_input=True) user = AuthClient().get_user(access_code) access_token = AccessToken(username=user.username, token=access_code) AuthConfigManager.set_access_token(access_token) floyd_logger.info("Login Successful") @click.command() def logout(): """ Logout of Floyd. """ AuthConfigManager.purge_access_token()
Clear trades from old search from data viewer before adding new ones
package uk.ac.cam.cstibhotel.otcanalyser.gui; import java.awt.BorderLayout; import javax.swing.JFrame; import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchListener; import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchResult; public class GUI extends JFrame implements SearchListener { private static final long serialVersionUID = 1L; public StatusBar statusBar; public static GUI gui; static SearchWindow searchWindow; DataViewer dataViewer; public static GUI getInstance() { if (gui==null) { gui = new GUI(); } return gui; } public GUI() { setTitle("OTC Analyser"); setSize(1000,600); setDefaultCloseOperation(EXIT_ON_CLOSE); searchWindow = SearchWindow.getInstance(); add(searchWindow,BorderLayout.WEST); searchWindow.setVisible(true); statusBar = StatusBar.getInstance(); add(statusBar,BorderLayout.SOUTH); statusBar.setVisible(true); dataViewer = DataViewer.dataViewer; this.add(dataViewer); dataViewer.setVisible(true); this.setVisible(true); } @Override public void getSearchResult(SearchResult s) { DataViewer.clearTrades(); DataViewer.addTrades(s.getResultData()); } }
package uk.ac.cam.cstibhotel.otcanalyser.gui; import java.awt.BorderLayout; import javax.swing.JFrame; import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchListener; import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchResult; public class GUI extends JFrame implements SearchListener { private static final long serialVersionUID = 1L; public StatusBar statusBar; public static GUI gui; static SearchWindow searchWindow; DataViewer dataViewer; public static GUI getInstance() { if (gui==null) { gui = new GUI(); } return gui; } public GUI() { setTitle("OTC Analyser"); setSize(1000,600); setDefaultCloseOperation(EXIT_ON_CLOSE); searchWindow = SearchWindow.getInstance(); add(searchWindow,BorderLayout.WEST); searchWindow.setVisible(true); statusBar = StatusBar.getInstance(); add(statusBar,BorderLayout.SOUTH); statusBar.setVisible(true); dataViewer = DataViewer.dataViewer; this.add(dataViewer); dataViewer.setVisible(true); this.setVisible(true); } @Override public void getSearchResult(SearchResult s) { DataViewer.addTrades(s.getResultData()); } }
Write .msg of chunk to file
#!/usr/bin/env python """ This example demonstrates a client fetching images from a server running img_server.py. The first packet contains the number of chunks to expect, and then that number of chunks is read. Lost packets are not handled in any way. """ from nuts import UDPAuthChannel channel = UDPAuthChannel('secret', timeout=4) with channel.connect( ('10.0.0.1', 8001) ) as session: session.send('Take pic!') msg = session.receive() num_chunks = int(msg) with open('latest_img.jpg', 'wb') as img_fh: for i in range(num_chunks): chunk = session.receive() print('got chunk %d of %d' % (i + 1, num_chunks)) # Preferably, the msg received would support the buffer interface # and be writable directly, but it isn't img_fh.write(chunk.msg)
#!/usr/bin/env python """ This example demonstrates a client fetching images from a server running img_server.py. The first packet contains the number of chunks to expect, and then that number of chunks is read. Lost packets are not handled in any way. """ from nuts import UDPAuthChannel channel = UDPAuthChannel('secret', timeout=4) with channel.connect( ('10.0.0.1', 8001) ) as session: session.send('Take pic!') msg = session.receive() num_chunks = int(msg) with open('latest_img.jpg', 'wb') as img_fh: for i in range(num_chunks): chunk = session.receive() print('got chunk %d of %d' % (i + 1, num_chunks)) img_fh.write(chunk)
Allow creation of the first famous user.
package edu.brown.hackathon.fifteenminutes; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Query; import com.google.gson.Gson; @SuppressWarnings("serial") public class IsFamousServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { long userId = getUserIdOfFamousUser(); UserResource ur = new UserResource(userId); Gson gson = new Gson(); resp.setContentType("application/json"); resp.getWriter().println(gson.toJson(ur)); } public static long getUserIdOfFamousUser() { Query query = new Query("FamousUser"); query.addSort("current_time", Query.SortDirection.DESCENDING); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (results.size() < 1) { return -1; } else { return (Long)results.get(0).getProperty("user_id"); } } }
package edu.brown.hackathon.fifteenminutes; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Query; import com.google.gson.Gson; @SuppressWarnings("serial") public class IsFamousServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { long userId = getUserIdOfFamousUser(); UserResource ur = new UserResource(userId); Gson gson = new Gson(); resp.setContentType("application/json"); resp.getWriter().println(gson.toJson(ur)); } public static long getUserIdOfFamousUser() { Query query = new Query("FamousUser"); query.addSort("current_time", Query.SortDirection.DESCENDING); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); return (Long)results.get(0).getProperty("user_id"); } }
Remove usage of dump component.
import React, { Component } from "react"; import { connect } from "react-redux"; import { SCREEN_STATE_PAGE_ENTER, SCREEN_STATE_PAGE_EXIT } from "../screen/action"; @connect( state => { return { screenAnimation: state.screen.animation }; }) export default class Transition extends Component { animationState = "stopped"; componentWillReceiveProps(nextProps) { if (this.animationState === "starting") { this.animationState = "started"; } if (nextProps.screenAnimation === SCREEN_STATE_PAGE_EXIT) { this.animationState = "starting"; } if (nextProps.screenAnimation === SCREEN_STATE_PAGE_ENTER) { this.animationState = "stopped"; } } render() { const { className, onEnterClassName, onExitClassName } = this.props; return ( <div className={`${className} ${this.props.screenAnimation === SCREEN_STATE_PAGE_EXIT ? onExitClassName: onEnterClassName}`}> {this.props.children || null} </div> ); } }
import React, { Component } from "react"; import { connect } from "react-redux"; import { SCREEN_STATE_PAGE_ENTER, SCREEN_STATE_PAGE_EXIT } from "../screen/action"; import Dumb from "./dumb"; @connect( state => { return { screenAnimation: state.screen.animation }; }) export default class Transition extends Component { animationState = "stopped"; componentWillReceiveProps(nextProps) { if (this.animationState === "starting") { this.animationState = "started"; } if (nextProps.screenAnimation === SCREEN_STATE_PAGE_EXIT) { this.animationState = "starting"; } if (nextProps.screenAnimation === SCREEN_STATE_PAGE_ENTER) { this.animationState = "stopped"; } } render() { const { className, onEnterClassName, onExitClassName } = this.props; return ( <div className={`${className} ${this.props.screenAnimation === SCREEN_STATE_PAGE_EXIT ? onExitClassName: onEnterClassName}`}> {/*<Dumb>*/} {this.props.children || null} {/*</Dumb>*/} </div> ); } }
Use /download as core download route.
<?php /** * Copyright Zikula Foundation 2014 - Zikula Application Framework * * This work is contributed to the Zikula Foundation under one or more * Contributor Agreements and licensed to You under the following license: * * @license MIT * * Please see the NOTICE file distributed with this source code for further * information regarding copyright and licensing. */ namespace Zikula\Module\CoreManagerModule\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; /** * UI operations executable by general users. */ class UserController extends \Zikula_AbstractController { /** * @Route("/download", options={"zkNoBundlePrefix" = 1}) */ public function viewCoreReleasesAction() { $releaseManager = $this->get('zikulacoremanagermodule.releasemanager'); $releases = $releaseManager->getSignificantReleases(false); $this->view->assign('releases', $releases); return $this->response($this->view->fetch('User/viewreleases.tpl')); } }
<?php /** * Copyright Zikula Foundation 2014 - Zikula Application Framework * * This work is contributed to the Zikula Foundation under one or more * Contributor Agreements and licensed to You under the following license: * * @license MIT * * Please see the NOTICE file distributed with this source code for further * information regarding copyright and licensing. */ namespace Zikula\Module\CoreManagerModule\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; /** * UI operations executable by general users. */ class UserController extends \Zikula_AbstractController { /** * @Route("/") */ public function viewCoreReleasesAction() { $releaseManager = $this->get('zikulacoremanagermodule.releasemanager'); $releases = $releaseManager->getSignificantReleases(false); $this->view->assign('releases', $releases); return $this->response($this->view->fetch('User/viewreleases.tpl')); } }
Change exception to more appropriate
<?php namespace X509\GeneralName; class IPv4Address extends IPAddress { /** * Initialize from octets * * @param string $octets * @throws \InvalidArgumentException * @return self */ public static function fromOctets($octets) { $ip = null; $mask = null; $bytes = unpack("C*", $octets); switch (count($bytes)) { case 4: $ip = implode(".", $bytes); break; case 8: $ip = implode(".", array_slice($bytes, 0, 4)); $mask = implode(".", array_slice($bytes, 4, 4)); break; default: throw new \UnexpectedValueException("Invalid IPv4 octet length."); } return new self($ip, $mask); } protected function _octets() { $bytes = array_map("intval", explode(".", $this->_ip)); if (isset($this->_mask)) { $bytes = array_merge($bytes, array_map("intval", explode(".", $this->_mask))); } return pack("C*", ...$bytes); } }
<?php namespace X509\GeneralName; class IPv4Address extends IPAddress { /** * Initialize from octets * * @param string $octets * @throws \InvalidArgumentException * @return self */ public static function fromOctets($octets) { $ip = null; $mask = null; $bytes = unpack("C*", $octets); switch (count($bytes)) { case 4: $ip = implode(".", $bytes); break; case 8: $ip = implode(".", array_slice($bytes, 0, 4)); $mask = implode(".", array_slice($bytes, 4, 4)); break; default: throw new \InvalidArgumentException("Invalid IPv4 octet length."); } return new self($ip, $mask); } protected function _octets() { $bytes = array_map("intval", explode(".", $this->_ip)); if (isset($this->_mask)) { $bytes = array_merge($bytes, array_map("intval", explode(".", $this->_mask))); } return pack("C*", ...$bytes); } }
Apply only for walkable contents.
<?php /** * BEAR.Framework * * @license http://opensource.org/licenses/bsd-license.php BSD */ namespace BEAR\Framework\Resource\View; use BEAR\Resource\Object as ResourceObject; use BEAR\Resource\Requestable; use BEAR\Resource\Renderable; /** * Request renderer * * @package BEAR.Framework * @subpackage View */ class JsonRenderer implements Renderable { /** * (non-PHPdoc) * @see BEAR\Resource.Renderable::render() */ public function render(ResourceObject $ro) { // evaluate all request in body. if (is_array($ro->body) || $ro->body instanceof \Traversable) { array_walk_recursive($ro->body, function(&$element) { if ($element instanceof Requestable) { $element = $element(); } }); } $ro->view = @json_encode($ro->body, JSON_PRETTY_PRINT); return $ro->view; } }
<?php /** * BEAR.Framework * * @license http://opensource.org/licenses/bsd-license.php BSD */ namespace BEAR\Framework\Resource\View; use BEAR\Resource\Object as ResourceObject; use BEAR\Resource\Requestable; use BEAR\Resource\Renderable; /** * Request renderer * * @package BEAR.Framework * @subpackage View */ class JsonRenderer implements Renderable { /** * (non-PHPdoc) * @see BEAR\Resource.Renderable::render() */ public function render(ResourceObject $ro) { // evaluate all request in body. array_walk_recursive($ro->body, function(&$element) { if ($element instanceof Requestable) { $element = $element(); } }); $ro->view = @json_encode($ro->body, JSON_PRETTY_PRINT); return $ro->view; } }
Change column's name and add a foreign key for the vehicles_colors table
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateVehiclesTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('vehicles', function (Blueprint $table) { $table->string('code'); $table->foreign('code')->references('code')->on('items'); $table->string('make'); $table->string('model'); $table->integer('year'); $table->enum('type', array('Car', 'Truck', 'Motorcycle', 'Boat', 'Other')); $table->enum('fuel', array('Gasoline', 'Diesel', 'Hybrid', 'Electric', 'Alternative'))->nullable(); $table->integer('color_id')->nullable(); $table->foreign('color_id')->references('id')->on('vehicles_colors'); $table->boolean('isGoodCondition')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::drop('vehicles'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateVehiclesTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('vehicles', function (Blueprint $table) { $table->string('code'); $table->foreign('code')->references('code')->on('items'); $table->string('make'); $table->string('model'); $table->integer('vehicle_year'); $table->enum('type', array('Car', 'Truck', 'Motorcycle', 'Boat', 'Other')); $table->enum('fuel', array('Gasoline', 'Diesel', 'Hybrid', 'Electric', 'Alternative'))->nullable(); $table->string('colours')->nullable(); $table->boolean('isGoodCondition')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::drop('vehicles'); } }
Make sure we're testing the right function!
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi_info): assert new_delhi_info.tzinfo == pytz.timezone("Asia/Kolkata")
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi): assert new_delhi.tzinfo == pytz.timezone("Asia/Kolkata")
Format file with python Black
#!/usr/bin/env python # encoding: utf-8 """ Created on Aug 29, 2014 @author: tmahrt """ from setuptools import setup import io setup( name="praatio", version="4.2.1", author="Tim Mahrt", author_email="timmahrt@gmail.com", url="https://github.com/timmahrt/praatIO", package_dir={"praatio": "praatio"}, packages=["praatio", "praatio.utilities"], package_data={ "praatio": [ "praatScripts/*.praat", ] }, license="LICENSE", description="A library for working with praat, textgrids, time aligned audio transcripts, and audio files.", long_description=io.open("README.md", "r", encoding="utf-8").read(), long_description_content_type="text/markdown", # install_requires=[], # No requirements! # requires 'from setuptools import setup' )
#!/usr/bin/env python # encoding: utf-8 ''' Created on Aug 29, 2014 @author: tmahrt ''' from setuptools import setup import io setup(name='praatio', version='4.2.1', author='Tim Mahrt', author_email='timmahrt@gmail.com', url='https://github.com/timmahrt/praatIO', package_dir={'praatio':'praatio'}, packages=['praatio', 'praatio.utilities'], package_data={'praatio': ['praatScripts/*.praat', ]}, license='LICENSE', description='A library for working with praat, textgrids, time aligned audio transcripts, and audio files.', long_description=io.open('README.md', 'r', encoding="utf-8").read(), long_description_content_type="text/markdown", # install_requires=[], # No requirements! # requires 'from setuptools import setup' )
Add siprefix to runtime dependencies.
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='claes@emt.uni-paderborn.de', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy', 'matplotlib', 'siprefix' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], )
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='claes@emt.uni-paderborn.de', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy', 'matplotlib' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], )
Remove use of getElement() in example @rev W-3224090@ @rev goliver@
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ onRadio: function(cmp, evt) { var selected = evt.source.get("v.label"); resultCmp = cmp.find("radioResult"); resultCmp.set("v.value", selected); }, onGroup: function(cmp, evt) { var selected = evt.source.get("v.label"); resultCmp = cmp.find("radioGroupResult"); resultCmp.set("v.value", selected); } })
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ onRadio: function(cmp, evt) { var elem = evt.getSource().getElement(); var selected = elem.textContent; resultCmp = cmp.find("radioResult"); resultCmp.set("v.value", selected); }, onGroup: function(cmp, evt) { var elem = evt.getSource().getElement(); var selected = elem.textContent; resultCmp = cmp.find("radioGroupResult"); resultCmp.set("v.value", selected); } })
Fix bug. board is property. not but function.
import React from 'react'; import { connect } from 'react-redux'; import pieceComponent from '../components/piece'; import { holdPiece, enhanceCanDropPosition } from '../actions'; import store from '../stores/index'; const mapStateToProps = (state) => { return { }; }; const mapDispatchToProps = (dispatch) => { return { onPieceClick: (piece) => { const state = store.getState(); const board = state.shogi.board; const holdingPiece = state.shogi.holdingPiece; if (!holdingPiece) { // FIX: holdingPiece equals piece. It's confusing. dispatch(holdPiece(piece)); dispatch(enhanceCanDropPosition(piece)); return; } } }; }; const CapturedPiece = connect( mapStateToProps, mapDispatchToProps )(pieceComponent); export default CapturedPiece;
import React from 'react'; import { connect } from 'react-redux'; import pieceComponent from '../components/piece'; import { holdPiece, enhanceCanDropPosition } from '../actions'; import store from '../stores/index'; const mapStateToProps = (state) => { return { }; }; const mapDispatchToProps = (dispatch) => { return { onPieceClick: (piece) => { const state = store.getState(); const board = state.shogi.board(); const holdingPiece = state.shogi.holdingPiece; if (!holdingPiece) { // FIX: holdingPiece equals piece. It's confusing. dispatch(holdPiece(piece)); dispatch(enhanceCanDropPosition(piece)); return; } } }; }; const CapturedPiece = connect( mapStateToProps, mapDispatchToProps )(pieceComponent); export default CapturedPiece;
Update default client registration implementation
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */package org.xdi.model.custom.script.type.client; import java.util.Map; import org.xdi.model.SimpleCustomProperty; /** * Dummy implementation of interface ClientRegistrationType * * @author Yuriy Movchan Date: 11/11/2014 */ public class DummyClientRegistrationType implements ClientRegistrationType { @Override public boolean init(Map<String, SimpleCustomProperty> configurationAttributes) { return true; } @Override public boolean destroy(Map<String, SimpleCustomProperty> configurationAttributes) { return true; } @Override public int getApiVersion() { return 1; } @Override public boolean createClient(Object registerRequest, Object client, Map<String, SimpleCustomProperty> configurationAttributes) { return false; } @Override public boolean updateClient(Object registerRequest, Object client, Map<String, SimpleCustomProperty> configurationAttributes) { return false; } }
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */package org.xdi.model.custom.script.type.client; import java.util.Map; import org.xdi.model.SimpleCustomProperty; /** * Dummy implementation of interface ClientRegistrationType * * @author Yuriy Movchan Date: 11/11/2014 */ public class DummyClientRegistrationType implements ClientRegistrationType { @Override public boolean init(Map<String, SimpleCustomProperty> configurationAttributes) { return true; } @Override public boolean destroy(Map<String, SimpleCustomProperty> configurationAttributes) { return true; } @Override public int getApiVersion() { return 1; } @Override public boolean updateClient(Object registerRequest, Object client, Map<String, SimpleCustomProperty> configurationAttributes) { return false; } }
Use PORT env var with 5000 fallback Makes more sense IMO since the example site uses PORT=3000 but not this generated website, and 5000 seems to be the default of `tux-scripts start`. This approach solves both issues really, since it allows the user to set their own port, or just use the default.
import React from 'react' import createContentfulAdapter from 'tux-adapter-contentful' import tux from './middleware/tux' import history from 'react-chain-history' import createReactChain from 'react-chain' import Home from './home' import './index.css' const publicUrl = process.env.PUBLIC_URL ? process.env.PUBLIC_URL : process.env.SERVER ? `https://localhost:${process.env.PORT || '5000'}` : `${location.protocol}//${location.host}/` // Get your Contentful clientId (application Uid) from https://app.contentful.com/account/profile/developers/applications const adapter = createContentfulAdapter({ space: process.env.TUX_CONTENTFUL_SPACE_ID, accessToken: process.env.TUX_CONTENTFUL_ACCESS_TOKEN, clientId: process.env.TUX_CONTENTFUL_CLIENT_ID, redirectUri: publicUrl, }) export default createReactChain() .chain(history()) .chain(tux({ adapter })) .chain(() => () => <Home />)
import React from 'react' import createContentfulAdapter from 'tux-adapter-contentful' import tux from './middleware/tux' import history from 'react-chain-history' import createReactChain from 'react-chain' import Home from './home' import './index.css' const publicUrl = process.env.PUBLIC_URL ? process.env.PUBLIC_URL : process.env.SERVER ? 'https://localhost:3000' : `${location.protocol}//${location.host}/` // Get your Contentful clientId (application Uid) from https://app.contentful.com/account/profile/developers/applications const adapter = createContentfulAdapter({ space: process.env.TUX_CONTENTFUL_SPACE_ID, accessToken: process.env.TUX_CONTENTFUL_ACCESS_TOKEN, clientId: process.env.TUX_CONTENTFUL_CLIENT_ID, redirectUri: publicUrl, }) export default createReactChain() .chain(history()) .chain(tux({ adapter })) .chain(() => () => <Home />)
Add an additional property assayStr SVN-Revision: 7349
package gov.nih.nci.calab.dto.workflow; public class AssayBean { private String assayId; private String assayName; private String assayType; private String assayStr; public AssayBean(String assayId, String assayName, String assayType) { super(); // TODO Auto-generated constructor stub this.assayId = assayId; this.assayName = assayName; this.assayType = assayType; } public String getAssayId() { return assayId; } public void setAssayId(String assayId) { this.assayId = assayId; } public String getAssayName() { return assayName; } public void setAssayName(String assayName) { this.assayName = assayName; } public String getAssayType() { return assayType; } public void setAssayType(String assayType) { this.assayType = assayType; } public String getAssayStr() { return this.assayType + " : " + this.assayName; } // public void setAssayStr(String assayStr) { // this.assayStr = assayStr; // } }
package gov.nih.nci.calab.dto.workflow; public class AssayBean { private String assayId; private String assayName; private String assayType; public AssayBean(String assayId, String assayName, String assayType) { super(); // TODO Auto-generated constructor stub this.assayId = assayId; this.assayName = assayName; this.assayType = assayType; } public String getAssayId() { return assayId; } public void setAssayId(String assayId) { this.assayId = assayId; } public String getAssayName() { return assayName; } public void setAssayName(String assayName) { this.assayName = assayName; } public String getAssayType() { return assayType; } public void setAssayType(String assayType) { this.assayType = assayType; } }
Rename bootstrap-sass Gulp task to 'sass'
var gulp = require('gulp'); var sass = require('gulp-sass'); // Common paths. var paths = { BootstrapSCSS: 'priv/assets/bootstrap-custom/bootstrap-custom.scss', BootstrapInclude: 'priv/components/bootstrap-sass/assets/stylesheets', } // Build admin CSS from SASS/CSS gulp.task('sass', function() { return gulp.src(paths.BootstrapSCSS) .pipe(sass({ trace: true, style: 'compressed', includePaths: [paths.BootstrapInclude] })) .pipe(gulp.dest('priv/static/css')); }); // Watch for changes. gulp.task('watch', function () { gulp.watch(paths.BootstrapSCSS, ['sass']); }); // Default gulp task. gulp.task('default', ['sass']);
var gulp = require('gulp'); var sass = require('gulp-sass'); // Common paths. var paths = { BootstrapSCSS: 'priv/assets/bootstrap-custom/bootstrap-custom.scss', BootstrapInclude: 'priv/components/bootstrap-sass/assets/stylesheets', } // Build admin CSS from SASS/CSS gulp.task('bootstrap-sass', function() { return gulp.src(paths.BootstrapSCSS) .pipe(sass({ trace: true, style: 'compressed', includePaths: [paths.BootstrapInclude] })) .pipe(gulp.dest('priv/static/css')); }); // Watch for changes. gulp.task('watch', function () { gulp.watch(paths.BootstrapSCSS, ['bootstrap-sass']); }); // Default gulp task. gulp.task('default', ['bootstrap-sass']);
Update modal creator with new heading markup.
<?php /** * Snippet for displaying a Campaign's creator property, which is an array. * * For available variables: * @see dosomething_campaign_load(). */ ?> <div class="promotion promotion--creator"> <a class="wrapper" href="#" data-modal-href="#modal--creator"> <p class="__copy"><?php print t('Created by'); ?></p> <div class="__image"> <img src="<?php print $picture['src_square']; ?>" /> </div> </a> <div data-modal id="modal--creator" class="modal--creator" role="dialog"> <a href="#" class="js-close-modal modal-close-button">×</a> <h2 class="heading -banner">The Creator</h2> <div class="wrapper"> <div class="__member"> <img src="<?php print $picture['src_square']; ?>" /> </div> <div class="__body"> <h4 class="__title heading -delta"><?php print $first_name; ?> <?php print $last_initial; ?></h4> <p class="__location"><?php print $city; ?>, <?php print $state; ?></p> <div class="copy"><?php print $copy; ?></div> <a href="#" class="js-close-modal">Back to main page</a> </div> </div> </div> </div>
<?php /** * Snippet for displaying a Campaign's creator property, which is an array. * * For available variables: * @see dosomething_campaign_load(). */ ?> <div class="promotion promotion--creator"> <a class="wrapper" href="#" data-modal-href="#modal--creator"> <p class="__copy"><?php print t('Created by'); ?></p> <div class="__image"> <img src="<?php print $picture['src_square']; ?>" /> </div> </a> <div data-modal id="modal--creator" class="modal--creator" role="dialog"> <a href="#" class="js-close-modal modal-close-button white">×</a> <h2 class="banner">The Creator</h2> <div class="wrapper"> <div class="__member"> <img src="<?php print $picture['src_square']; ?>" /> </div> <div class="__body"> <h4 class="__title heading -delta"><?php print $first_name; ?> <?php print $last_initial; ?></h4> <p class="__location"><?php print $city; ?>, <?php print $state; ?></p> <div class="copy"><?php print $copy; ?></div> <a href="#" class="js-close-modal">Back to main page</a> </div> </div> </div> </div>
Add class docblock explaining the dependency on the LocaleListener
<?php namespace OpenConext\EngineBlockBridge\EventListener; use EngineBlock_ApplicationSingleton; use OpenConext\EngineBlockBundle\Localization\LocaleProvider; use Zend_Translate_Adapter; /** * This listener depends on the LocaleListener in the EngineBlockBundle, so the priority should be set so that it is * called after the LocaleListener. */ final class SetCortoTranslationsLocaleListener { /** * @var LocaleProvider */ private $localeProvider; /** * @var Zend_Translate_Adapter */ private $translator; public function __construct(LocaleProvider $localeProvider) { $this->localeProvider = $localeProvider; $this->translator = EngineBlock_ApplicationSingleton::getInstance()->getTranslator()->getAdapter(); } public function onKernelRequest() { $locale = $this->localeProvider->getLocale(); $this->translator->setLocale($locale); } }
<?php namespace OpenConext\EngineBlockBridge\EventListener; use EngineBlock_ApplicationSingleton; use OpenConext\EngineBlockBundle\Localization\LocaleProvider; use Zend_Translate_Adapter; final class SetCortoTranslationsLocaleListener { /** * @var LocaleProvider */ private $localeProvider; /** * @var Zend_Translate_Adapter */ private $translator; public function __construct(LocaleProvider $localeProvider) { $this->localeProvider = $localeProvider; $this->translator = EngineBlock_ApplicationSingleton::getInstance()->getTranslator()->getAdapter(); } public function onKernelRequest() { $locale = $this->localeProvider->getLocale(); $this->translator->setLocale($locale); } }
Remove non required if else statement
package com.catpeds.rest.resource; import java.util.Objects; import org.springframework.hateoas.ResourceSupport; import com.catpeds.model.Pedigree; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * {@link Pedigree}'s {@link ResourceSupport} * * @author padriano * */ public class PedigreeResource extends ResourceSupport { /** * Pedigree information content */ private final Pedigree pedigree; @JsonCreator public PedigreeResource(@JsonProperty("pedigree") Pedigree pedigree) { this.pedigree = pedigree; } /** * @see #pedigree * * @return the pedigree */ public Pedigree getPedigree() { return pedigree; } /** * @see org.springframework.hateoas.ResourceSupport#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } return Objects.equals(pedigree, ((PedigreeResource) obj).getPedigree()); } /** * @see org.springframework.hateoas.ResourceSupport#hashCode() */ @Override public int hashCode() { return Objects.hash(super.hashCode(), pedigree); } }
package com.catpeds.rest.resource; import java.util.Objects; import org.springframework.hateoas.ResourceSupport; import com.catpeds.model.Pedigree; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * {@link Pedigree}'s {@link ResourceSupport} * * @author padriano * */ public class PedigreeResource extends ResourceSupport { /** * Pedigree information content */ private final Pedigree pedigree; @JsonCreator public PedigreeResource(@JsonProperty("pedigree") Pedigree pedigree) { this.pedigree = pedigree; } /** * @see #pedigree * * @return the pedigree */ public Pedigree getPedigree() { return pedigree; } /** * @see org.springframework.hateoas.ResourceSupport#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } if (Objects.equals(pedigree, ((PedigreeResource) obj).getPedigree())) { return true; } return false; } /** * @see org.springframework.hateoas.ResourceSupport#hashCode() */ @Override public int hashCode() { return Objects.hash(super.hashCode(), pedigree); } }
Split line to avoid flake8 warning
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = 'GU Comics' language = 'en' url = 'http://www.gucomics.com/' start_date = '2000-07-10' rights = 'Woody Hearn' class Crawler(CrawlerBase): history_capable_date = '2000-07-10' schedule = 'Mo,We,Fr' time_zone = 'US/Eastern' def crawl(self, pub_date): page_url = 'http://www.gucomics.com/' + pub_date.strftime('%Y%m%d') page = self.parse_page(page_url) title = page.text('b') title = title.replace('"', '') title = title.strip() text = page.text('font[class="main"]') # If there is a --- the text after is not about the comic text = text[:text.find('---')] text = text.strip() url = 'http://www.gucomics.com/comics/' + pub_date.strftime( '%Y/gu_%Y%m%d')+'.jpg' return CrawlerImage(url, title, text)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = 'GU Comics' language = 'en' url = 'http://www.gucomics.com/' start_date = '2000-07-10' rights = 'Woody Hearn' class Crawler(CrawlerBase): history_capable_date = '2000-07-10' schedule = 'Mo,We,Fr' time_zone = 'US/Eastern' def crawl(self, pub_date): page_url = 'http://www.gucomics.com/' + pub_date.strftime('%Y%m%d') page = self.parse_page(page_url) title = page.text('b') title = title.replace('"', '') title = title.strip() text = page.text('font[class="main"]') # If there is a --- the text after is not about the comic text = text[:text.find('---')] text = text.strip() url = 'http://www.gucomics.com/comics/' + pub_date.strftime('%Y/gu_%Y%m%d')+'.jpg' return CrawlerImage(url, title, text)
Make the comment be concise
//Require Module var log4js = require('log4js'); var logger = log4js.getLogger('Logging'); /** * Excute mysql query and return the result. * * @Param {Object} db * @Param {String} query * @Param {function} callback * @Return {Object['affectedRows']} r * @Return {Object} err */ function excuteMySQLQuery (db,query,callback){ logger.debug('Testing Query:', query); db.query(query,function(err,result){ //If the result have error, return the error if(err){ callback(err); return; } var r = {affectedRows :0}; //If the result have affectedRows, save it in r return to be a result. if(result.affectedRows){ r['affectedRows'] = result['affectedRows']; } callback(null,r); }); } module.exports = { excuteMySQLQuery:excuteMySQLQuery }
//Require Module var log4js = require('log4js'); var logger = log4js.getLogger('Logging'); function excuteMySQLQuery (db,query,callback){ /** * Receive the database connection, query and callback function, * Then show the query which will be test at first. * After that, excute the query. * If the result have error, return the error, * Else if the result have affectedRows, save it in r return it. * Else,it will return null. * */ logger.debug('Testing Query:', query); db.query(query,function(err,result){ if(err){ callback(err); return; } var r = {affectedRows :0}; if(result.affectedRows){ r['affectedRows'] = result['affectedRows']; } callback(null,r); }); } module.exports = { excuteMySQLQuery:excuteMySQLQuery }
Increment minor version to 2.13 to prepare for a new release. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=155003222
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 13; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 12; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
Add save as pdf feature.
import sublime, sublime_plugin import os import re from subprocess import call from .mistune import markdown HTML_START = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' HTML_END = '</body></html>' class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) md_source = self.view.substr(region) md_source.encode(encoding='UTF-8',errors='strict') html_source = HTML_START + markdown(md_source) + HTML_END file_name = self.view.file_name() html_file = self.change_extension(file_name, ".html") with open(html_file, 'w+') as file_: file_.write(html_source) self.save_pdf(html_file) print(file_name) print(html_file) def change_extension(self,file_name, new_ext): f, ext = os.path.splitext(file_name) f += new_ext return f def save_pdf(self, html_file): pdf_file = self.change_extension(html_file, ".pdf") call(["wkhtmltopdf",html_file,pdf_file])
import sublime, sublime_plugin import os import re from .mistune import markdown HTML_START = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' HTML_END = '</body></html>' class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) md_source = self.view.substr(region) md_source.encode(encoding='UTF-8',errors='strict') html_source = HTML_START + markdown(md_source) + HTML_END file_name = self.view.file_name() html_file = self.change_extension(file_name, ".html") with open(html_file, 'w+') as file_: file_.write(html_source) print(file_name) print(html_file) def change_extension(self,file_name, new_ext): f, ext = os.path.splitext(file_name) f += new_ext return f
Change label 'Create Property' to 'Add Property'.
<?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Properties'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="property-index"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Add Property', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'headline', ['label'=>'Type', 'value'=> function ($property){ return $property->type->typeName; } ], 'address', 'city', 'county', 'state', 'acres', //'price', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
<?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Properties'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="property-index"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Create Property', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'headline', ['label'=>'Type', 'value'=> function ($property){ return $property->type->typeName; } ], 'address', 'city', 'county', 'state', 'acres', //'price', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
Improve confidence interval test code
package imagej.data.autoscale; import static org.junit.Assert.assertEquals; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.ops.util.Tuple2; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.ByteType; import org.junit.Test; import org.scijava.Context; public class ConfidenceIntervalAutoscaleMethodTest { Context context = new Context(AutoscaleService.class); @Test public void test() { AutoscaleService service = context.getService(AutoscaleService.class); AutoscaleMethod method = service.getAutoscaleMethod("95% CI"); Img<RealType> img = getImg(); Tuple2<Double, Double> range = method.getRange(img); // System.out.println(range.get1()); // System.out.println(range.get2()); assertEquals(2, range.get1(), 0); assertEquals(97, range.get2(), 0); } private Img<RealType> getImg() { Img<ByteType> img = ArrayImgs.bytes(100); byte i = 0; for (ByteType b : img) b.set(i++); return (Img<RealType>) (Img) img; } }
package imagej.data.autoscale; import static org.junit.Assert.assertTrue; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.ops.util.Tuple2; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.ByteType; import org.junit.Test; import org.scijava.Context; public class ConfidenceIntervalAutoscaleMethodTest { Context context = new Context(AutoscaleService.class); @Test public void test() { AutoscaleService service = context.getService(AutoscaleService.class); AutoscaleMethod method = service.getAutoscaleMethod("95% CI"); Img<RealType> img = getImg(); Tuple2<Double, Double> range = method.getRange(img); System.out.println(range.get1()); System.out.println(range.get2()); assertTrue(true); } private Img<RealType> getImg() { Img<ByteType> img = ArrayImgs.bytes(100); byte i = 0; for (ByteType b : img) b.set(i++); return (Img<RealType>) (Img) img; } }
Add mail_certificate which sends email with flask-mail Replace COMMAND_MAIL. Send certs from /etc/openvpn/client/ Use template /templates/mail.txt
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request from flask import Flask, render_template from flask_mail import Mail, Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/client/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) call([app.config['COMMAND_MAIL'], request.id, request.email]) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
Include a slug for the upcoming event
<?php // Copyright 2019 Peter Beverloo. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. error_reporting((E_ALL | E_STRICT) & ~E_WARNING); ini_set('display_errors', 1); require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/error.php'; Header('Access-Control-Allow-Origin: *'); Header('Content-Type: application/json'); $environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']); if (!$environment->isValid()) dieWithError('Unrecognized volunteer portal environment.'); echo json_encode([ 'contactName' => 'Peter', 'contactTarget' => 'mailto:' . $environment->getContact(), 'title' => $environment->getName(), 'events' => [ [ 'name' => 'AnimeCon 2021', 'enablePortal' => false, 'enableRegistration' => false, 'slug' => '2021', 'timezone' => 'Europe/Amsterdam', 'website' => 'https://www.animecon.nl/', ], ], ]);
<?php // Copyright 2019 Peter Beverloo. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. error_reporting((E_ALL | E_STRICT) & ~E_WARNING); ini_set('display_errors', 1); require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/error.php'; Header('Access-Control-Allow-Origin: *'); Header('Content-Type: application/json'); $environment = \Anime\Environment::createForHostname($_SERVER['HTTP_HOST']); if (!$environment->isValid()) dieWithError('Unrecognized volunteer portal environment.'); echo json_encode([ 'contactName' => 'Peter', 'contactTarget' => 'mailto:' . $environment->getContact(), 'title' => $environment->getName(), 'events' => [ [ 'name' => 'AnimeCon 2021', 'enablePortal' => false, 'enableRegistration' => false, 'timezone' => 'Europe/Amsterdam', 'website' => 'https://www.animecon.nl/', ], ], ]);
Add default empty code to sensors created through sensor manager
// Default sensor generator. const createSensor = ({ id, macAddress, name, location, batteryLevel, isActive, logInterval }) => ({ id, macAddress, name, location, batteryLevel, isActive, logInterval, }); class SensorManager { constructor(dbService, utils) { this.db = dbService; this.utils = utils; this.createSensorFunc = createSensor; } set sensorCreator(createSensorFunc) { this.createSensorFunc = createSensorFunc; } get sensorCreator() { return this.createSensorFunc; } createSensor = async ({ location: newLocation, logInterval, macAddress, name }) => { const id = this.utils.createUuid(); let location = newLocation; if (!newLocation) { const locations = await this.db.getLocations(); [location] = locations; } return this.sensorCreator({ id, macAddress, name, location, logInterval, code: '', batteryLevel: 0, isActive: true, }); }; saveSensor = async sensor => this.db.upsertSensor(sensor); } let SensorManagerInstance; export const getSensorManagerInstance = (dbService, utils) => { if (!SensorManagerInstance) { SensorManagerInstance = new SensorManager(dbService, utils); } return SensorManagerInstance; }; export default getSensorManagerInstance;
// Default sensor generator. const createSensor = ({ id, macAddress, name, location, batteryLevel, isActive, logInterval }) => ({ id, macAddress, name, location, batteryLevel, isActive, logInterval, }); class SensorManager { constructor(dbService, utils) { this.db = dbService; this.utils = utils; this.createSensorFunc = createSensor; } set sensorCreator(createSensorFunc) { this.createSensorFunc = createSensorFunc; } get sensorCreator() { return this.createSensorFunc; } createSensor = async ({ location: newLocation, logInterval, macAddress, name }) => { const id = this.utils.createUuid(); let location = newLocation; if (!newLocation) { const locations = await this.db.getLocations(); [location] = locations; } return this.sensorCreator({ id, macAddress, name, location, batteryLevel: 0, isActive: true, logInterval, }); }; saveSensor = async sensor => this.db.upsertSensor(sensor); } let SensorManagerInstance; export const getSensorManagerInstance = (dbService, utils) => { if (!SensorManagerInstance) { SensorManagerInstance = new SensorManager(dbService, utils); } return SensorManagerInstance; }; export default getSensorManagerInstance;
Add markup to table to make AJAX update it.
<?php if(isset($CreateGameMessage)) { echo $CreateGameMessage; } ?> <table class="standard" id="GameList" class="ajax"> <tr> <th>Players</th> <th>Current Turn</th> <th></th> </tr><?php foreach($ChessGames as $ChessGame) { ?> <tr> <td><?php echo $ChessGame->getWhitePlayer()->getLinkedDisplayName(false); ?> vs <?php echo $ChessGame->getBlackPlayer()->getLinkedDisplayName(false); ?> </td> <td><?php echo $ChessGame->getCurrentTurnPlayer()->getLinkedDisplayName(false); ?> </td> <td> <div class="buttonA"><a class="buttonA" href="<?php echo $ChessGame->getPlayGameHREF(); ?>">&nbsp;Play&nbsp;</a></div> </td> </tr><?php } ?> </table> <form action="<?php echo Globals::getChessCreateHREF(); ?>" method="POST"> <label for="player_id">Challenge: </label> <select id="player_id" name="player_id"><?php foreach($PlayerList as $PlayerID => $PlayerName) { ?><option value="<?php echo $PlayerID; ?>"><?php echo $PlayerName; ?></option><?php } ?> </select><br/> <input type="submit"/> </form>
<?php if(isset($CreateGameMessage)) { echo $CreateGameMessage; } ?> <table class="standard"> <tr> <th>Players</th> <th>Current Turn</th> <th></th> </tr><?php foreach($ChessGames as $ChessGame) { ?> <tr> <td><?php echo $ChessGame->getWhitePlayer()->getLinkedDisplayName(false); ?> vs <?php echo $ChessGame->getBlackPlayer()->getLinkedDisplayName(false); ?> </td> <td><?php echo $ChessGame->getCurrentTurnPlayer()->getLinkedDisplayName(false); ?> </td> <td> <div class="buttonA"><a class="buttonA" href="<?php echo $ChessGame->getPlayGameHREF(); ?>">&nbsp;Play&nbsp;</a></div> </td> </tr><?php } ?> </table> <form action="<?php echo Globals::getChessCreateHREF(); ?>" method="POST"> <label for="player_id">Challenge: </label> <select id="player_id" name="player_id"><?php foreach($PlayerList as $PlayerID => $PlayerName) { ?><option value="<?php echo $PlayerID; ?>"><?php echo $PlayerName; ?></option><?php } ?> </select><br/> <input type="submit"/> </form>
Fix Pref Selection schedule reference
import React, { Component} from 'react'; import { inject, observer } from 'mobx-react'; import TextRow from '../fields/TextRow'; import CheckRow from '../fields/CheckRow'; import CheckValueRow from '../fields/CheckValueRow'; import SelectRow from '../fields/SelectRow'; import { times, days } from './schedule.fixture' @inject('view_store') @observer class SpeedTabPanel extends Component { render() { return ( <div> <h3>Speed Limits</h3> <CheckValueRow idCheck='speed-limit-up-enabled' idValue='speed-limit-up' label='Upload (kB/s)'/> <CheckValueRow idCheck='speed-limit-down-enabled' idValue='speed-limit-down' label='Download (kB/s)'/> <h3>Alternative Speed Limits</h3> <p>Override normal speed limits manually or at scheduled times</p> <TextRow id='alt-speed-up' label='Upload (kB/s)'/> <TextRow id='alt-speed-down' label='Download (kB/s)'/> <CheckRow id='alt-speed-time-enabled' label='Scheduled Times'/> <SelectRow id='alt-speed-time-begin' label='From' options={times}/> <SelectRow id='alt-speed-time-end' label='To' options={times}/> <SelectRow id='alt-speed-time-day' label='On days' options={days}/> </div> ); } } export default SpeedTabPanel;
import React, { Component} from 'react'; import { inject, observer } from 'mobx-react'; import TextRow from '../fields/TextRow'; import CheckRow from '../fields/CheckRow'; import CheckValueRow from '../fields/CheckValueRow'; import SelectRow from '../fields/SelectRow'; import { times, days } from './schedule' @inject('view_store') @observer class SpeedTabPanel extends Component { render() { return ( <div> <h3>Speed Limits</h3> <CheckValueRow idCheck='speed-limit-up-enabled' idValue='speed-limit-up' label='Upload (kB/s)'/> <CheckValueRow idCheck='speed-limit-down-enabled' idValue='speed-limit-down' label='Download (kB/s)'/> <h3>Alternative Speed Limits</h3> <p>Override normal speed limits manually or at scheduled times</p> <TextRow id='alt-speed-up' label='Upload (kB/s)'/> <TextRow id='alt-speed-down' label='Download (kB/s)'/> <CheckRow id='alt-speed-time-enabled' label='Scheduled Times'/> <SelectRow id='alt-speed-time-begin' label='From' options={times}/> <SelectRow id='alt-speed-time-end' label='To' options={times}/> <SelectRow id='alt-speed-time-day' label='On days' options={days}/> </div> ); } } export default SpeedTabPanel;
Add possibility of custom country list.
<?php session_start(); error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT); define("DOC_ROOT", str_replace("/core/inc", "", str_replace("\\", "/", __DIR__))); require_once(DOC_ROOT."/core/inc/constants.php"); require_once(DOC_ROOT."/core/inc/functions.php"); require_once(filePath("inc/country_list.php")); require_once(DOC_ROOT."/core/entity/entity.php"); require_once(DOC_ROOT."/core/entity/l10n_entity.php"); require_once(DOC_ROOT."/core/controller/controller.php"); require_once(DOC_ROOT."/core/model/model.php"); require_once(DOC_ROOT."/core/class/mail_message.php"); if (file_exists(DOC_ROOT."/extend/inc/constants.php")) require_once(DOC_ROOT."/extend/inc/constants.php"); if (file_exists(DOC_ROOT."/extend/inc/functions.php")) require_once(DOC_ROOT."/extend/inc/functions.php"); $Config = newClass("Config"); $Db = newClass("Db"); $Db->debug = $Config->getDebug(); $dbc = $Config->getDatabase(); $Db->connect($dbc["user"], $dbc["pass"], $dbc["db"], $dbc["host"]); $ControllerFactory = newClass("ControllerFactory", $Config, $Db);
<?php session_start(); error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT); define("DOC_ROOT", str_replace("/core/inc", "", str_replace("\\", "/", __DIR__))); require_once(DOC_ROOT."/core/inc/constants.php"); require_once(DOC_ROOT."/core/inc/functions.php"); require_once(DOC_ROOT."/core/inc/country_list.php"); require_once(DOC_ROOT."/core/entity/entity.php"); require_once(DOC_ROOT."/core/entity/l10n_entity.php"); require_once(DOC_ROOT."/core/controller/controller.php"); require_once(DOC_ROOT."/core/model/model.php"); require_once(DOC_ROOT."/core/class/mail_message.php"); if (file_exists(DOC_ROOT."/extend/inc/constants.php")) require_once(DOC_ROOT."/extend/inc/constants.php"); if (file_exists(DOC_ROOT."/extend/inc/functions.php")) require_once(DOC_ROOT."/extend/inc/functions.php"); $Config = newClass("Config"); $Db = newClass("Db"); $Db->debug = $Config->getDebug(); $dbc = $Config->getDatabase(); $Db->connect($dbc["user"], $dbc["pass"], $dbc["db"], $dbc["host"]); $ControllerFactory = newClass("ControllerFactory", $Config, $Db);
Remove dead code in phantomjs server.
"use strict"; var system = require("system"); if (system.args.length < 2) { console.log("Missing arguments."); phantom.exit(); } var url = system.args[1]; var renderHtml = function(url, cb) { var page = require("webpage").create(); var finished = false; page.settings.loadImages = false; page.settings.localToRemoteUrlAccessEnabled = true; page.onCallback = function() { setTimeout(function() { if (!finished) { cb(page.content); page.close(); finished = true; } }, 100); }; page.onInitialized = function() { page.evaluate(function() { document.addEventListener("__htmlReady__", function() { window.callPhantom(); }, false); }); }; page.open(url); setTimeout(function() { if (!finished) { cb(page.content); page.close(); finished = true; } }, 10000); }; renderHtml(url, function(html) { console.log(html); phantom.exit(); });
"use strict"; var system = require("system"); if (system.args.length < 2) { console.log("Missing arguments."); phantom.exit(); } var server = require("webserver").create(); var url = system.args[1]; var renderHtml = function(url, cb) { var page = require("webpage").create(); var finished = false; page.settings.loadImages = false; page.settings.localToRemoteUrlAccessEnabled = true; page.onCallback = function() { setTimeout(function() { if (!finished) { cb(page.content); page.close(); finished = true; } }, 100); }; page.onInitialized = function() { page.evaluate(function() { document.addEventListener("__htmlReady__", function() { window.callPhantom(); }, false); }); }; page.open(url); setTimeout(function() { if (!finished) { cb(page.content); page.close(); finished = true; } }, 10000); }; renderHtml(url, function(html) { console.log(html); phantom.exit(); });
Increase number of cronjobs on cronjob list page to 100 Close #2953
<?php namespace wcf\acp\page; use wcf\data\cronjob\CronjobList; use wcf\page\SortablePage; /** * Shows information about configured cron jobs. * * @author Alexander Ebert * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Page * * @property CronjobList $objectList */ class CronjobListPage extends SortablePage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.cronjob.list'; /** * @inheritDoc */ public $neededPermissions = ['admin.management.canManageCronjob']; /** * @inheritDoc */ public $defaultSortField = 'cronjobID'; /** * @inheritDoc */ public $itemsPerPage = 100; /** * @inheritDoc */ public $validSortFields = ['cronjobID', 'nextExec', 'startMinute', 'startHour', 'startDom', 'startMonth', 'startDow']; /** * @inheritDoc */ public $objectListClassName = CronjobList::class; /** * @inheritDoc */ public function initObjectList() { parent::initObjectList(); $this->sqlOrderBy = "cronjob.".$this->sortField." ".$this->sortOrder; } }
<?php namespace wcf\acp\page; use wcf\data\cronjob\CronjobList; use wcf\page\SortablePage; /** * Shows information about configured cron jobs. * * @author Alexander Ebert * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Page * * @property CronjobList $objectList */ class CronjobListPage extends SortablePage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.cronjob.list'; /** * @inheritDoc */ public $neededPermissions = ['admin.management.canManageCronjob']; /** * @inheritDoc */ public $defaultSortField = 'cronjobID'; /** * @inheritDoc */ public $validSortFields = ['cronjobID', 'nextExec', 'startMinute', 'startHour', 'startDom', 'startMonth', 'startDow']; /** * @inheritDoc */ public $objectListClassName = CronjobList::class; /** * @inheritDoc */ public function initObjectList() { parent::initObjectList(); $this->sqlOrderBy = "cronjob.".$this->sortField." ".$this->sortOrder; } }
Remove obsolete error class 'DatabaseDriverError'
<?php /* * PHP-Auth (https://github.com/delight-im/PHP-Auth) * Copyright (c) delight.im (https://www.delight.im/) * Licensed under the MIT License (https://opensource.org/licenses/MIT) */ namespace Delight\Auth; class AuthException extends \Exception {} class UnknownIdException extends AuthException {} class InvalidEmailException extends AuthException {} class UnknownUsernameException extends AuthException {} class InvalidPasswordException extends AuthException {} class EmailNotVerifiedException extends AuthException {} class UserAlreadyExistsException extends AuthException {} class NotLoggedInException extends AuthException {} class InvalidSelectorTokenPairException extends AuthException {} class TokenExpiredException extends AuthException {} class TooManyRequestsException extends AuthException {} class DuplicateUsernameException extends AuthException {} class AmbiguousUsernameException extends AuthException {} class AttemptCancelledException extends AuthException {} class ResetDisabledException extends AuthException {} class ConfirmationRequestNotFound extends AuthException {} class AuthError extends \Exception {} class DatabaseError extends AuthError {} class MissingCallbackError extends AuthError {} class HeadersAlreadySentError extends AuthError {} class EmailOrUsernameRequiredError extends AuthError {}
<?php /* * PHP-Auth (https://github.com/delight-im/PHP-Auth) * Copyright (c) delight.im (https://www.delight.im/) * Licensed under the MIT License (https://opensource.org/licenses/MIT) */ namespace Delight\Auth; class AuthException extends \Exception {} class UnknownIdException extends AuthException {} class InvalidEmailException extends AuthException {} class UnknownUsernameException extends AuthException {} class InvalidPasswordException extends AuthException {} class EmailNotVerifiedException extends AuthException {} class UserAlreadyExistsException extends AuthException {} class NotLoggedInException extends AuthException {} class InvalidSelectorTokenPairException extends AuthException {} class TokenExpiredException extends AuthException {} class TooManyRequestsException extends AuthException {} class DuplicateUsernameException extends AuthException {} class AmbiguousUsernameException extends AuthException {} class AttemptCancelledException extends AuthException {} class ResetDisabledException extends AuthException {} class ConfirmationRequestNotFound extends AuthException {} class AuthError extends \Exception {} class DatabaseError extends AuthError {} class DatabaseDriverError extends DatabaseError {} class MissingCallbackError extends AuthError {} class HeadersAlreadySentError extends AuthError {} class EmailOrUsernameRequiredError extends AuthError {}
Fix indentation; override old-style start() from BackendBase
from urllib import urlencode from urllib2 import urlopen from rapidsms.backends.base import BackendBase class TropoBackend(BackendBase): """A RapidSMS threadless backend for Tropo""" def configure(self, config=None, **kwargs): self.config = config def start(self): """Override BackendBase.start(), which never returns""" self._running = True def send(self, message): self.debug("send(%s)" % message) base_url = 'http://api.tropo.com/1.0/sessions' token = self.config['auth_token'] action = 'create' number = self.config['number'] params = urlencode([('action', action), ('token', token), ('numberToDial', message.connection.identity), ('msg', message.text)]) self.debug("%s?%s" % (base_url, params)) data = urlopen('%s?%s' % (base_url, params)).read() self.debug(data) return True
from urllib import urlencode from urllib2 import urlopen from rapidsms.backends.base import BackendBase class TropoBackend(BackendBase): """A RapidSMS threadless backend for Tropo""" def configure(self, config=None, **kwargs): self.config = config super(TropoBackend, self).configure(**kwargs) def send(self, message): base_url = 'http://api.tropo.com/1.0/sessions' token = self.config['auth_token'] action = 'create' number = self.config['number'] params = urlencode([('action', action), ('token', token), ('numberToDial', message.connection.identity), ('msg', message.text)]) self.debug("%s?%s" % (base_url, params)) data = urlopen('%s?%s' % (base_url, params)).read() self.debug(data)
Improve error message and imports
from typing import IO, Text import re from logging import getLogger from io import StringIO import yaml NBSP = "\u00A0" pattern = re.compile(r"^\s*[\u00A0]+\s*", re.MULTILINE) logger = getLogger(__name__) def _replace_nbsp(origdata): counter = 0 def _replacer_func(matchobj): nonlocal counter counter += 1 string = matchobj.group(0) rc = string.replace(NBSP, " ") return rc data = pattern.sub(_replacer_func, origdata) if counter: plural = "s were" if counter > 1 else " was" logger.warn( f"Note: {counter} lines with non-breaking space character{plural} detected in cumulusci.yml.\n" "Perhaps you cut and pasted from a Web page?\n" "Future versions of CumulusCI may disallow these characters.\n" ) return data def cci_safe_load(f_config: IO[Text]): "Load a file, convert NBSP->space and parse it in YAML." data = _replace_nbsp(f_config.read()) rc = yaml.safe_load(StringIO(data)) return rc
from typing import IO, Text from re import compile, MULTILINE from logging import getLogger from io import StringIO import yaml NBSP = "\u00A0" pattern = compile(r"^\s*[\u00A0]+\s*", MULTILINE) logger = getLogger(__name__) def _replace_nbsp(origdata): counter = 0 def _replacer_func(matchobj): nonlocal counter counter += 1 string = matchobj.group(0) rc = string.replace(NBSP, " ") return rc data = pattern.sub(_replacer_func, origdata) if counter: plural = "s were" if counter > 1 else " was" logger.warn( f"Note: {counter} non-breaking space character{plural} detected in cumulusci.yml.\n" "Perhaps you cut and pasted it from a Web page.\n" "Future versions of CumulusCI may disallow these characters.\n" ) return data def cci_safe_load(f_config: IO[Text]): "Load a file, convert NBSP->space and parse it in YAML." data = _replace_nbsp(f_config.read()) rc = yaml.safe_load(StringIO(data)) return rc
Select features using classification model
import pandas as pd from sklearn.feature_selection import SelectKBest, f_classif def select_kbest_clf(data_frame, target, k=4): """ Selecting K-Best features for classification :param data_frame: A pandas dataFrame with the training data :param target: target variable name in DataFrame :param k: desired number of features from the data :returns feature_scores: scores for each feature in the data as pandas DataFrame """ feat_selector = SelectKBest(f_classif, k=k) _ = feat_selector.fit(data_frame.drop(target, axis=1), data_frame[target]) feat_scores = pd.DataFrame() feat_scores["F Score"] = feat_selector.scores_ feat_scores["P Value"] = feat_selector.pvalues_ feat_scores["Support"] = feat_selector.get_support() feat_scores["Attribute"] = data_frame.drop(target, axis=1).columns return feat_scores df = pd.read_csv("NABIL.csv") df.drop(df.columns[[0,1,9,13]], axis=1, inplace=True) df.drop(df.index[:19],inplace=True) kbest_feat = select_kbest_clf(df, 'Updown', k=4) kbest_feat = kbest_feat.sort(["F Score", "P Value"], ascending=[False, False]) print("\nFeature scores using classification method \n") print(kbest_feat)
import pandas as pd from sklearn.feature_selection import SelectKBest, f_classif def select_kbest_clf(data_frame, target, k=4): """ Selecting K-Best features for classification :param data_frame: A pandas dataFrame with the training data :param target: target variable name in DataFrame :param k: desired number of features from the data :returns feature_scores: scores for each feature in the data as pandas DataFrame """ feat_selector = SelectKBest(f_classif, k=k) _ = feat_selector.fit(data_frame.drop(target, axis=1), data_frame[target]) feat_scores = pd.DataFrame() feat_scores["F Score"] = feat_selector.scores_ feat_scores["P Value"] = feat_selector.pvalues_ feat_scores["Support"] = feat_selector.get_support() feat_scores["Attribute"] = data_frame.drop(target, axis=1).columns return feat_scores df = pd.read_csv("NABIL.csv") df.drop(df.columns[[1]], axis=1, inplace=True) #print(df.columns) kbest_feat = select_kbest_clf(df, 'Signal', k=4) kbest_feat = kbest_feat.sort(["F Score", "P Value"], ascending=[False, False]) print(kbest_feat)
Allow to be applied to constructors git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9919 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2008, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Mark a constructor or method as creating a resource * which requires cleanup. * The marked method must be a member of a class * marked with the CleanupObligation annotation. * * @author David Hovemeyer */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) public @interface CreatesObligation { }
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2008, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Mark a constructor or method as creating a resource * which requires cleanup. * The marked method must be a member of a class * marked with the CleanupObligation annotation. * * @author David Hovemeyer */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CreatesObligation { }
Format number as string or it errors in some webservers
from django.conf.urls.defaults import * import os.path urlpatterns = patterns('', url(r'^media/(?P<path>.+)?$', 'django.views.static.serve', { 'document_root': os.path.join(os.path.dirname(__file__), 'media'), 'show_indexes': True }, name='media'), url(r'^$', 'overseer.views.index', name='index'), url(r'^service/(?P<slug>[^/]+)/$', 'overseer.views.service', name='service'), url(r'^service/(?P<slug>[^/]+)/last-event/$', 'overseer.views.last_event', name='last_event'), url(r'^event/(?P<id>[^/]+)/$', 'overseer.views.event', name='event'), url(r'^(?P<id>\d+)$', 'django.views.generic.simple.redirect_to', {'url': 'event/%(id)s/'}, name='event_short'), url(r'^subscribe/$', 'overseer.views.create_subscription', name='create_subscription'), url(r'^subscription/(?P<ident>[^/]+)/$', 'overseer.views.update_subscription', name='update_subscription'), url(r'^subscription/(?P<ident>[^/]+)/verify/$', 'overseer.views.verify_subscription', name='verify_subscription'), )
from django.conf.urls.defaults import * import os.path urlpatterns = patterns('', url(r'^media/(?P<path>.+)?$', 'django.views.static.serve', { 'document_root': os.path.join(os.path.dirname(__file__), 'media'), 'show_indexes': True }, name='media'), url(r'^$', 'overseer.views.index', name='index'), url(r'^service/(?P<slug>[^/]+)/$', 'overseer.views.service', name='service'), url(r'^service/(?P<slug>[^/]+)/last-event/$', 'overseer.views.last_event', name='last_event'), url(r'^event/(?P<id>[^/]+)/$', 'overseer.views.event', name='event'), url(r'^(?P<id>\d+)$', 'django.views.generic.simple.redirect_to', {'url': 'event/%(id)d/'}, name='event_short'), url(r'^subscribe/$', 'overseer.views.create_subscription', name='create_subscription'), url(r'^subscription/(?P<ident>[^/]+)/$', 'overseer.views.update_subscription', name='update_subscription'), url(r'^subscription/(?P<ident>[^/]+)/verify/$', 'overseer.views.verify_subscription', name='verify_subscription'), )
Fix: Align text in code editor with component (remove padding)
import React from 'react'; import PropTypes from 'prop-types'; import Styled from 'rsg-components/Styled'; const styles = ({ fontFamily, color, space, fontSize }) => ({ root: { padding: [[space[1], space[2], space[1], space[1]]], fontFamily: fontFamily.base, fontSize: fontSize.small, color: color.light, backgroundColor: color.codeBackground, }, // Tweak CodeMirror styles. Duplicate selectors are for increased specificity '@global': { '.CodeMirror.CodeMirror': { fontFamily: fontFamily.monospace, height: 'auto', padding: [[space[0], space[2]]], fontSize: fontSize.small, }, '.CodeMirror.CodeMirror pre': { padding: 0, }, '.CodeMirror-scroll.CodeMirror-scroll': { height: 'auto', overflowY: 'hidden', overflowX: 'auto', }, '.cm-error.cm-error': { background: 'none', }, }, }); export function EditorLoaderRenderer({ classes }) { return ( <div className={classes.root}> Loading… </div> ); } EditorLoaderRenderer.propTypes = { classes: PropTypes.object.isRequired, }; export default Styled(styles)(EditorLoaderRenderer);
import React from 'react'; import PropTypes from 'prop-types'; import Styled from 'rsg-components/Styled'; const styles = ({ fontFamily, color, space, fontSize }) => ({ root: { padding: [[space[1], space[2], space[1], space[1]]], fontFamily: fontFamily.base, fontSize: fontSize.small, color: color.light, backgroundColor: color.codeBackground, }, // Tweak CodeMirror styles. Duplicate selectors are for increased specificity '@global': { '.CodeMirror.CodeMirror': { fontFamily: fontFamily.monospace, height: 'auto', padding: [[space[0], space[2]]], fontSize: fontSize.small, }, '.CodeMirror-scroll.CodeMirror-scroll': { height: 'auto', overflowY: 'hidden', overflowX: 'auto', }, '.cm-error.cm-error': { background: 'none', }, }, }); export function EditorLoaderRenderer({ classes }) { return ( <div className={classes.root}> Loading… </div> ); } EditorLoaderRenderer.propTypes = { classes: PropTypes.object.isRequired, }; export default Styled(styles)(EditorLoaderRenderer);
Expand ~ and ~xxx at the start of filenames.
""" Functions for retrieving strings from files """ import os def string_from_file(string, strip=True): """ Return an unaltered string or the contents of a file if the string begins with @ and the rest of it points at a path. If 'strip' is True, remove leading and trailing whitespace (default behavior). """ if string[0] != "@": value = string else: path = os.path.expanduser(string[1:]) with open(path, 'r') as content: value = content.read() return value.strip() if strip else value if __name__ == "__main__": print string_from_file("Plain string") print string_from_file("@/etc/fstab") print string_from_file("@~/.bashrc") try: print string_from_file("@/invalid/path") except Exception as ex: print "FAILED: " + str(ex)
""" Functions for retrieving strings from files """ import os def string_from_file(string, strip=True): """ Return an unaltered string or the contents of a file if the string begins with @ and the rest of it points at a path. If 'strip' is True, remove leading and trailing whitespace (default behavior). """ if string[0] != "@": value = string else: with open(string[1:], 'r') as content: value = content.read() return value.strip() if strip else value if __name__ == "__main__": print string_from_file("Plain string") print string_from_file("@/etc/fstab") try: print string_from_file("@/invalid/path") except Exception as ex: print "FAILED: " + str(ex)
Add test to show disk usage ratio per partition.
package com.alibaba.rocketmq.example.verify; import com.alibaba.rocketmq.common.UtilAll; import org.apache.commons.cli.*; public class SelectPartition { public static void main(String[] args) throws ParseException { Options options = new Options(); Option option = new Option("p", "path", true, "Paths in CSV"); options.addOption(option); CommandLineParser parser = new DefaultParser(); CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption('p')) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Select Partition", options); return; } String pathCSV = commandLine.getOptionValue("p"); UtilAll.selectPath(pathCSV); UtilAll.getDiskPartitionSpaceUsedPercent(pathCSV); } }
package com.alibaba.rocketmq.example.verify; import com.alibaba.rocketmq.common.UtilAll; import org.apache.commons.cli.*; public class SelectPartition { public static void main(String[] args) throws ParseException { Options options = new Options(); Option option = new Option("p", "path", true, "Paths in CSV"); options.addOption(option); CommandLineParser parser = new DefaultParser(); CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption('p')) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Select Partition", options); return; } String pathCSV = commandLine.getOptionValue("p"); String selectedPath = UtilAll.selectPath(pathCSV); System.out.println(selectedPath); } }
Add Django as a requirement Django>=1.3 is required, although >=1.4.1 is recommended
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='django-bleach', version="0.1.3", description='Easily use bleach with Django models and templates', author='Tim Heap', author_email='heap.tim@gmail.com', url='https://bitbucket.org/ionata/django-bleach', packages=find_packages(), install_requires=[ 'bleach', 'Django>=1.3', ], package_data={}, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='django-bleach', version="0.1.3", description='Easily use bleach with Django models and templates', author='Tim Heap', author_email='heap.tim@gmail.com', url='https://bitbucket.org/ionata/django-bleach', packages=find_packages(), install_requires=['bleach'], package_data={}, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
Add testCanJsonSerialize test to datetime helper
<?php namespace ZpgRtf\Tests\Helpers; use PHPUnit\Framework\TestCase; use ZpgRtf\Helpers\DateTimeHelper; class DateTimeHelperTest extends TestCase { public function testCanInstantiate() { $this->assertInstanceOf( DateTimeHelper::class, new DateTimeHelper() ); } public function testCanEncodeCustomFormat() { $format = 'c'; $timestamp = date($format); $dateTimeHelper = new DateTimeHelper($timestamp); $dateTimeHelper->setHelperFormat($format); $this->assertSame( json_decode(json_encode($dateTimeHelper)), $timestamp ); } public function testCanJsonSerialize() { $this->assertJson( json_encode(new DateTimeHelper()) ); $this->assertInstanceOf( \JsonSerializable::class, new DateTimeHelper() ); } }
<?php namespace ZpgRtf\Tests\Helpers; use PHPUnit\Framework\TestCase; use ZpgRtf\Helpers\DateTimeHelper; class DateTimeHelperTest extends TestCase { public function testCanInstantiate() { $this->assertInstanceOf( DateTimeHelper::class, new DateTimeHelper() ); } public function testCanEncodeCustomFormat() { $format = 'c'; $timestamp = date($format); $dateTimeHelper = new DateTimeHelper($timestamp); $dateTimeHelper->setHelperFormat($format); $this->assertSame( json_decode(json_encode($dateTimeHelper)), $timestamp ); } }
Remove non existing class name
// Copyright 2020 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // https://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React, { Component } from "react"; import { Redirect } from "react-router-dom"; class Home extends Component { constructor(properties) { super(properties); this.state = { isLoggedIn: false, logUrl: "", }; } componentDidMount() { fetch("/api/login-status") .then((response) => response.json()) .then((json) => this.setState({ isLoggedIn: json.isLoggedIn, logUrl: json.logUrl }) ); } render() { if (this.state.isLoggedIn) { localStorage.setItem("logOutUrl", this.state.logUrl); return <Redirect to="/home" />; } return ( <div> <h1>Recipe Finder</h1> <a href={this.state.logUrl}>Login</a> </div> ); } } export default Home;
// Copyright 2020 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // https://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React, { Component } from "react"; import { Redirect } from "react-router-dom"; class Home extends Component { constructor(properties) { super(properties); this.state = { isLoggedIn: false, logUrl: "", }; } componentDidMount() { fetch("/api/login-status") .then((response) => response.json()) .then((json) => this.setState({ isLoggedIn: json.isLoggedIn, logUrl: json.logUrl }) ); } render() { if (this.state.isLoggedIn) { localStorage.setItem("logOutUrl", this.state.logUrl); return <Redirect to="/home" />; } return ( <div> <h1>Recipe Finder</h1> <a href={this.state.logUrl} className="home-buttons"> Login </a> </div> ); } } export default Home;
Fix a test that was broken on some versions of java 8. Will change in the future
package com.novoda.simplechromecustomtabs; import com.novoda.notils.exception.DeveloperError; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; @RunWith(RobolectricTestRunner.class) public class SimpleChromeCustomTabsTest { @Test public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() { try { SimpleChromeCustomTabs.getInstance(); fail("A Developer error exception was expected, but there was nothing"); } catch (DeveloperError e) { // passes } } @Test public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() { SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application); assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class); } }
package com.novoda.simplechromecustomtabs; import com.novoda.notils.exception.DeveloperError; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) public class SimpleChromeCustomTabsTest { @Test(expected = DeveloperError.class) public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() { SimpleChromeCustomTabs.getInstance(); } @Test public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() { SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application); assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class); } }
Add firstAamcMethod to sessionType model This has been added to the frontend since the extraction happened.
import Ember from 'ember'; import DS from 'ember-data'; const { String:EmberString, computed } = Ember; const { Model, attr, belongsTo, hasMany } = DS; const { htmlSafe } = EmberString; export default Model.extend({ title: attr('string'), calendarColor: attr('string'), active: attr('boolean'), assessment: attr('boolean'), assessmentOption: belongsTo('assessment-option', {async: true}), school: belongsTo('school', {async: true}), aamcMethods: hasMany('aamc-method', {async: true}), sessions: hasMany('session', {async: true}), safeCalendarColor: computed('calendarColor', function(){ const calendarColor = this.get('calendarColor'); const pattern = new RegExp("^#[a-fA-F0-9]{6}$"); if (pattern.test(calendarColor)) { return htmlSafe(calendarColor); } return ''; }), sessionCount: computed('sessions.[]', function(){ const sessons = this.hasMany('sessions'); return sessons.ids().length; }), firstAamcMethod: computed('aamcMethods.[]', async function(){ const aamcMethods = await this.get('aamcMethods'); return aamcMethods.get('firstObject'); }), });
import Ember from 'ember'; import DS from 'ember-data'; const { String:EmberString, computed } = Ember; const { Model, attr, belongsTo, hasMany } = DS; const { htmlSafe } = EmberString; export default Model.extend({ title: attr('string'), calendarColor: attr('string'), active: attr('boolean'), assessment: attr('boolean'), assessmentOption: belongsTo('assessment-option', {async: true}), school: belongsTo('school', {async: true}), aamcMethods: hasMany('aamc-method', {async: true}), sessions: hasMany('session', {async: true}), safeCalendarColor: computed('calendarColor', function(){ const calendarColor = this.get('calendarColor'); const pattern = new RegExp("^#[a-fA-F0-9]{6}$"); if (pattern.test(calendarColor)) { return htmlSafe(calendarColor); } return ''; }), sessionCount: computed('sessions.[]', function(){ const sessons = this.hasMany('sessions'); return sessons.ids().length; }) });
Change subscribed events in AvaiabilityEventSubscriber
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Plugin\Availability\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use WellCommerce\Plugin\AdminMenu\Event\AdminMenuInitEvent; /** * Class AvailabilityEventSubscriber * * @package WellCommerce\Plugin\Availability\Event * @author Adam Piotrowski <adam@wellcommerce.org> */ class AvailabilityEventSubscriber implements EventSubscriberInterface { public function onAdminMenuInitAction(Event $event) { } public static function getSubscribedEvents() { return [ AdminMenuInitEvent::ADMIN_MENU_INIT_EVENT => 'onAdminMenuInitAction' ]; } }
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Plugin\Availability\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use WellCommerce\Plugin\AdminMenu\Event\AdminMenuInitEvent; /** * Class AvailabilityEventSubscriber * * @package WellCommerce\Plugin\Availability\Event * @author Adam Piotrowski <adam@wellcommerce.org> */ class AvailabilityEventSubscriber implements EventSubscriberInterface { public function onAdminMenuInitAction(Event $event) { } public static function getSubscribedEvents() { return array( AdminMenuInitEvent::ADMIN_MENU_INIT_EVENT => 'onAdminMenuInitAction' ); } }
Upgrade to Flask 0.12.3 to fix CVE-2018-1000656
from setuptools import setup with open('README.md') as file: long_description = file.read() setup( name="chalupas-files", version="0.1.0", author="Antonin Messinger", author_email="antonin.messinger@gmail.com", description=" Convert any document", long_description=long_description, license="MIT License", url="https://github.com/Antojitos/chalupas", download_url="https://github.com/Antojitos/chalupas/archive/0.1.0.tar.gz", keywords=["chalupas", "convert", "document"], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Flask', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ], packages=['chalupas'], install_requires=[ 'Flask==0.12.3', 'pypandoc==1.1.3' ], tests_require=[ 'python-magic==0.4.11', ], test_suite='tests.main' )
from setuptools import setup with open('README.md') as file: long_description = file.read() setup( name="chalupas-files", version="0.1.0", author="Antonin Messinger", author_email="antonin.messinger@gmail.com", description=" Convert any document", long_description=long_description, license="MIT License", url="https://github.com/Antojitos/chalupas", download_url="https://github.com/Antojitos/chalupas/archive/0.1.0.tar.gz", keywords=["chalupas", "convert", "document"], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Flask', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ], packages=['chalupas'], install_requires=[ 'Flask==0.10.1', 'pypandoc==1.1.3' ], tests_require=[ 'python-magic==0.4.11', ], test_suite='tests.main' )
Fix USER in fabric file (the deploy user and ssh user aren't necessarily the same). Set default value for PROJECT (this is the go-rts-zambia repo after all).
from fabric.api import cd, sudo, env import os PROJECT = os.environ.get('PROJECT', 'go-rts-zambia') DEPLOY_USER = os.environ.get('DEPLOY_USER', 'jmbo') env.path = os.path.join('/', 'var', 'praekelt', PROJECT) def restart(): sudo('/etc/init.d/nginx restart') sudo('supervisorctl reload') def deploy(): with cd(env.path): sudo('git pull', user=DEPLOY_USER) sudo('ve/bin/python manage.py syncdb --migrate --noinput', user=DEPLOY_USER) sudo('ve/bin/python manage.py collectstatic --noinput', user=DEPLOY_USER) def install_packages(force=False): with cd(env.path): sudo('ve/bin/pip install %s -r requirements.pip' % ( '--upgrade' if force else '',), user=DEPLOY_USER)
from fabric.api import cd, sudo, env import os expected_vars = [ 'PROJECT', ] for var in expected_vars: if var not in os.environ: raise Exception('Please specify %s environment variable' % ( var,)) PROJECT = os.environ['PROJECT'] USER = os.environ.get('USER', 'jmbo') env.path = os.path.join('/', 'var', 'praekelt', PROJECT) def restart(): sudo('/etc/init.d/nginx restart') sudo('supervisorctl reload') def deploy(): with cd(env.path): sudo('git pull', user=USER) sudo('ve/bin/python manage.py syncdb --migrate --noinput', user=USER) sudo('ve/bin/python manage.py collectstatic --noinput', user=USER) def install_packages(force=False): with cd(env.path): sudo('ve/bin/pip install %s -r requirements.pip' % ( '--upgrade' if force else '',), user=USER)
Allow internal `nextTick` utility to use microtasks when possible.
import { Promise } from 'rsvp'; export const nextTick = typeof Promise === 'undefined' ? setTimeout : cb => Promise.resolve().then(cb); export const futureTick = setTimeout; /** @private @returns {Promise<void>} promise which resolves on the next turn of the event loop */ export function nextTickPromise() { return new Promise(resolve => { nextTick(resolve); }); } /** Retrieves an array of destroyables from the specified property on the object provided, iterates that array invoking each function, then deleting the property (clearing the array). @private @param {Object} object an object to search for the destroyable array within @param {string} property the property on the object that contains the destroyable array */ export function runDestroyablesFor(object, property) { let destroyables = object[property]; if (!destroyables) { return; } for (let i = 0; i < destroyables.length; i++) { destroyables[i](); } delete object[property]; } /** Returns whether the passed in string consists only of numeric characters. @private @param {string} n input string @returns {boolean} whether the input string consists only of numeric characters */ export function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }
import { Promise } from 'rsvp'; export const nextTick = setTimeout; export const futureTick = setTimeout; /** @private @returns {Promise<void>} promise which resolves on the next turn of the event loop */ export function nextTickPromise() { return new Promise(resolve => { nextTick(resolve); }); } /** Retrieves an array of destroyables from the specified property on the object provided, iterates that array invoking each function, then deleting the property (clearing the array). @private @param {Object} object an object to search for the destroyable array within @param {string} property the property on the object that contains the destroyable array */ export function runDestroyablesFor(object, property) { let destroyables = object[property]; if (!destroyables) { return; } for (let i = 0; i < destroyables.length; i++) { destroyables[i](); } delete object[property]; } /** Returns whether the passed in string consists only of numeric characters. @private @param {string} n input string @returns {boolean} whether the input string consists only of numeric characters */ export function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }
CRM-739: Create class and command (oro.process.definition.load) to read process configuration from *.yml files to DB - small fix in configuration
<?php namespace Oro\Bundle\WorkflowBundle\Configuration; use Oro\Bundle\WorkflowBundle\Entity\ProcessTrigger; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\Processor; use Symfony\Component\Config\Definition\Builder\TreeBuilder; class ProcessTriggerListConfiguration implements ConfigurationInterface { /** * @var ProcessTriggerConfiguration */ protected $triggerConfiguration; /** * @param ProcessTriggerConfiguration $triggerConfiguration */ public function __construct(ProcessTriggerConfiguration $triggerConfiguration) { $this->triggerConfiguration = $triggerConfiguration; } /** * @param array $configs * @return array */ public function processConfiguration(array $configs) { $processor = new Processor(); return $processor->processConfiguration($this, array($configs)); } /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('configuration'); $rootNode->useAttributeAsKey('name'); $this->triggerConfiguration->addTriggerNodes($rootNode->prototype('array')->prototype('array')); return $treeBuilder; } }
<?php namespace Oro\Bundle\WorkflowBundle\Configuration; use Oro\Bundle\WorkflowBundle\Entity\ProcessTrigger; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\Processor; use Symfony\Component\Config\Definition\Builder\TreeBuilder; class ProcessTriggerListConfiguration implements ConfigurationInterface { /** * @var ProcessTriggerConfiguration */ protected $triggerConfiguration; /** * @param ProcessTriggerConfiguration $triggerConfiguration */ public function __construct(ProcessTriggerConfiguration $triggerConfiguration) { $this->triggerConfiguration = $triggerConfiguration; } /** * @param array $configs * @return array */ public function processConfiguration(array $configs) { $processor = new Processor(); return $processor->processConfiguration($this, array($configs)); } /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('configuration'); $rootNode->useAttributeAsKey('name'); $nodeBuilder = $rootNode ->prototype('array') ->prototype('array'); $this->triggerConfiguration->addTriggerNodes($nodeBuilder); return $treeBuilder; } }
Fix terms to only show terms ahead of focused term.
<?php namespace Kula\Core\Bundle\SystemBundle\Controller; use Kula\Core\Bundle\FrameworkBundle\Controller\Controller; class CoreTermsController extends Controller { public function indexAction() { $this->authorize(); $this->processForm(); $term_service = $this->get('kula.core.term'); // Get terms $terms = $this->db()->db_select('CORE_TERM') ->fields('CORE_TERM') ->condition('START_DATE', $term_service->getStartDate($this->focus->getTermID()), '>=') ->orderBy('START_DATE', 'ASC') ->orderBy('END_DATE', 'ASC') ->orderBy('TERM_ABBREVIATION', 'ASC') ->orderBy('TERM_NAME', 'ASC') ->execute()->fetchAll(); return $this->render('KulaCoreSystemBundle:Terms:index.html.twig', array('terms' => $terms)); } public function chooserAction() { $this->authorize(); $data = $this->chooser('Core.Term')->createChooserMenu($this->request->query->get('q')); return $this->JSONResponse($data); } }
<?php namespace Kula\Core\Bundle\SystemBundle\Controller; use Kula\Core\Bundle\FrameworkBundle\Controller\Controller; class CoreTermsController extends Controller { public function indexAction() { $this->authorize(); $this->processForm(); // Get terms $terms = $this->db()->db_select('CORE_TERM') ->fields('CORE_TERM') ->orderBy('START_DATE', 'ASC') ->orderBy('END_DATE', 'ASC') ->orderBy('TERM_ABBREVIATION', 'ASC') ->orderBy('TERM_NAME', 'ASC') ->execute()->fetchAll(); return $this->render('KulaCoreSystemBundle:Terms:index.html.twig', array('terms' => $terms)); } public function chooserAction() { $this->authorize(); $data = $this->chooser('Core.Term')->createChooserMenu($this->request->query->get('q')); return $this->JSONResponse($data); } }
Fix: Reduce visibility of field to maximum needed
<?php namespace Application\Service; use Zend\Log\Logger; class ErrorHandlingService { /** * @var Logger */ private $logger; public function __construct(Logger $logger) { $this->logger = $logger; } public function logException(\Exception $e) { $trace = $e->getTraceAsString(); $i = 1; do { $messages[] = $i++ . ": " . $e->getMessage(); } while ($e = $e->getPrevious()); $log = "Exception:n" . implode("n", $messages); $log .= "nTrace:n" . $trace; $this->logger->err($log); } }
<?php /** * Created by Gary Hockin. * Date: 04/12/14 * @GeeH */ namespace Application\Service; use Zend\Log\Logger; class ErrorHandlingService { /** * @var Logger */ protected $logger; public function __construct(Logger $logger) { $this->logger = $logger; } public function logException(\Exception $e) { $trace = $e->getTraceAsString(); $i = 1; do { $messages[] = $i++ . ": " . $e->getMessage(); } while ($e = $e->getPrevious()); $log = "Exception:n" . implode("n", $messages); $log .= "nTrace:n" . $trace; $this->logger->err($log); } }
Add ConnectionError handling and reconnection to Twitter streamer
import logging import time from django.core.management.base import BaseCommand, CommandError from django.conf import settings from social.models import * from social.utils import * from tweetstream import FilterStream, ConnectionError class Command(BaseCommand): help = "Start Twitter streaming" def handle(self, *args, **options): self.logger = logging.getLogger(__name__) self.updater = FeedUpdater(self.logger) feed_ids = Feed.objects.filter(type='TW').values_list('origin_id', flat=True) self.logger.info("Waiting for tweets for %d feeds" % len(feed_ids)) reconnect_timeout = 1 while True: stream = FilterStream(settings.TWITTER_USERNAME, settings.TWITTER_PASSWORD, follow=feed_ids) try: for tweet in stream: reconnect_timeout = 1 self.updater.process_tweet(tweet) except ConnectionError as e: self.logger.error("%s" % e) reconnect_timeout = 2 * reconnect_timeout time.sleep(reconnect_timeout)
import logging from django.core.management.base import BaseCommand, CommandError from django.conf import settings from social.models import * from social.utils import * from tweetstream import FilterStream class Command(BaseCommand): help = "Start Twitter streaming" def handle(self, *args, **options): self.logger = logging.getLogger(__name__) self.updater = FeedUpdater(self.logger) feed_ids = Feed.objects.filter(type='TW').values_list('origin_id', flat=True) stream = FilterStream(settings.TWITTER_USERNAME, settings.TWITTER_PASSWORD, follow=feed_ids) self.logger.info("Waiting for tweets for %d feeds" % len(feed_ids)) for tweet in stream: self.updater.process_tweet(tweet)
Fix callback cast of SerializeResponse
/* * Copyright 2014 Danilo Reinert * * 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 * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reinert.requestor.impl.gdeferred; import io.reinert.requestor.RawResponseImpl; import io.reinert.requestor.Response; /** * DoneCallback with optional access to the response. * * @param <T> Type of the response payload */ public abstract class DoneCallback<T> implements io.reinert.gdeferred.DoneCallback<T> { @Override public void onDone(T result) { } /** * If you want to access the Response attributes, then override this method. * * @param response the HTTP Response returned from the Request. */ @SuppressWarnings("unchecked") public void onDone(Response<T> response) { if (response instanceof RawResponseImpl) { onDone((T) response); return; } onDone(response.getPayload()); } }
/* * Copyright 2014 Danilo Reinert * * 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 * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reinert.requestor.impl.gdeferred; import io.reinert.requestor.Response; /** * DoneCallback with optional access to the response. * * @param <T> Type of the response payload */ public abstract class DoneCallback<T> implements io.reinert.gdeferred.DoneCallback<T> { @Override public void onDone(T result) { } public void onDone(Response<T> response) { onDone(response.getPayload()); } }
Improve test structure for themeable
import React, {PropTypes} from 'react' import {render} from 'react-dom' import {getContextualizer} from 'react-context-props' import {equal} from 'assert' import themeable from './themeable' describe('themeable', () => { it('gets the prop from context', () => { const root = document.createElement('div') document.body.innerHTML = '' document.body.appendChild(root) const Theme = getContextualizer({ customizations: PropTypes.shape({ informal: PropTypes.bool }) }) function Salutation ({ formality }) { return <div id='salutation'> {formality === 'formal' ? 'Greetings' : 'Hello'} </div> } const ThemeableSalutation = themeable((customizations, props) => ({ formality: customizations.informal ? 'informal' : 'formal' }))(Salutation) render( <Theme customizations={{informal: true}}> <div> <ThemeableSalutation /> </div> </Theme>, root ) equal( root.querySelector('#salutation').textContent.trim(), 'Hello' ) }) })
import React, {PropTypes} from 'react' import {render} from 'react-dom' import {getContextualizer} from 'react-context-props' import {equal} from 'assert' import themeable from './themeable' const root = document.createElement('div') document.body.appendChild(root) describe('themeable', () => { it('gets the prop from context', () => { const Theme = getContextualizer({ customizations: PropTypes.shape({ informal: PropTypes.bool }) }) function Salutation ({ formality }) { return <div id='salutation'> {formality === 'formal' ? 'Greetings' : 'Hello'} </div> } const ThemeableSalutation = themeable((customizations, props) => ({ formality: customizations.informal ? 'informal' : 'formal' }))(Salutation) render( <Theme customizations={{informal: true}}> <div> <ThemeableSalutation /> </div> </Theme>, root ) equal( root.querySelector('#salutation').textContent.trim(), 'Hello' ) }) })
Fix CORS to allow for credentials Something changed in the client code requiring this setting.
import logging import os import flask import flask_cors from sqlalchemy_jsonapi import flaskext as flask_jsonapi from swd6 import config from swd6.db.models import db CONF = config.CONF DEFAULT_CONF_PATH = '/opt/swd6/api/api.conf' app = None def start(): # pylint: disable=global-statement global app app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = CONF.db.uri app.config['SERVER_NAME'] = CONF.api.host app.logger.setLevel(logging.DEBUG) flask_cors.CORS(app, origins=CONF.api.cors_hosts, supports_credentials=True) logging.getLogger('flask_cors').level = logging.DEBUG db.init_app(app) flask_jsonapi.FlaskJSONAPI(app, db, options={'dasherize': False, 'include_fk_columns': True}) return app logging.basicConfig(level=logging.DEBUG) if os.path.exists(DEFAULT_CONF_PATH): config_files = [DEFAULT_CONF_PATH] else: config_files = [] config.load([], default_config_files=config_files) start()
import logging import os import flask import flask_cors from sqlalchemy_jsonapi import flaskext as flask_jsonapi from swd6 import config from swd6.db.models import db CONF = config.CONF DEFAULT_CONF_PATH = '/opt/swd6/api/api.conf' app = None def start(): # pylint: disable=global-statement global app app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = CONF.db.uri app.config['SERVER_NAME'] = CONF.api.host app.logger.setLevel(logging.DEBUG) flask_cors.CORS(app, origins=CONF.api.cors_hosts) logging.getLogger('flask_cors').level = logging.DEBUG db.init_app(app) flask_jsonapi.FlaskJSONAPI(app, db, options={'dasherize': False, 'include_fk_columns': True}) return app logging.basicConfig(level=logging.DEBUG) if os.path.exists(DEFAULT_CONF_PATH): config_files = [DEFAULT_CONF_PATH] else: config_files = [] config.load([], default_config_files=config_files) start()
Support fetching urls for inbox attachments
'use strict'; var express = require('express'); var router = module.exports = express.Router(); router.post('/url', function(req, res, next) { var data = req.body, model; if (data.type === 'expense_attachment') { model = req.app.get('bookshelf').models.ExpenseAttachment; } else if (data.type === 'inbox_attachment') { model = req.app.get('bookshelf').models.InboxItemAttachment; } if (!model) return res.status(400).send({error: 'Unknown file type'}); model.forge({environment_id: req.user.get('environment_id'), id: data.id}).fetch().then(function(model) { if (!model) return res.status(401).send({error: 'Forbidden'}); var params = { Bucket: process.env.AWS_S3_BUCKET, Key: model.get('s3path') }; var url = req.s3.getSignedUrl('getObject', params); return res.send({url: url}); }).catch(next); });
var express = require('express'); var router = module.exports = express.Router(); router.post('/url', function(req, res, next) { var data = req.body, model; if (data.type === 'expense_attachment') { model = req.app.get('bookshelf').models.ExpenseAttachment; } if (!model) return res.status(400).send({error: 'Unknown file type'}); model.forge({environment_id: req.user.get('environment_id'), id: data.id}).fetch().then(function(model) { if (!model) return res.status(401).send({error: 'Forbidden'}); var params = { Bucket: process.env.AWS_S3_BUCKET, Key: model.get('s3path') }; var url = req.s3.getSignedUrl('getObject', params); return res.send({url: url}); }).catch(next); });
Add custom authentication form to set the label 'username' label to 'student number' for the login form.
from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationForm from .models import WhitelistedUsername User = get_user_model() class CustomAuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(CustomAuthenticationForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Student number' class ExclusiveRegistrationForm(RegistrationForm): def __init__(self, *args, **kwargs): super(ExclusiveRegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Student number' def clean(self): # TODO: try catch KeyError here to avoid empty form error form_username = self.cleaned_data['username'] try: # If this runs without raising an exception, then the username is in # our database of whitelisted usernames. WhitelistedUsername.objects.get(username=form_username.lower()) except ObjectDoesNotExist: err = ValidationError(_('Unrecognised student number. Are you a CS1 student at UCT?s'), code='invalid') self.add_error(User.USERNAME_FIELD, err) super(ExclusiveRegistrationForm, self).clean()
from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationForm from .models import WhitelistedUsername User = get_user_model() class ExclusiveRegistrationForm(RegistrationForm): def __init__(self, *args, **kwargs): super(ExclusiveRegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Student number' def clean(self): # TODO: try catch KeyError here to avoid empty form error form_username = self.cleaned_data['username'] try: # If this runs without raising an exception, then the username is in # our database of whitelisted usernames. WhitelistedUsername.objects.get(username=form_username.lower()) except ObjectDoesNotExist: err = ValidationError(_('Unrecognised student number. Are you a CS1 student at UCT?s'), code='invalid') self.add_error(User.USERNAME_FIELD, err) super(ExclusiveRegistrationForm, self).clean()
Fix flake8 errors for build.
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n - 1) + FibonacciTask.fibonacci(n - 2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries = 3 # The hard limit for max task running time. # This value should be set between max actual running time and # queue visibility timeout. time_limit = 5 # seconds # The queue name queue = 'default' @staticmethod def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return FibonacciTask.fibonacci(n-1) + FibonacciTask.fibonacci(n-2) def run_task(self, n, *args, **kwargs): print('fibonacci(%d) = %d' % (n, self.fibonacci(n)))
Improve error feedback on server add screen
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { addServer } from '../actions/servers'; import { setStatus, clearStatus } from '../actions/status'; import ServerForm from '../widgets/server-form'; class ServerAdd extends Component { static propTypes = { dispatch: PropTypes.func.isRequired, loading: PropTypes.bool.isRequired, error: PropTypes.any, server: PropTypes.object, }; static contextTypes = { history: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(setStatus('Add server information')); } componentWillReceiveProps ({ error, loading }) { const { dispatch } = this.props; if (error) dispatch(setStatus(error)); if (loading) dispatch(setStatus('Adding server...')); } componentWillUnmount () { this.props.dispatch(clearStatus()); } async onSubmit (server) { await this.props.dispatch(addServer(server)); if (!this.props.error) this.context.history.goBack(); } render () { return ( <box left="center" top="center" height={21} width={80} shadow="true"> <ServerForm onSubmit={::this.onSubmit} /> </box> ); } } export default connect( state => state.addServer )(ServerAdd);
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { addServer } from '../actions/servers'; import { setStatus, clearStatus } from '../actions/status'; import ServerForm from '../widgets/server-form'; class ServerAdd extends Component { static propTypes = { dispatch: PropTypes.func.isRequired, loading: PropTypes.bool.isRequired, error: PropTypes.any, server: PropTypes.object, }; static contextTypes = { history: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(setStatus('Add server information')); } componentWillReceiveProps ({ error, loading }) { const { dispatch } = this.props; if (error) dispatch(setStatus(error)); if (loading) dispatch(setStatus('Adding server...')); } componentWillUnmount () { this.props.dispatch(clearStatus()); } async onSubmit (server) { await this.props.dispatch(addServer(server)); if (this.props.server) this.context.history.goBack(); } render () { return ( <box left="center" top="center" height={21} width={80} shadow="true"> <ServerForm onSubmit={::this.onSubmit} /> </box> ); } } export default connect( state => state.addServer )(ServerAdd);
Return latest 3 data items
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var jsonParser = bodyParser.json(); var request = require('request'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/', function (req, res) { res.send('Slack Commands!'); }); app.all('/github', jsonParser, function (req, res) { console.log(req.params); console.log(req.body); request({ url: `http://api.github.com/users/${req.body.user_name || req.body.text}/events`, headers: { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'SlackCmds', } }, function (error, response, body) { let data = JSON.parse(body).map((item)=>{ return { 'type': item.type, 'date': item.created_at}; }); res.json(data.slice(0,3)); }) }); var port = process.env.PORT || 3000; app.listen(port, function () { console.log(`Example app listening on port ${port}!`) });
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var jsonParser = bodyParser.json(); var request = require('request'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/', function (req, res) { res.send('Slack Commands!'); }); app.all('/github', jsonParser, function (req, res) { console.log(req.params); console.log(req.body); request({ url: `http://api.github.com/users/${req.body.user_name || req.body.text}/events`, headers: { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'SlackCmds', } }, function (error, response, body) { let data = JSON.parse(body).map((item)=>{ return { 'type': item.type, 'date': item.created_at}; }); res.json(data); }) }); var port = process.env.PORT || 3000; app.listen(port, function () { console.log(`Example app listening on port ${port}!`) });
Fix incorrect checksum verification when checksum is 32 (0x20, space)
#!/usr/bin/env python class TeleinfoParser: integerKeys = [ 'ISOUSC', 'BASE', 'HCHC', 'HCHP', 'EJPHN', 'EJPHPM', 'BBRHCJB', 'BBRHPJB', 'BBRHCJW', 'BBRHPJW', 'BBRHCJR', 'BBRHPJR', 'PEJP', 'IINST', 'IINST1', 'IINST2', 'IINST3', 'ADPS', 'IMAX', 'IMAX1', 'IMAX2', 'IMAX3', 'PAPP', 'ADIR1', 'ADIR2', 'ADIR3' ] def checksum (self, label, value): """Return the checksum of a value and label""" sum = 32 for c in label + value: sum += ord(c) return chr((sum & 63) + 32) def parse (self, message): """Read and verify Teleinfo datagram and return it as a dict""" trames = [trame.split(" ", 2) for trame in message.strip("\r\n\x03\x02").split("\r\n")] return dict([ [trame[0], int(trame[1]) if trame[0] in self.integerKeys else trame[1]] for trame in trames if (len(trame) == 3) and (self.checksum(trame[0],trame[1]) == trame[2]) ])
#!/usr/bin/env python class TeleinfoParser: integerKeys = [ 'ISOUSC', 'BASE', 'HCHC', 'HCHP', 'EJPHN', 'EJPHPM', 'BBRHCJB', 'BBRHPJB', 'BBRHCJW', 'BBRHPJW', 'BBRHCJR', 'BBRHPJR', 'PEJP', 'IINST', 'IINST1', 'IINST2', 'IINST3', 'ADPS', 'IMAX', 'IMAX1', 'IMAX2', 'IMAX3', 'PAPP', 'ADIR1', 'ADIR2', 'ADIR3' ] def checksum (self, label, value): """Return the checksum of a value and label""" sum = 32 for c in label + value: sum += ord(c) return chr((sum & 63) + 32) def parse (self, message): """Read and verify Teleinfo datagram and return it as a dict""" trames = [trame.split(" ") for trame in message.strip("\r\n\x03\x02").split("\r\n")] return dict([ [trame[0], int(trame[1]) if trame[0] in self.integerKeys else trame[1]] for trame in trames if (len(trame) == 3) and (self.checksum(trame[0],trame[1]) == trame[2]) ])
Update title to ReCAPTCHA v3
<?php require_once 'recaptcha.class.php'; $form_id = "form"; $site_key = 'YOUR_SITE_KEY'; $secret_key = 'YOUR_SECRET_KEY'; $recaptcha = new Recaptcha($form_id, $site_key, $secret_key); ?> <!doctype html> <html> <head> <title>ReCAPTCHA v3 API Class Demo</title> </head> <body> <?php ob_start(); ?> <form id="form" method="post"> <input type="text" name="example" value="" placeholder="Example Field" /> <?php echo $recaptcha->button(); ?> </form> <?php $form = ob_get_clean(); if(!empty($_POST)) { $response = $recaptcha->get_response(); echo "Success: ". ( $response->success ? 'true' : 'false' ) ."<br />\r\n"; echo "Score: ". $response->score ."<br />\r\n"; if($response->success) { echo "Passed Captcha."; } else { echo "Failed Captcha."; echo $form; } } else { echo $form; } echo $recaptcha->script(); ?> </body> </html>
<?php require_once 'recaptcha.class.php'; $form_id = "form"; $site_key = 'YOUR_SITE_KEY'; $secret_key = 'YOUR_SECRET_KEY'; $recaptcha = new Recaptcha($form_id, $site_key, $secret_key); ?> <!doctype html> <html> <head> <title>Invisible ReCAPTCHA API Class Demo</title> </head> <body> <?php ob_start(); ?> <form id="form" method="post"> <input type="text" name="example" value="" placeholder="Example Field" /> <?php echo $recaptcha->button(); ?> </form> <?php $form = ob_get_clean(); if(!empty($_POST)) { $response = $recaptcha->get_response(); echo "Success: ". ( $response->success ? 'true' : 'false' ) ."<br />\r\n"; echo "Score: ". $response->score ."<br />\r\n"; if($response->success) { echo "Passed Captcha."; } else { echo "Failed Captcha."; echo $form; } } else { echo $form; } echo $recaptcha->script(); ?> </body> </html>
Revert the ,bgimage: define.classPath(this) to require, since the correct new way of loading local resources for WebGL causes an exception in Dali. /root/teem/dreemgl-dev/classes/ui/view.js:532 if(require.loaded(this._bgimage)){ bgimagemode:"stretch" is left in the code, since that fixes the problem with the sizing of images for the Dali runtime.
/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others. 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 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ //Pure JS based composition define.class(function($server$, composition, $ui$, screen, view, label, require){ this.render = function(){ var dynviews = []; for (var digit=0; digit<10; digit++) { for (var w=100; w<=200; w+= 25) { var v1 = view({ size: vec2(w, w) ,bgimage: require('./assets/' + digit + '.png') // ,bgimage: define.classPath(this) + 'assets/' + digit + '.png' ,bgimagemode:"stretch" }) dynviews.push(v1); } } var views = [ screen({name:'default', clearcolor:'#484230'} ,dynviews) ]; return views } })
/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others. 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 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ //Pure JS based composition define.class(function($server$, composition, $ui$, screen, view, label, require){ this.render = function(){ var dynviews = []; for (var digit=0; digit<10; digit++) { for (var w=100; w<=200; w+= 25) { var v1 = view({ size: vec2(w, w) ,bgimage: define.classPath(this) + 'assets/' + digit + '.png' ,bgimagemode:"stretch" }) dynviews.push(v1); } } var views = [ screen({name:'default', clearcolor:'#484230'} ,dynviews) ]; return views } })
Drop obsoleted support for offset.
from .base import Base class List(Base): current = None def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def __len__(self): """Return the count field.""" return int(self['count']) def get_object_name(self): return self.object_type.__name__.lower() + 's' def __iter__(self): """Implement iterator interface.""" self.current = None return self def __next__(self): """Implement iterator interface.""" if self.current is None: self.current = 0 else: self.current += 1 try: item = self['_embedded'][self.get_object_name()][self.current] return self.object_type(item) except IndexError: raise StopIteration next = __next__ # support python2 iterator interface @property def count(self): if 'count' not in self: return None return int(self['count'])
from .base import Base class List(Base): current = None def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def __len__(self): """Return the count field.""" return int(self['count']) def get_object_name(self): return self.object_type.__name__.lower() + 's' def __iter__(self): """Implement iterator interface.""" self.current = None return self def __next__(self): """Implement iterator interface.""" if self.current is None: self.current = 0 else: self.current += 1 try: item = self['_embedded'][self.get_object_name()][self.current] return self.object_type(item) except IndexError: raise StopIteration next = __next__ # support python2 iterator interface @property def count(self): if 'count' not in self: return None return int(self['count']) def get_offset(self): if 'offset' not in self: return None return self['offset']
Remove unused imports Only define MsgPackEngine if we can import MsgPack
import json class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' raise NotImplementedError class JsonEngine(Engine): CONTENT_TYPES = ['application/json',] def dumps(self, data): return json.dumps(data) def loads(self, data): return json.loads(data) try: import msgpack except ImportError: pass else: class MsgPackEngine(Engine): CONTENT_TYPES = ['application/x-msgpack',] def dumps(self, data): return msgpack.dumps(data) def loads(self, data): return msgpack.loads(data)
import json try: import msgpack except ImportError: pass from decimal import Decimal from datetime import date, datetime, time class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' raise NotImplementedError class JsonEngine(Engine): CONTENT_TYPES = ['application/json',] def dumps(self, data): return json.dumps(data) def loads(self, data): return json.loads(data) class MsgPackEngine(Engine): CONTENT_TYPES = ['application/x-msgpack',] def dumps(self, data): return msgpack.dumps(data) def loads(self, data): return msgpack.loads(data)
Add the missing 'np.' before 'array'
"""The metrics module implements functions assessing prediction error for specific purposes.""" import numpy as np def trapz(x, y): """Trapezoidal rule for integrating the curve defined by x-y pairs. Assume x and y are in the range [0,1] """ assert len(x) == len(y), 'x and y need to be of same length' x = np.concatenate([x, np.array([0.0, 1.0])]) y = np.concatenate([y, np.array([0.0, 1.0])]) sort_idx = np.argsort(x) sx = x[sort_idx] sy = y[sort_idx] area = 0.0 for ix in range(len(x) - 1): area += 0.5 * (sx[ix + 1] - sx[ix]) * (sy[ix + 1] + sy[ix]) return area
"""The metrics module implements functions assessing prediction error for specific purposes.""" import numpy as np def trapz(x, y): """Trapezoidal rule for integrating the curve defined by x-y pairs. Assume x and y are in the range [0,1] """ assert len(x) == len(y), 'x and y need to be of same length' x = np.concatenate([x, array([0.0, 1.0])]) y = np.concatenate([y, array([0.0, 1.0])]) sort_idx = np.argsort(x) sx = x[sort_idx] sy = y[sort_idx] area = 0.0 for ix in range(len(x)-1): area += 0.5*(sx[ix+1]-sx[ix])*(sy[ix+1]+sy[ix]) return area
Remove node engine version from published package
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ /* eslint-disable no-console */ import fs from 'fs'; import path from 'path'; import async from 'async'; // ///////////////////////////////////////////////////////////// // Helpers // ///////////////////////////////////////////////////////////// const distPath = path.resolve.bind(path, path.resolve(__dirname, '../', '.tmp')); // ///////////////////////////////////////////////////////////// // Tasks // ///////////////////////////////////////////////////////////// async.series([ /** * Clean up the package.json */ (done) => { console.log('### Cleaning up the package.json'); const packageJSON = JSON.parse(fs.readFileSync(distPath('package.json')).toString()); // Used by documentation site // Can be used for CI tests by consuming applications packageJSON.SLDS = { gitURL: packageJSON.devDependencies['@salesforce-ux/design-system'] }; delete packageJSON.scripts; // This is a UI library, not a node package. delete packageJSON.engines.node; delete packageJSON.devDependencies; delete packageJSON['pre-push']; delete packageJSON['pre-commit']; fs.writeFile( distPath('package.json'), JSON.stringify(packageJSON, null, 2), done ); } ], (err) => { if (err) throw err; });
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ /* eslint-disable no-console */ import fs from 'fs'; import path from 'path'; import async from 'async'; // ///////////////////////////////////////////////////////////// // Helpers // ///////////////////////////////////////////////////////////// const distPath = path.resolve.bind(path, path.resolve(__dirname, '../', '.tmp')); // ///////////////////////////////////////////////////////////// // Tasks // ///////////////////////////////////////////////////////////// async.series([ /** * Clean up the package.json */ (done) => { console.log('### Cleaning up the package.json'); const packageJSON = JSON.parse(fs.readFileSync(distPath('package.json')).toString()); // Used by documentation site // Can be used for CI tests by consuming applications packageJSON.SLDS = { gitURL: packageJSON.devDependencies['@salesforce-ux/design-system'] }; delete packageJSON.scripts; delete packageJSON.devDependencies; delete packageJSON['pre-push']; delete packageJSON['pre-commit']; fs.writeFile( distPath('package.json'), JSON.stringify(packageJSON, null, 2), done ); } ], (err) => { if (err) throw err; });
Fix Reader to support non-model audio (no ID)
Kpcc.Article = DS.Model.extend({ title : DS.attr(), short_title : DS.attr(), published_at : DS.attr(), byline : DS.attr(), teaser : DS.attr(), body : DS.attr(), public_url : DS.attr(), assets : DS.hasMany('asset'), audio : DS.attr(), category : DS.belongsTo('category'), }); Kpcc.ArticleSerializer = Kpcc.ApplicationSerializer.extend( DS.EmbeddedRecordsMixin, { attrs: { assets : { embedded: 'always' }, category : { embedded: 'always' } } } )
Kpcc.Article = DS.Model.extend({ title : DS.attr(), short_title : DS.attr(), published_at : DS.attr(), byline : DS.attr(), teaser : DS.attr(), body : DS.attr(), public_url : DS.attr(), assets : DS.hasMany('asset'), audio : DS.hasMany("audio"), category : DS.belongsTo('category'), }); Kpcc.ArticleSerializer = Kpcc.ApplicationSerializer.extend( DS.EmbeddedRecordsMixin, { attrs: { assets : { embedded: 'always' }, category : { embedded: 'always' }, audio : { embedded: 'always' } } } )
Fix RN 0.47 breaking change
package com.balthazargronon.RCTZeroconf; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.List; /** * Created by Jeremy White on 8/1/2016. * Copyright © 2016 Balthazar Gronon MIT */ public class ZeroconfReactPackage implements ReactPackage { @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return new ArrayList<>(); } // Deprecated RN 0.47 public List<Class<? extends JavaScriptModule>> createJSModules() { return new ArrayList<>(); } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ZeroconfModule(reactContext)); return modules; } }
package com.balthazargronon.RCTZeroconf; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.List; /** * Created by Jeremy White on 8/1/2016. * Copyright © 2016 Balthazar Gronon MIT */ public class ZeroconfReactPackage implements ReactPackage { @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return new ArrayList<>(); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return new ArrayList<>(); } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ZeroconfModule(reactContext)); return modules; } }
11239: Abort running request if new one fired
// ELMO.Views.DashboardReport // // View model for the dashboard report ELMO.Views.DashboardReportView = class DashboardReportView extends ELMO.Views.ApplicationView { get el() { return '.report'; } get events() { return { 'change .report-chooser': 'handleReportChange', 'click .action-link-close': 'handleReportClose', }; } handleReportChange(e) { const id = $(e.target).val(); if (id) { this.changeReport(id, $(e.target).find('option:selected').text()); } } handleReportClose(e) { e.preventDefault(); this.changeReport(null, I18n.t('activerecord.models.report/report.one')); } changeReport(id, name) { if (this.request) { this.request.abort(); } this.toggleLoader(true); this.$('.report-title-text').html(name); this.$('.report-chooser').find('option').attr('selected', false); this.$('.report-output-and-modal').empty(); this.$('.action-link').hide(); const url = ELMO.app.url_builder.build(`dashboard/report?id=${id || ''}`); this.request = $.get(url, this.handleReportLoaded.bind(this)); } handleReportLoaded(html) { this.request = null; this.$el.html(html); } toggleLoader(bool) { $('.report-pane-header .inline-load-ind img').toggle(bool); } };
// ELMO.Views.DashboardReport // // View model for the dashboard report ELMO.Views.DashboardReportView = class DashboardReportView extends ELMO.Views.ApplicationView { get el() { return '.report'; } get events() { return { 'change .report-chooser': 'handleReportChange', 'click .action-link-close': 'handleReportClose', }; } handleReportChange(e) { const id = $(e.target).val(); if (id) { this.changeReport(id, $(e.target).find('option:selected').text()); } } handleReportClose(e) { e.preventDefault(); this.changeReport(null, I18n.t('activerecord.models.report/report.one')); } changeReport(id, name) { this.toggleLoader(true); this.$('.report-title-text').html(name); this.$('.report-chooser').find('option').attr('selected', false); this.$('.report-output-and-modal').empty(); this.$('.action-link').hide(); this.$el.load(ELMO.app.url_builder.build(`dashboard/report?id=${id || ''}`)); } toggleLoader(bool) { $('.report-pane-header .inline-load-ind img').toggle(bool); } };
Update char swap operation without temp character
/* Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". */ package main import ( "fmt" ) func main() { tests := [][]string{{"", ""}, {" ", " "}, {" ", " "}, {"a", "a"}, {"ab", "ba"}, {"hello", "olleh"}, {"Hello, 世界!", "!界世 ,olleH"}} for _, test := range tests { if reverseString(test[0]) == test[1] { fmt.Println("PASS") } else { fmt.Println("FAIL") fmt.Println("\t", test) } } } func reverseString(s string) string { // transform input string into rune (unicode char) slice for convenient manipulation s_runes := []rune(s) // reverse characters for i := 0; i < len(s_runes)/2; i++ { s_runes[i], s_runes[len(s_runes)-i-1] = s_runes[len(s_runes)-i-1], s_runes[i] } return string(s_runes) }
/* Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". */ package main import ( "fmt" ) func main() { tests := [][]string{{"", ""}, {" ", " "}, {" ", " "}, {"a", "a"}, {"ab", "ba"}, {"hello", "olleh"}, {"Hello, 世界!", "!界世 ,olleH"}} for _, test := range tests { if reverseString(test[0]) == test[1] { fmt.Println("PASS") } else { fmt.Println("FAIL") fmt.Println("\t", test) } } } func reverseString(s string) string { // transform input string into rune (unicode char) slice for convenient manipulation s_runes := []rune(s) // reverse characters for i := 0; i < len(s_runes)/2; i++ { temp := s_runes[i] s_runes[i] = s_runes[len(s_runes)-i-1] s_runes[len(s_runes)-i-1] = temp } return string(s_runes) }
Fix nodejs v6 'TypeError: Object.values is not a function'
const chalk = require('chalk'); LOG_TYPES = { NONE: 0, ERROR: 1, NORMAL: 2, DEBUG: 3 }; let logType = LOG_TYPES.NORMAL; const setLogType = (type) => { if (typeof type !== 'number') return; logType = type; }; const logTime = () => { let nowDate = new Date(); return nowDate.toLocaleDateString() + ' ' + nowDate.toLocaleTimeString([], { hour12: false }); }; const log = (...args) => { if (logType < LOG_TYPES.NORMAL) return; console.log(logTime(), chalk.bold.green('[INFO]'), ...args); }; const error = (...args) => { if (logType < LOG_TYPES.ERROR) return; console.log(logTime(), chalk.bold.red('[ERROR]'), ...args); }; const debug = (...args) => { if (logType < LOG_TYPES.DEBUG) return; console.log(logTime(), chalk.bold.blue('[DEBUG]'), ...args); }; module.exports = { LOG_TYPES, setLogType, log, error, debug }
const chalk = require('chalk'); LOG_TYPES = { NONE: 0, ERROR: 1, NORMAL: 2, DEBUG: 3 }; let logType = LOG_TYPES.NORMAL; const setLogType = (type) => { if (!(type in Object.values(LOG_TYPES))) return; logType = type; }; const logTime = () => { let nowDate = new Date(); return nowDate.toLocaleDateString() + ' ' + nowDate.toLocaleTimeString([], { hour12: false }); }; const log = (...args) => { if (logType < LOG_TYPES.NORMAL) return; console.log(logTime(), chalk.bold.green('[INFO]'), ...args); }; const error = (...args) => { if (logType < LOG_TYPES.ERROR) return; console.log(logTime(), chalk.bold.red('[ERROR]'), ...args); }; const debug = (...args) => { if (logType < LOG_TYPES.DEBUG) return; console.log(logTime(), chalk.bold.blue('[DEBUG]'), ...args); }; module.exports = { LOG_TYPES, setLogType, log, error, debug }
Use @lru_cache now that memoize is gone.
from django.utils.lru_cache import lru_cache from . import app_settings @lru_cache def get_render_method(): return from_dotted_path(app_settings.EMAIL_RENDER_METHOD) @lru_cache def get_context_processors(): return [from_dotted_path(x) for x in app_settings.EMAIL_CONTEXT_PROCESSORS] def from_dotted_path(fullpath): """ Returns the specified attribute of a module, specified by a string. ``from_dotted_path('a.b.c.d')`` is roughly equivalent to:: from a.b.c import d except that ``d`` is returned and not entered into the current namespace. """ module, attr = fullpath.rsplit('.', 1) return getattr(__import__(module, {}, {}, (attr,)), attr)
from django.utils.functional import memoize from . import app_settings def get_render_method(): return from_dotted_path(app_settings.EMAIL_RENDER_METHOD) get_render_method = memoize(get_render_method, {}, 0) def get_context_processors(): return [from_dotted_path(x) for x in app_settings.EMAIL_CONTEXT_PROCESSORS] get_context_processors = memoize(get_context_processors, {}, 0) def from_dotted_path(fullpath): """ Returns the specified attribute of a module, specified by a string. ``from_dotted_path('a.b.c.d')`` is roughly equivalent to:: from a.b.c import d except that ``d`` is returned and not entered into the current namespace. """ module, attr = fullpath.rsplit('.', 1) return getattr(__import__(module, {}, {}, (attr,)), attr)
Refactor and split input amount into pounds and pence
// ($(this).val() && Number($(this).val()) > 0) function isValidAmount(input) { var maxVal = 100000000 var minVal = 0 var pounds; var pence; var trimmedInput = input.trim() var decimalPointPosition = trimmedInput.indexOf('.') if(decimalPointPosition === -1) { pounds = trimmedInput } else { pounds = trimmedInput.slice(0, decimalPointPosition) pence = trimmedInput.slice(decimalPointPosition + 1) } pounds = pounds.replace(/^£|[\s,]+/g, "") if(pence) { if(pence.length > 2) { return false } } var amount = Number(pounds * 100) if(pence) { amount += Number(pence) } if(amount) { if(amount > maxVal || amount < minVal) { return false } } else { return false } return true } exports.isValidAmount = isValidAmount
// ($(this).val() && Number($(this).val()) > 0) function isValidAmount(input) { var maxVal = 100000000 var minVal = 0 var value = input.split('.') var pounds = value[0] var pence = value[1] pounds = pounds.replaceAll(/^£|[\s,]+/g, "") if(pence) { var lengthOfPence = pence.length if(lengthOfPence > 2) { return false } } var amount = Number(pounds * 100) if(pence) { amount += Number(pence) } if(amount) { console.log('Amount: ' + amount) if(amount > maxVal || amount < minVal) { return false } } else { return false } return true } exports.isValidAmount = isValidAmount
Add vi scrolling keys to scrolling key-binding
exports = module.exports = function (UI) { var setHistoryHeight = function () { // Set the history component dynamic height UI.components.history.height = UI.screen.height - UI.components.input.height; }; UI.screen.on('prerender', function () { setHistoryHeight(); }); UI.screen.on('resize', function () { setHistoryHeight(); UI.screen.render(); }); // If box is focused, handle `Control+s`. UI.components.input.key('C-s', function(ch, key) { var message = this.getValue(); UI.context.room.writeMessage(message); this.clearValue(); UI.screen.render(); }); // Quit on `q`, or `Control-C` when the focus is on the screen UI.screen.key(['q', 'C-c'], function (ch, key) { return process.exit(0); }); // Focus on `escape` or `i` when focus is on the screen. UI.screen.key(['escape', 'i'], function () { // Set the focus on the input. UI.components.input.focus(); }); // History scrolling events. UI.screen.key(['up', 'k'], function () { UI.components.history.up(); }); UI.screen.key(['down', 'j'], function () { UI.components.history.down(); }); };
exports = module.exports = function (UI) { var setHistoryHeight = function () { // Set the history component dynamic height UI.components.history.height = UI.screen.height - UI.components.input.height; }; UI.screen.on('prerender', function () { setHistoryHeight(); }); UI.screen.on('resize', function () { setHistoryHeight(); UI.screen.render(); }); // If box is focused, handle `Control+s`. UI.components.input.key('C-s', function(ch, key) { var message = this.getValue(); UI.context.room.writeMessage(message); this.clearValue(); UI.screen.render(); }); // Quit on `q`, or `Control-C` when the focus is on the screen UI.screen.key(['q', 'C-c'], function (ch, key) { return process.exit(0); }); // Focus on `escape` or `i` when focus is on the screen. UI.screen.key(['escape', 'i'], function () { // Set the focus on the input. UI.components.input.focus(); }); UI.screen.key(['up', 'down'], function (ch, key) { UI.components.history[key.name](); }); };
Fix "const" search and replace
'use strict'; let rpc = require('./rpc'); let util = require('./util'); let idKey = util.idKey; let realmKey = util.realmKey; let registeredConstructors = {}; exports.create = create; exports.registerConstructors = registerConstructors; function create(realmId, info) { let schema = info.schema; let constructor = (registeredConstructors[realmId] || {})[schema.name]; let object = constructor ? Object.create(constructor.prototype) : {}; let props = {}; object[realmKey] = realmId; object[idKey] = info.id; for (let prop of schema.properties) { let name = prop.name; props[name] = { get: getterForProperty(name), set: setterForProperty(name), }; } Object.defineProperties(object, props); return object; } function registerConstructors(realmId, constructors) { registeredConstructors[realmId] = constructors; } function getterForProperty(name) { return function() { return rpc.getObjectProperty(this[realmKey], this[idKey], name); }; } function setterForProperty(name) { return function(value) { rpc.setObjectProperty(this[realmKey], this[idKey], name, value); }; }
'use strict'; let rpc = require('./rpc'); let util = require('./util'); let idKey = util.idKey; let realmKey = util.realmKey; let registeredConstructors = {}; exports.create = create; exports.registerConstructors = registerConstructors; function create(realmId, info) { let schema = info.schema; let constructor = (registeredConstructors[realmId] || {})[schema.name]; let object = constructor ? Object.create(constructor.prototype) : {}; let props = {}; object[realmKey] = realmId; object[idKey] = info.id; for (let prop of schema.properties) { let name = prop.name; props[name] = { get: getterForProperty(name), set: setterForProperty(name), }; } Object.defineProperties(object, props); return object; } function registerletructors(realmId, letructors) { registeredletructors[realmId] = letructors; } function getterForProperty(name) { return function() { return rpc.getObjectProperty(this[realmKey], this[idKey], name); }; } function setterForProperty(name) { return function(value) { rpc.setObjectProperty(this[realmKey], this[idKey], name, value); }; }
Update warning message one last time
import warning from './warning'; const requestStatuses = { IDLE: 'IDLE', PENDING: 'PENDING', FAILED: 'FAILED', SUCCEEDED: 'SUCCEEDED', }; if (process.env.NODE_ENV !== 'production') { Object.defineProperty(requestStatuses, 'NULL', { get() { warning( `You attempted to access the NULL request status from the requestStatus object ` + `that is exported from Redux Resource. The NULL request status ` + `has been renamed to IDLE in Redux Resource v3. Please update your ` + `application to use the new request status. Typically, this can be ` + `done by doing a find and replace within your source code to ` + `replace the string "NULL" with "IDLE". For more information, refer to ` + `the documentation for the request statuses at: ` + `https://redux-resource.js.org/docs/api-reference/request-statuses.html\n\n` + `Also, the migration guide to Redux Resource v3 can be found at: ` + `https://github.com/jamesplease/redux-resource/blob/master/packages/redux-resource/docs/migration-guides/2-to-3.md`, `NULL_REQUEST_STATUS_ACCESSED` ); }, }); } export default requestStatuses;
import warning from './warning'; const requestStatuses = { IDLE: 'IDLE', PENDING: 'PENDING', FAILED: 'FAILED', SUCCEEDED: 'SUCCEEDED', }; if (process.env.NODE_ENV !== 'production') { Object.defineProperty(requestStatuses, 'NULL', { get() { warning( `You attempted to access the NULL request status from the requestStatus object ` + `that is exported from Redux Resource. The NULL request status ` + `has been renamed to IDLE in Redux Resource v3. Please update your ` + `application to use the new request status. Typically, this can be ` + `done by doing a find and replace within your source code to ` + `replace "NULL" with "IDLE". For more information, refer to the ` + `documentation for the request statuses at: ` + `https://redux-resource.js.org/docs/api-reference/request-statuses.html\n\n` + `Also, the migration guide to Redux Resource v3 can be found at: ` + `https://github.com/jamesplease/redux-resource/blob/master/packages/redux-resource/docs/migration-guides/2-to-3.md`, `NULL_REQUEST_STATUS_ACCESSED` ); }, }); } export default requestStatuses;
Fix uuid generator, add objectSize calculator
var titleCase = function toTitleCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }; var uuid = function uuidGenerator () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; var browserString = function browserString (config) { return config.os + ' ' + config.os_version + ', ' + titleCase(config.browser || config.device) + ' ' + config.browser_version; } var objectSize = function objectSize (obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; exports.titleCase = titleCase; exports.uuid = uuid; exports.browserString = browserString; exports.objectSize = objectSize;
var titleCase = function toTitleCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }; var uuid = function uuidGenerator () { 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; var browserString = function browserString (config) { return config.os + ' ' + config.os_version + ': ' + titleCase(config.browser || config.device) + ' ' + config.browser_version; } exports.titleCase = titleCase; exports.uuid = uuid; exports.browserString = browserString;
Fix particle texture causing FileNotFoundException The string used in the ResourceLocation for the sprinkler water particle was for an icon instead of the texture. As a result, the client would throw an exception and then it would instead use the "missingo" texture. Although this does fix the black and purple texture, all particles will still be water colored. For example, blocks break into bursts of water droplets. A separate commit fixes that though.
package com.infinityraider.agricraft.renderers.particles; //heavily inspired by the OpenBlocks sprinkler import com.infinityraider.agricraft.utility.BaseIcons; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class LiquidSprayFX extends AgriCraftFX { public LiquidSprayFX(World world, double x, double y, double z, float scale, float gravity, Vec3d vector) { super(world, x, y, z, scale, gravity, vector, new ResourceLocation("minecraft:textures/blocks/water_still.png")); this.particleMaxAge = 15; this.setSize(0.2f, 0.2f); } }
package com.infinityraider.agricraft.renderers.particles; //heavily inspired by the OpenBlocks sprinkler import com.infinityraider.agricraft.utility.BaseIcons; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class LiquidSprayFX extends AgriCraftFX { public LiquidSprayFX(World world, double x, double y, double z, float scale, float gravity, Vec3d vector) { super(world, x, y, z, scale, gravity, vector, new ResourceLocation(BaseIcons.WATER_STILL.location)); this.particleMaxAge = 15; this.setSize(0.2f, 0.2f); } }
Initialize select dropdown for categories with maps
from django import forms from django.utils.translation import ugettext_lazy as _ from adhocracy4.categories.forms import CategorizableFieldMixin from adhocracy4.maps import widgets as maps_widgets from . import models class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm): class Media: js = ('js/select_dropdown_init.js',) def __init__(self, *args, **kwargs): self.settings = kwargs.pop('settings_instance') super().__init__(*args, **kwargs) self.fields['point'].widget = maps_widgets.MapChoosePointWidget( polygon=self.settings.polygon) self.fields['point'].error_messages['required'] = _( 'Please locate your proposal on the map.') class Meta: model = models.MapIdea fields = ['name', 'description', 'category', 'point', 'point_label'] class MapIdeaModerateForm(forms.ModelForm): class Meta: model = models.MapIdea fields = ['moderator_feedback']
from django import forms from django.utils.translation import ugettext_lazy as _ from adhocracy4.categories.forms import CategorizableFieldMixin from adhocracy4.maps import widgets as maps_widgets from . import models class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm): def __init__(self, *args, **kwargs): self.settings = kwargs.pop('settings_instance') super().__init__(*args, **kwargs) self.fields['point'].widget = maps_widgets.MapChoosePointWidget( polygon=self.settings.polygon) self.fields['point'].error_messages['required'] = _( 'Please locate your proposal on the map.') class Meta: model = models.MapIdea fields = ['name', 'description', 'category', 'point', 'point_label'] class MapIdeaModerateForm(forms.ModelForm): class Meta: model = models.MapIdea fields = ['moderator_feedback']
Add unserialize handler for data objects
<?php namespace Slack; /** * A serializable model object that stores its data in a hash. */ abstract class DataObject implements \JsonSerializable { /** * @var array The object's data cache. */ public $data = []; /** * Creates a data object from an array of data. * * @param array $data The array containing object data. * * @return self A new object instance. */ public static function fromData(array $data) { $reflection = new \ReflectionClass(static::class); $instance = $reflection->newInstanceWithoutConstructor(); $instance->data = $data; $instance->jsonUnserialize($data); return $instance; } /** * Returns scalar data to be serialized. * * @return array */ public function jsonSerialize() { return $this->data; } /** * Re-initializes the object when unserialized or created from a data array. * * @param array $data The object data. */ public function jsonUnserialize(array $data) { } }
<?php namespace Slack; /** * A serializable model object that stores its data in a hash. */ abstract class DataObject implements \JsonSerializable { /** * @var array The object's data cache. */ public $data = []; /** * Creates a data object from an array of data. * * @param array $data The array containing object data. * * @return self A new object instance. */ public static function fromData(array $data) { $reflection = new \ReflectionClass(static::class); $instance = $reflection->newInstanceWithoutConstructor(); $instance->data = $data; return $instance; } /** * Returns scalar data to be serialized. * * @return array */ public function jsonSerialize() { return $this->data; } }
[1.4][sfSympalPlugin][0.7] Fix so we only enable markdown editor for Markdown slot types git-svn-id: a12887034337be3812df6d060455f26cce89a7aa@25946 ee427ae8-e902-0410-961c-c3ed070cd9f9
<?php include_stylesheets_for_form($form) ?> <?php include_javascripts_for_form($form) ?> <span id="sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form" class="sympal_<?php echo sfInflector::tableize($contentSlot->getType()) ?>_content_slot_editor_form"> <?php echo $form->renderHiddenFields() ?> <?php if ($contentSlot->getIsColumn()): ?> <?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot') && !isset($form[$contentSlot->getName()])): ?> <?php echo $form[$sf_user->getCulture()][$contentSlot->getName()] ?> <?php else: ?> <?php echo $form[$contentSlot->getName()] ?> <?php endif; ?> <?php else: ?> <?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot')): ?> <?php echo $form[$sf_user->getCulture()]['value'] ?> <?php else: ?> <?php echo $form['value'] ?> <?php endif; ?> <?php endif; ?> </span> <script type="text/javascript"> <?php if ($contentSlot->getType() == 'Markdown'): ?> $('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form textarea').markItUp(mySettings); <?php endif; ?> $('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form textarea').elastic(); </script>
<?php include_stylesheets_for_form($form) ?> <?php include_javascripts_for_form($form) ?> <span id="sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form" class="sympal_<?php echo sfInflector::tableize($contentSlot->getType()) ?>_content_slot_editor_form"> <?php echo $form->renderHiddenFields() ?> <?php if ($contentSlot->getIsColumn()): ?> <?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot') && !isset($form[$contentSlot->getName()])): ?> <?php echo $form[$sf_user->getCulture()][$contentSlot->getName()] ?> <?php else: ?> <?php echo $form[$contentSlot->getName()] ?> <?php endif; ?> <?php else: ?> <?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot')): ?> <?php echo $form[$sf_user->getCulture()]['value'] ?> <?php else: ?> <?php echo $form['value'] ?> <?php endif; ?> <?php endif; ?> </span> <script type="text/javascript"> $('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form textarea').markItUp(mySettings); $('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form').elastic(); </script>
Convert tests to es6 format
var fs = require('fs') var slSystems = require('../src/slSystemsCrawler') var webTimmi = require('../src/webTimmiCrawler') describe('sls systems crawler', () => { var obj var expected before(() => { obj = slSystems.table(fs.readFileSync(__dirname + '/fixture/meilahti.html', 'utf-8')) expected = JSON.parse(fs.readFileSync(__dirname + '/fixture/meilahti.json', 'utf-8')) }) it('transforms table to json', () => { expect(obj).to.eql(expected) }) }) describe('web timmi crawler', () => { var obj var expected before(() => { obj = webTimmi.parseMarkup(fs.readFileSync(__dirname + '/fixture/weekViewMenu.html', 'utf-8')) expected = JSON.parse(fs.readFileSync(__dirname + '/fixture/taivallahti.json', 'utf-8')) }) it('transforms table to json', () => { expect(obj).to.eql(expected) }) })
var fs = require('fs') var slSystems = require('../src/slSystemsCrawler') var webTimmi = require('../src/webTimmiCrawler') describe('sls systems crawler', function () { var obj var expected before(function () { obj = slSystems.table(fs.readFileSync(__dirname + '/fixture/meilahti.html', 'utf-8')) expected = JSON.parse(fs.readFileSync(__dirname + '/fixture/meilahti.json', 'utf-8')) }) it('transforms table to json', function () { expect(obj).to.eql(expected) }) }) describe('web timmi crawler', function () { var obj var expected before(function () { obj = webTimmi.parseMarkup(fs.readFileSync(__dirname + '/fixture/weekViewMenu.html', 'utf-8')) expected = JSON.parse(fs.readFileSync(__dirname + '/fixture/taivallahti.json', 'utf-8')) }) it('transforms table to json', function () { expect(obj).to.eql(expected) }) })
Use a basic for loop
module.exports = Ready; function Ready() { var listeners = []; var args = null; function onReady(callback) { if (typeof callback === "function") { if (args) { call(callback); } else { listeners.push(callback); } } } onReady.signal = function signalReady() { if (args) return; // TODO: error? observe? just use last? args = Array.prototype.slice.call(arguments); for (var i = 0; i < listeners.length; i++) { call(listeners[i]); } listeners = []; return; }; function call(cb) { cb.apply(null, args); } return onReady; }
module.exports = Ready; function Ready() { var listeners = []; var args = null; function onReady(callback) { if (typeof callback === "function") { if (args) { call(callback); } else { listeners.push(callback); } } } onReady.signal = function signalReady() { if (args) return; // TODO: error? observe? just use last? args = Array.prototype.slice.call(arguments); listeners.forEach(call); listeners = []; return; }; function call(cb) { cb.apply(null, args); } return onReady; }
Update the crontab schedule to run every day at midnight
""" Celery tasks for the User Profiles portion of RAPID. """ import datetime import logging from celery.schedules import crontab from celery.task import PeriodicTask from profiles.models import Profile LOGGER = logging.getLogger(None) """The logger for this module""" # Note: Logging doesn't appear to work properly unless we get the root logger class Update_Users(PeriodicTask): """ Periodic task to update users as inactive who have not logged in for more than 90 days This class runs every day at midnight """ run_every = crontab(minute=0, hour=0) def run(self, **kwargs): LOGGER.debug("Running Update_Users task...") print("Updating users alert flag...") current_time = datetime.datetime.utcnow() #print("current_time",current_time) expired_date = current_time - datetime.timedelta(days=90) print("expired_date:",expired_date) Profile.objects.filter(last_login__lte = expired_date).update(alerts=False,is_active=False)
""" Celery tasks for the User Profiles portion of RAPID. """ import datetime import logging from celery.schedules import crontab from celery.task import PeriodicTask from profiles.models import Profile LOGGER = logging.getLogger(None) """The logger for this module""" # Note: Logging doesn't appear to work properly unless we get the root logger class Update_Users(PeriodicTask): """ Periodic task to update users as inactive who have not logged in for more than 90 days This class runs every day at midnight """ #run_every = crontab(minute=0, hour=0) run_every = crontab() def run(self, **kwargs): LOGGER.debug("Running Update_Users task...") print("Updating users alert flag...") current_time = datetime.datetime.utcnow() #print("current_time",current_time) expired_date = current_time - datetime.timedelta(days=90) print("expired_date:",expired_date) Profile.objects.filter(last_login__lte = expired_date).update(alerts=False,is_active=False)
Add &v as alias for &vote
package com.tisawesomeness.minecord.command.misc; import com.tisawesomeness.minecord.Bot; import com.tisawesomeness.minecord.command.Command; import com.tisawesomeness.minecord.util.MessageUtils; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.utils.MarkdownUtil; public class VoteCommand extends Command { public CommandInfo getInfo() { return new CommandInfo( "vote", "Vote for the bot!", null, new String[]{"v", "upvote", "updoot", "rep"}, 0, false, false, false ); } public Result run(String[] args, MessageReceivedEvent e) throws Exception { String m = "Top.gg: " + MarkdownUtil.maskedLink("VOTE", "https://top.gg/bot/292279711034245130/vote"); return new Result(Outcome.SUCCESS, MessageUtils.embedMessage("Vote for Minecord!", null, m, Bot.color)); } }
package com.tisawesomeness.minecord.command.misc; import com.tisawesomeness.minecord.Bot; import com.tisawesomeness.minecord.command.Command; import com.tisawesomeness.minecord.util.MessageUtils; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.utils.MarkdownUtil; public class VoteCommand extends Command { public CommandInfo getInfo() { return new CommandInfo( "vote", "Vote for the bot!", null, new String[]{"upvote", "updoot", "rep"}, 0, false, false, false ); } public Result run(String[] args, MessageReceivedEvent e) throws Exception { String m = "Top.gg: " + MarkdownUtil.maskedLink("VOTE", "https://top.gg/bot/292279711034245130/vote"); return new Result(Outcome.SUCCESS, MessageUtils.embedMessage("Vote for Minecord!", null, m, Bot.color)); } }
Make the 'd' in 'updated' optional along with the space before the date
"use strict"; const util = require("gulp-util"); const through = require("through2"); const moment = require("moment"); module.exports = function(options) { options = options || {}; function updateDate(file, options) { const now = moment().format("YYYY/MM/DD"), regex = /Last updated?: ?(\d{4}\/\d{2}\/\d{2})/i, prev = regex.exec(file)[1]; if (options.log) { util.log( `${util.colors.cyan("[gulp-update-humanstxt-date]")} ` + `Found the previous date to be: ${util.colors.red(prev)}. ` + `Replacing with ${util.colors.green(now)}.` ); } file = file.replace(prev, now); return file; } return through.obj(function(file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new util.PluginError("gulp-update-humanstxt-date", "Streaming not supported")); return; } try { file.contents = new Buffer(updateDate(file.contents.toString(), options)); this.push(file); } catch (err) { this.emit("error", new util.PluginError("gulp-update-humanstxt-date", err)); } cb(); }); };
"use strict"; const util = require("gulp-util"); const through = require("through2"); const moment = require("moment"); module.exports = function(options) { options = options || {}; function updateDate(file, options) { const now = moment().format("YYYY/MM/DD"), regex = /Last updated: (\d{4}\/\d{2}\/\d{2})/i, prev = regex.exec(file)[1]; if (options.log) { util.log( `${util.colors.cyan("[gulp-update-humanstxt-date]")} ` + `Found the previous date to be: ${util.colors.red(prev)}. ` + `Replacing with ${util.colors.green(now)}.` ); } file = file.replace(prev, now); return file; } return through.obj(function(file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new util.PluginError("gulp-update-humanstxt-date", "Streaming not supported")); return; } try { file.contents = new Buffer(updateDate(file.contents.toString(), options)); this.push(file); } catch (err) { this.emit("error", new util.PluginError("gulp-update-humanstxt-date", err)); } cb(); }); };
Increment version in preparation for release
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests']) raise SystemExit(errno) setup( name='gis_metadata_parser', description='Parser for GIS metadata standards including FGDC and ISO-19115', keywords='fgdc,iso,ISO-19115,ISO-19139,metadata,xml,parser', version='0.6.0', packages=[ 'gis_metadata', 'gis_metadata.tests' ], install_requires=[ 'parserutils', 'six' ], url='https://github.com/consbio/gis-metadata-parser', license='BSD', cmdclass={'test': RunTests} )
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests']) raise SystemExit(errno) setup( name='gis_metadata_parser', description='Parser for GIS metadata standards including FGDC and ISO-19115', keywords='fgdc,iso,ISO-19115,ISO-19139,metadata,xml,parser', version='0.5.0', packages=[ 'gis_metadata', 'gis_metadata.tests' ], install_requires=[ 'parserutils', 'six' ], url='https://github.com/consbio/gis-metadata-parser', license='BSD', cmdclass={'test': RunTests} )
[Telegram] Update to context based callbacks
import telegram import telegram.ext import os import dotenv version = "0.2.0" # Load credentials from .env dotenv.load_dotenv() token = os.getenv("TELEGRAM_BOT_API_TOKEN") bot = telegram.Bot(token = token) updater = telegram.ext.Updater(token = token, use_context = True) def test(update, context): context.bot.sendMessage(chat_id = update.message.chat_id, text = "Hello, World!") def ping(update, context): context.bot.sendMessage(chat_id = update.message.chat_id, text = "pong") test_handler = telegram.ext.CommandHandler("test", test) updater.dispatcher.add_handler(test_handler) ping_handler = telegram.ext.CommandHandler("ping", ping) updater.dispatcher.add_handler(ping_handler) updater.start_polling() bot_info = bot.getMe() print(f"Started up Telegram Harmonbot ({bot_info['username']}) ({bot_info['id']})") if os.getenv("CI") or os.getenv("GITHUB_ACTION"): updater.stop()
import telegram import telegram.ext import os import dotenv version = "0.1.4" # Load credentials from .env dotenv.load_dotenv() token = os.getenv("TELEGRAM_BOT_API_TOKEN") bot = telegram.Bot(token = token) updater = telegram.ext.Updater(token = token) def test(bot, update): bot.sendMessage(chat_id = update.message.chat_id, text = "Hello, World!") def ping(bot, update): bot.sendMessage(chat_id = update.message.chat_id, text = "pong") test_handler = telegram.ext.CommandHandler("test", test) updater.dispatcher.add_handler(test_handler) ping_handler = telegram.ext.CommandHandler("ping", ping) updater.dispatcher.add_handler(ping_handler) updater.start_polling() bot_info = bot.getMe() print(f"Started up Telegram Harmonbot ({bot_info['username']}) ({bot_info['id']})") if os.getenv("CI") or os.getenv("GITHUB_ACTION"): updater.stop()
Use "os" as valid constant for SYSTEM EOL check
package org.theultimatedeployer.enforcer.editorconfig.check; /** * Created by chris on 20.09.16. */ public class EOLCheckConfig implements CheckConfig{ public static final int SYSTEM = 0; public static final int UNIX = 1; public static final int WINDOWS = 2; // MAC OS X now uses UNIX -> old apple ;-) public static final int OLD_APPLE = 3; int plattform; public EOLCheckConfig(final String configVal) { if ("system".equalsIgnoreCase(configVal) || "os".equalsIgnoreCase(configVal)) { plattform = SYSTEM; } else if ("LF".equalsIgnoreCase(configVal)) { plattform = UNIX; } else if ("CRLF".equalsIgnoreCase(configVal)){ plattform = WINDOWS; } } public boolean isWindows() { return plattform == WINDOWS; } public boolean isUnix() { return plattform == UNIX; } public boolean isOldApple() { return plattform == OLD_APPLE; } public void setUnix() { plattform = UNIX; } public void setWindows() { plattform = WINDOWS; } public void setOldApple() { plattform = OLD_APPLE; } }
package org.theultimatedeployer.enforcer.editorconfig.check; /** * Created by chris on 20.09.16. */ public class EOLCheckConfig implements CheckConfig{ public static final int SYSTEM = 0; public static final int UNIX = 1; public static final int WINDOWS = 2; // MAC OS X now uses UNIX -> old apple ;-) public static final int OLD_APPLE = 3; int plattform; public EOLCheckConfig(final String configVal) { if ("system".equalsIgnoreCase(configVal)) { plattform = SYSTEM; } else if ("LF".equalsIgnoreCase(configVal)) { plattform = UNIX; } else if ("CRLF".equalsIgnoreCase(configVal)){ plattform = WINDOWS; } } public boolean isWindows() { return plattform == WINDOWS; } public boolean isUnix() { return plattform == UNIX; } public boolean isOldApple() { return plattform == OLD_APPLE; } public void setUnix() { plattform = UNIX; } public void setWindows() { plattform = WINDOWS; } public void setOldApple() { plattform = OLD_APPLE; } }