text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix the spellchecker nastyness in the rteditor
CKEDITOR.editorConfig = function( config ) { config.toolbar = 'Full'; config.toolbar_Full = [ ['Styles', '-', 'Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink', 'Image', '-', 'Undo', 'Redo', '-', 'Find', 'Replace', 'SelectAll'] ]; config.toolbar_Lite = [ ['Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink'] ]; config.resize_enabled = false; config.toolbarCanCollapse = false; config.stylesSet = 'coorg:coorgStyles.js'; config.removePlugins = 'elementspath,scayt'; config.disableNativeSpellchecker = false; // If we choose to enable scayt again, we have to set our own language... // config.scayt_sLang = COORGLANG; };
CKEDITOR.editorConfig = function( config ) { config.toolbar = 'Full'; config.toolbar_Full = [ ['Styles', '-', 'Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink', 'Image', '-', 'Undo', 'Redo', '-', 'Find', 'Replace', 'SelectAll'] ]; config.toolbar_Lite = [ ['Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink'] ]; config.resize_enabled = false; config.toolbarCanCollapse = false; config.stylesSet = 'coorg:coorgStyles.js'; config.removePlugins = 'elementspath'; };
Add disableHostCheck for dev server
import webpack from 'webpack'; import baseConfig from './base.babel'; const host = 'localhost'; const port = 3000; const baseDevConfig = { ...baseConfig, mode: 'development', devtool: 'inline-source-map', devServer: { host, port, disableHostCheck: true }, output: { ...baseConfig.output, publicPath: `http://localhost:${port}/js/`, }, module: { rules: [ ...baseConfig.module.rules, { test: /\.css?$/, use: ['style-loader', 'raw-loader'], }, ], }, plugins: [ ...baseConfig.plugins, new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), }), ], }; const buildDevConfig = config => ({ ...baseDevConfig, ...config, }); export default [ buildDevConfig({ entry: './app/index', target: 'electron-renderer', }), buildDevConfig({ entry: './app/worker/index.js', resolve: { ...baseDevConfig.resolve, aliasFields: ['browser'], }, output: { ...baseDevConfig.output, filename: 'RNDebuggerWorker.js', libraryTarget: undefined, }, target: 'webworker', }), ];
import webpack from 'webpack'; import baseConfig from './base.babel'; const host = 'localhost'; const port = 3000; const baseDevConfig = { ...baseConfig, mode: 'development', devtool: 'inline-source-map', devServer: { host, port }, output: { ...baseConfig.output, publicPath: `http://localhost:${port}/js/`, }, module: { rules: [ ...baseConfig.module.rules, { test: /\.css?$/, use: ['style-loader', 'raw-loader'], }, ], }, plugins: [ ...baseConfig.plugins, new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), }), ], }; const buildDevConfig = config => ({ ...baseDevConfig, ...config, }); export default [ buildDevConfig({ entry: './app/index', target: 'electron-renderer', }), buildDevConfig({ entry: './app/worker/index.js', resolve: { ...baseDevConfig.resolve, aliasFields: ['browser'], }, output: { ...baseDevConfig.output, filename: 'RNDebuggerWorker.js', libraryTarget: undefined, }, target: 'webworker', }), ];
Use getPublishedPost when displaying a post
<?php namespace SymfonyDay\Bundle\BlogBundle\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class DefaultController extends Controller { /** * @Route("/blog", name="blog") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getEntityManager(); $posts = $em->getRepository('SymfonyDayBlogBundle:Post') ->getMostRecentPosts() ; return array('posts' => $posts); } /** * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post") * @Template() */ public function postAction($id) { $em = $this->getDoctrine()->getEntityManager(); $post = $em->getRepository('SymfonyDayBlogBundle:Post') ->getPublishedPost($id) ; if (!$post) { throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id)); } return array('post' => $post); } }
<?php namespace SymfonyDay\Bundle\BlogBundle\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class DefaultController extends Controller { /** * @Route("/blog", name="blog") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getEntityManager(); $posts = $em->getRepository('SymfonyDayBlogBundle:Post') ->getMostRecentPosts() ; return array('posts' => $posts); } /** * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post") * @Template() */ public function postAction($id) { $em = $this->getDoctrine()->getEntityManager(); $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id); if (!$post) { throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id)); } return array('post' => $post); } }
Fix change because you swapped url auth mechanisms
import React from "react"; import { JSON_AUTHORIZATION_HEADERS, JSON_POST_AUTHORIZATION_HEADERS } from "../constants/requests"; import { LOGOUT_URL } from "../constants/urls"; export const getFetch = url => { return fetch(url, { method: "GET", headers: JSON_AUTHORIZATION_HEADERS }); }; export const getFetchJSONAPI = url => { return getFetch(url).then(response => { // If not authenticated, means token has expired // force a hard logout if (response.status === 401) { window.location.assign(LOGOUT_URL); } const results = response.json(); return results; }); }; export const postFetchJSONAPI = (url, postParams) => { return fetch(url, { method: "POST", headers: JSON_POST_AUTHORIZATION_HEADERS, body: JSON.stringify(postParams) }).then(response => { if (!response.ok) { alert("Invalid Request Entered"); } return response.json(); }); };
import React from "react"; import { JSON_AUTHORIZATION_HEADERS, JSON_POST_AUTHORIZATION_HEADERS } from "../constants/requests"; import { LOGOUT_URL } from "../constants/urls"; export const getFetch = url => { return fetch(url, { method: "GET", headers: JSON_AUTHORIZATION_HEADERS }); }; export const getFetchJSONAPI = url => { return getFetch(url).then(response => { // If not authenticated, means token has expired // force a hard logout if (response.status === 403) { window.location.assign(LOGOUT_URL); } const results = response.json(); return results; }); }; export const postFetchJSONAPI = (url, postParams) => { return fetch(url, { method: "POST", headers: JSON_POST_AUTHORIZATION_HEADERS, body: JSON.stringify(postParams) }).then(response => { if (!response.ok) { alert("Invalid Request Entered"); } return response.json(); }); };
Add input file presence check
package main import ( "flag" "fmt" "os" ) var output string func init() { flag.Usage = func() { fmt.Printf("Usage: %s [-out=out.path] in.path\n\n", os.Args[0]) flag.PrintDefaults() } flag.StringVar(&output, "out", "out.go", "Specify a path to the output file") flag.Parse() } func main() { checkRequirements() file, err := os.Open(flag.Arg(0)) if err != nil { fmt.Printf("Error! %s\n", err) os.Exit(2) } defer file.Close() fmt.Printf("input file: %s, output file: %s\n", flag.Arg(0), output) } func checkRequirements() { args := flag.Args() if len(args) == 0 { flag.Usage() fmt.Printf("Error! The input file is required\n") os.Exit(1) } else if len(args) > 1 { fmt.Printf("Notice! To many positional arguments, ignoring %v\n", args[1:]) } }
package main import ( "flag" "fmt" "os" ) var output string func init() { flag.Usage = func() { fmt.Printf("Usage: %s [-out=out.path] in.path\n\n", os.Args[0]) flag.PrintDefaults() } flag.StringVar(&output, "out", "out.go", "Specify a path to the output file") flag.Parse() } func main() { checkRequirements() fmt.Printf("input file: %s, output file: %s\n", flag.Arg(0), output) } func checkRequirements() { args := flag.Args() if len(args) == 0 { flag.Usage() fmt.Printf("Error! The input file is required\n") os.Exit(1) } else if len(args) > 1 { fmt.Printf("Notice! To many positional arguments, ignoring %v\n", args[1:]) } }
emojiRow: Create `handlePress` function to to call onPress with param. So that, instead of creating new arrow function for each emojiRow, there can be a single function which can be called with corresponding emoji name to autocomplete.
/* @flow */ import React, { PureComponent } from 'react'; import { StyleSheet, View } from 'react-native'; import { RawLabel, Touchable } from '../common'; import Emoji from '../emoji/Emoji'; const styles = StyleSheet.create({ emojiRow: { flexDirection: 'row', padding: 8, alignItems: 'center', }, text: { paddingLeft: 6, }, }); type Props = { name: string, onPress: (name: string) => void, }; export default class EmojiRow extends PureComponent<Props> { props: Props; handlePress = () => { const { name, onPress } = this.props; onPress(name); }; render() { const { name } = this.props; // TODO: this only handles Unicode emoji (shipped with the app), // not realm emoji or Zulip extra emoji. See our issue #2846. return ( <Touchable onPress={this.handlePress}> <View style={styles.emojiRow}> <Emoji name={name} size={20} /> <RawLabel style={styles.text} text={name} /> </View> </Touchable> ); } }
/* @flow */ import React, { PureComponent } from 'react'; import { StyleSheet, View } from 'react-native'; import { RawLabel, Touchable } from '../common'; import Emoji from '../emoji/Emoji'; const styles = StyleSheet.create({ emojiRow: { flexDirection: 'row', padding: 8, alignItems: 'center', }, text: { paddingLeft: 6, }, }); type Props = { name: string, onPress: () => void, }; export default class EmojiRow extends PureComponent<Props> { props: Props; render() { const { name, onPress } = this.props; // TODO: this only handles Unicode emoji (shipped with the app), // not realm emoji or Zulip extra emoji. See our issue #2846. return ( <Touchable onPress={onPress}> <View style={styles.emojiRow}> <Emoji name={name} size={20} /> <RawLabel style={styles.text} text={name} /> </View> </Touchable> ); } }
Prepend http to urls in user history
import os.path import json import urlparse ACCEPTED_FILETYPES = [ 'json', # 'csv' ] class HistoryParser(): def __init__(self, path): if not os.path.isfile(path): raise Exception("File not found.") if path.split(".")[-1] not in ACCEPTED_FILETYPES: raise Exception("Filetype not accepted.") self.path = path def _parse(self): with open(self.path) as data_file: data = json.load(data_file) return data def countVisitedPages(self): data = self._parse() visited = {} for entry in data: url = urlparse.urlparse(entry["url"]).netloc if len(url.split(".")) > 2: # some links are actually browser addons addresses try: visited[url] = visited[url] + entry["visitCount"] except: visited[url] = entry["visitCount"] return visited
import os.path import json import urlparse ACCEPTED_FILETYPES = [ 'json', # 'csv' ] class HistoryParser(): def __init__(self, path): if not os.path.isfile(path): raise Exception("File not found.") if path.split(".")[-1] not in ACCEPTED_FILETYPES: raise Exception("Filetype not accepted.") self.path = path def _parse(self): with open(self.path) as data_file: data = json.load(data_file) return data def countVisitedPages(self): data = self._parse() visited = {} for entry in data: url = urlparse.urlparse(entry["url"]).netloc try: visited[url] = visited[url] + entry["visitCount"] except: visited[url] = entry["visitCount"] return visited # hp = HistoryParser("../../example/andrei_history.json") # hp.countVisitedPages()
Use “lightGray” for web view background color
package mozilla.org.webmaker.view; import android.app.Activity; import android.content.Context; import android.view.ViewGroup; import mozilla.org.webmaker.R; import org.json.JSONObject; import org.xwalk.core.XWalkView; import mozilla.org.webmaker.client.WebClient; import mozilla.org.webmaker.javascript.WebAppInterface; public class WebmakerWebView extends XWalkView { public WebmakerWebView(Context context, Activity activity, String pageName) { this(context, activity, pageName, null); } public WebmakerWebView(Context context, Activity activity, String pageName, JSONObject routeParams) { super(context, activity); this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); this.load("file:///android_asset/www/pages/" + pageName + "/index.html", null); this.setResourceClient(new WebClient(this)); this.setBackgroundColor(getResources().getColor(R.color.light_gray)); this.addJavascriptInterface(new WebAppInterface(context, routeParams), "Android"); } }
package mozilla.org.webmaker.view; import android.app.Activity; import android.content.Context; import android.view.ViewGroup; import org.json.JSONObject; import org.xwalk.core.XWalkView; import mozilla.org.webmaker.client.WebClient; import mozilla.org.webmaker.javascript.WebAppInterface; public class WebmakerWebView extends XWalkView { public WebmakerWebView(Context context, Activity activity, String pageName) { this(context, activity, pageName, null); } public WebmakerWebView(Context context, Activity activity, String pageName, JSONObject routeParams) { super(context, activity); this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); this.load("file:///android_asset/www/pages/" + pageName + "/index.html", null); this.setResourceClient(new WebClient(this)); this.setBackgroundColor(0x00000000); this.addJavascriptInterface(new WebAppInterface(context, routeParams), "Android"); } }
Change the call from BooleanStr::toStr to BooleanStr::toString
<?php namespace Bruno\AdobeConnectClient\Traits; use \Bruno\AdobeConnectClient\Helper\CamelCase as CC; use \Bruno\AdobeConnectClient\Helper\BooleanStr as B; /** * Converts the public properties into an array to use in the WS call * * Works only for the not empty properties. False and null are considered empty values. */ trait ParameterTrait { /** * Convert the public properties into an array to use in the WS call * * @return array */ public function toArray() { $parameters = []; foreach ($this as $field => $value) { if (empty($value)) { continue; } if (is_bool($value)) { $value = B::toString($value); } elseif ($value instanceof \DateTimeInterface) { $value = $value->format(\DateTime::W3C); } $parameters[CC::toHyphen($field)] = $value; } return $parameters; } }
<?php namespace Bruno\AdobeConnectClient\Traits; use \Bruno\AdobeConnectClient\Helper\CamelCase as CC; use \Bruno\AdobeConnectClient\Helper\BooleanStr as B; /** * Converts the public properties into an array to use in the WS call * * Works only for the not empty properties. False and null are considered empty values. */ trait ParameterTrait { /** * Convert the public properties into an array to use in the WS call * * @return array */ public function toArray() { $parameters = []; foreach ($this as $field => $value) { if (empty($value)) { continue; } if (is_bool($value)) { $value = B::toStr($value); } elseif ($value instanceof \DateTimeInterface) { $value = $value->format(\DateTime::W3C); } $parameters[CC::toHyphen($field)] = $value; } return $parameters; } }
Support args in different orders
var exec = require('child_process').exec; var path = require('path'); var extend = require('xtend'); var command = require('language-command'); /** * Execute a file in a particular programming language. * * @param {String} language * @param {String} file * @param {Array} args * @param {Object} opts * @param {Function} done */ module.exports = function (language, file, args, opts, done) { // Support for skipping arguments and options. if (typeof args === 'function') { done = args; args = null; opts = null; } // Support for skipping options. if (typeof opts === 'function') { done = opts; opts = null; } // Reverse options and arguments. if (typeof args === 'object' && !Array.isArray(args)) { opts = args; args = null; } var cmd = command(language, file, args); // Pass back the language unsupported error in an async fashion. if (cmd == null) { return done(new Error('Language not supported')); } return exec(cmd, extend({ cwd: path.dirname(file) }, opts), done); };
var exec = require('child_process').exec; var path = require('path'); var extend = require('xtend'); var command = require('language-command'); /** * Execute a file in a particular programming language. * * @param {String} language * @param {String} file * @param {String} args * @param {Object} opts * @param {Function} done */ module.exports = function (language, file, args, opts, done) { // Support for skipping arguments and options. if (typeof args === 'function') { done = args; args = null; opts = null; } // Support for skipping options. if (typeof opts === 'function') { done = opts; opts = null; } var cmd = command(language, file, args); // Pass back the language unsupported error in an async fashion. if (cmd == null) { return done(new Error('Language not supported')); } return exec(cmd, extend({ cwd: path.dirname(file) }, opts), done); };
Handle Android RN 0.47 breaking change
package com.reactlibrary.linkedinsdk; 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.Arrays; import java.util.Collections; import java.util.List; public class RNLinkedInSessionManagerPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNLinkedInSessionManagerModule(reactContext)); } // Deprecated RN 0.47 public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package com.reactlibrary.linkedinsdk; 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.Arrays; import java.util.Collections; import java.util.List; public class RNLinkedInSessionManagerPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNLinkedInSessionManagerModule(reactContext)); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Test - checking visibitlity of Change Avatar link
describe('tests', function() { var username = "USERNAME"; var linksnum = 0; var links = element.all(by.repeater('link in annotatedlinks')); browser.get('https://webmaker.org/user/' + username); it('Should have a title', function() { expect(browser.getTitle()).toEqual(username + ' | Webmaker'); }); it('Should display username', function() { expect(element(by.binding(' WMP.username ')).getText()).toEqual(username); }); it('Should show correct number of links', function() { expect(links.count()).toEqual(linksnum); }); it('Should not display edit button when not logged in', function() { expect(element(by.buttonText('Edit')).isPresent()).toBe(false); }); it('Should show login buttton', function() { expect(element(by.buttonText('Log In')).isPresent()).toBe(true); }); it('Should not display change avatar when not logged in', function() { expect(element(by.binding(' Gravatar | i18n ')).isPresent()).toBe(false); }); });
describe('tests', function() { var username = "USERNAME"; var linksnum = 0; var links = element.all(by.repeater('link in annotatedlinks')); browser.get('https://webmaker.org/user/' + username); it('Should have a title', function() { expect(browser.getTitle()).toEqual(username + ' | Webmaker'); }); it('Should display username', function() { expect(element(by.binding(' WMP.username ')).getText()).toEqual(username); }); it('Should show correct number of links', function() { expect(links.count()).toEqual(linksnum); }); it('Should not display edit button when not logged in', function() { expect(element(by.buttonText('Edit')).isPresent()).toBe(false); }); it('Should show login buttton', function() { expect(element(by.buttonText('Log In')).isPresent()).toBe(true); }); });
Send PM to querying user (i think? bad docs.)
import pre import supybot.log as log import supybot.conf as conf import supybot.utils as utils import supybot.world as world import supybot.ircdb as ircdb from supybot.commands import * import supybot.irclib as irclib import supybot.ircmsgs as ircmsgs import supybot.plugins as plugins import supybot.ircutils as ircutils import supybot.callbacks as callbacks class Dupe(callbacks.Plugin): def _dupe(self, irc, query, limit): results = pre.dupe(query, limit) if (results): irc.reply(format('Got %s.', results.length)) irc.reply(format('Results %s', results), private=True) else: irc.reply(format('Could not find any results for %s.', name)) def dupe(self, irc, msg, args, text): """dupe <search> Perform a search for dupe releases using Pre.im's Web API """ limit = self.registryValue('limit', msg.args[0]) self._dupe(irc, text, limit) dupe = wrap(dupe, ['text']) Class = Dupe
import pre import supybot.log as log import supybot.conf as conf import supybot.utils as utils import supybot.world as world import supybot.ircdb as ircdb from supybot.commands import * import supybot.irclib as irclib import supybot.ircmsgs as ircmsgs import supybot.plugins as plugins import supybot.ircutils as ircutils import supybot.callbacks as callbacks class Dupe(callbacks.Plugin): def _dupe(self, irc, query, limit): results = pre.dupe(query, limit) if (results): irc.reply(format('Got %s.', results)) else: irc.reply(format('Could not find any results for %s.', name)) def dupe(self, irc, msg, args, text): """dupe <search> Perform a search for dupe releases using Pre.im's Web API """ limit = self.registryValue('limit', msg.args[0]) self._dupe(irc, text, limit) dupe = wrap(dupe, ['text']) Class = Dupe
Add role removal and logic cleanup
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author,role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign + " ." else: await client.add_roles(message.author,role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is if len(msg) != 1: try: await client.add_roles(message.author,message.server.roles[role[0]]) except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." client.send_message(message.channel, msg) else: pass
Use lombok to create contructors
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless 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 org.springframework.data.gclouddatastore.repository; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; @Data @AllArgsConstructor @NoArgsConstructor public class Person { @Id private long id; private String emailAddress; private String firstName; private String lastName; private int birthYear; private boolean citizen; public Person(long id) { this.id = id; } }
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless 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 org.springframework.data.gclouddatastore.repository; import lombok.Data; import org.springframework.data.annotation.Id; @Data public class Person { @Id private long id; private String emailAddress; private String firstName; private String lastName; private int birthYear; private boolean citizen; public Person() { } public Person(long id) { this.id = id; } }
Correct background image manipulation doc
<?php namespace League\Glide\Manipulators; use Intervention\Image\Image; use League\Glide\Manipulators\Helpers\Color; /** * @property string $bg */ class Background extends BaseManipulator { /** * Perform background image manipulation. * @param Image $image The source image. * @return Image The manipulated image. */ public function run(Image $image) { if (is_null($this->bg)) { return $image; } $color = (new Color($this->bg))->formatted(); if ($color) { $new = $image->getDriver()->newImage($image->width(), $image->height(), $color); $new->mime = $image->mime; $image = $new->insert($image, 'top-left', 0, 0); } return $image; } }
<?php namespace League\Glide\Manipulators; use Intervention\Image\Image; use League\Glide\Manipulators\Helpers\Color; /** * @property string $bg */ class Background extends BaseManipulator { /** * Perform blur image manipulation. * @param Image $image The source image. * @return Image The manipulated image. */ public function run(Image $image) { if (is_null($this->bg)) { return $image; } $color = (new Color($this->bg))->formatted(); if ($color) { $new = $image->getDriver()->newImage($image->width(), $image->height(), $color); $new->mime = $image->mime; $image = $new->insert($image, 'top-left', 0, 0); } return $image; } }
Change notifier interval: 20 -> 10
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() job_defaults = { 'coalesce': False, 'max_instances': 2 } scheduler = BlockingScheduler(job_defaults=job_defaults) @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier (interval=1)") subprocess.check_call( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', minutes=10) def timed_job_min10(): print("Run notifier (interval=10)") subprocess.check_call( "notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', days=7) def timed_job_days7(): print("Run teacher_error_resetter") subprocess.check_call( "teacher_error_resetter -concurrency=5", shell=True) scheduler.start()
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() job_defaults = { 'coalesce': False, 'max_instances': 2 } scheduler = BlockingScheduler(job_defaults=job_defaults) @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier (interval=1)") subprocess.check_call( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', minutes=20) def timed_job_min10(): print("Run notifier (interval=10)") subprocess.check_call( "notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', days=7) def timed_job_days7(): print("Run teacher_error_resetter") subprocess.check_call( "teacher_error_resetter -concurrency=5", shell=True) scheduler.start()
Change DataCenters from struct to slice
package clcgo import ( "encoding/json" "errors" "fmt" ) type DataCenters []DataCenter type DataCenter struct { ID string Name string } const DataCentersURL = APIRoot + "/datacenters/%s" func (d DataCenters) URL(a string) (string, error) { return fmt.Sprintf(DataCentersURL, a), nil } func (d *DataCenters) Unmarshal(j []byte) error { return json.Unmarshal(j, &d) } type DataCenterCapabilities struct { DataCenter DataCenter `json:"-"` Templates []struct { Name string Description string } } const DataCenterCapabilitiesURL = DataCentersURL + "/%s/deploymentCapabilities" func (d DataCenterCapabilities) URL(a string) (string, error) { if d.DataCenter.ID == "" { return "", errors.New("Need a DataCenter with an ID") } return fmt.Sprintf(DataCenterCapabilitiesURL, a, d.DataCenter.ID), nil } func (d *DataCenterCapabilities) Unmarshal(j []byte) error { return json.Unmarshal(j, &d) }
package clcgo import ( "encoding/json" "errors" "fmt" ) type DataCenters struct { DataCenters []DataCenter } type DataCenter struct { ID string Name string } const DataCentersURL = APIRoot + "/datacenters/%s" func (d DataCenters) URL(a string) (string, error) { return fmt.Sprintf(DataCentersURL, a), nil } func (d *DataCenters) Unmarshal(j []byte) error { return json.Unmarshal(j, &d.DataCenters) } type DataCenterCapabilities struct { DataCenter DataCenter `json:"-"` Templates []struct { Name string Description string } } const DataCenterCapabilitiesURL = DataCentersURL + "/%s/deploymentCapabilities" func (d DataCenterCapabilities) URL(a string) (string, error) { if d.DataCenter.ID == "" { return "", errors.New("Need a DataCenter with an ID") } return fmt.Sprintf(DataCenterCapabilitiesURL, a, d.DataCenter.ID), nil } func (d *DataCenterCapabilities) Unmarshal(j []byte) error { return json.Unmarshal(j, &d) }
Fix 'popupOptions' typo in 'github'
Github = {}; // Request Github credentials for the user // @param options {optional} // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Github.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'github'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback( new ServiceConfiguration.ConfigError()); return; } var credentialToken = Random.secret(); var scope = (options && options.requestPermissions) || []; var flatScope = _.map(scope, encodeURIComponent).join('+'); var loginStyle = OAuth._loginStyle('github', config, options); var loginUrl = 'https://github.com/login/oauth/authorize' + '?client_id=' + config.clientId + '&scope=' + flatScope + '&redirect_uri=' + OAuth._redirectUri('github', config) + '&state=' + OAuth._stateParam(loginStyle, credentialToken); OAuth.launchLogin({ loginService: "github", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: credentialRequestCompleteCallback, credentialToken: credentialToken, popupOptions: {width: 900, height: 450} }); };
Github = {}; // Request Github credentials for the user // @param options {optional} // @param credentialRequestCompleteCallback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. Github.requestCredential = function (options, credentialRequestCompleteCallback) { // support both (options, callback) and (callback). if (!credentialRequestCompleteCallback && typeof options === 'function') { credentialRequestCompleteCallback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'github'}); if (!config) { credentialRequestCompleteCallback && credentialRequestCompleteCallback( new ServiceConfiguration.ConfigError()); return; } var credentialToken = Random.secret(); var scope = (options && options.requestPermissions) || []; var flatScope = _.map(scope, encodeURIComponent).join('+'); var loginStyle = OAuth._loginStyle('github', config, options); var loginUrl = 'https://github.com/login/oauth/authorize' + '?client_id=' + config.clientId + '&scope=' + flatScope + '&redirect_uri=' + OAuth._redirectUri('github', config) + '&state=' + OAuth._stateParam(loginStyle, credentialToken); OAuth.launchLogin({ loginService: "github", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: credentialRequestCompleteCallback, credentialToken: credentialToken, popupOptons: {width: 900, height: 450} }); };
Use https for docs URL
import sys import textwrap try: import gi gi.require_version("Gst", "1.0") from gi.repository import GLib, GObject, Gst except ImportError: print( textwrap.dedent( """ ERROR: A GObject based library was not found. Mopidy requires GStreamer to work. GStreamer is a C library with a number of dependencies itself, and cannot be installed with the regular Python tools like pip. Please see https://docs.mopidy.com/en/latest/installation/ for instructions on how to install the required dependencies. """ ) ) raise else: Gst.init([]) gi.require_version("GstPbutils", "1.0") from gi.repository import GstPbutils GLib.set_prgname("mopidy") GLib.set_application_name("Mopidy") REQUIRED_GST_VERSION = (1, 14, 0) REQUIRED_GST_VERSION_DISPLAY = ".".join(map(str, REQUIRED_GST_VERSION)) if Gst.version() < REQUIRED_GST_VERSION: sys.exit( f"ERROR: Mopidy requires GStreamer >= {REQUIRED_GST_VERSION_DISPLAY}, " f"but found {Gst.version_string()}." ) __all__ = [ "GLib", "GObject", "Gst", "GstPbutils", "gi", ]
import sys import textwrap try: import gi gi.require_version("Gst", "1.0") from gi.repository import GLib, GObject, Gst except ImportError: print( textwrap.dedent( """ ERROR: A GObject based library was not found. Mopidy requires GStreamer to work. GStreamer is a C library with a number of dependencies itself, and cannot be installed with the regular Python tools like pip. Please see http://docs.mopidy.com/en/latest/installation/ for instructions on how to install the required dependencies. """ ) ) raise else: Gst.init([]) gi.require_version("GstPbutils", "1.0") from gi.repository import GstPbutils GLib.set_prgname("mopidy") GLib.set_application_name("Mopidy") REQUIRED_GST_VERSION = (1, 14, 0) REQUIRED_GST_VERSION_DISPLAY = ".".join(map(str, REQUIRED_GST_VERSION)) if Gst.version() < REQUIRED_GST_VERSION: sys.exit( f"ERROR: Mopidy requires GStreamer >= {REQUIRED_GST_VERSION_DISPLAY}, " f"but found {Gst.version_string()}." ) __all__ = [ "GLib", "GObject", "Gst", "GstPbutils", "gi", ]
Add a few asserts to the test git-svn-id: c55cfc7c8893d43c3333f2d886128b43c8520716@380472 13f79535-47bb-0310-9956-ffa450edef68
package org.xbean.jmx; import junit.framework.TestCase; import org.xbean.spring.context.ClassPathXmlApplicationContext; import java.util.List; /** * $Rev$ */ public class JMXTest extends TestCase { public void testSimple() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/xbean/jmx/jmx-simple.xml"); try { Object jmxService = context.getBean("jmxService"); assertNotNull(jmxService); Object jmxExporter = context.getBean("jmxExporter"); assertNotNull(jmxExporter); assertTrue(jmxExporter instanceof MBeanExporter); List mbeans = ((MBeanExporter) jmxExporter).getMBeans(); assertNotNull(mbeans); assertEquals(2, mbeans.size()); assertSame(jmxService, mbeans.get(0)); assertSame(jmxService, mbeans.get(1)); } finally { context.destroy(); } } }
package org.xbean.jmx; import junit.framework.TestCase; import org.xbean.spring.context.ClassPathXmlApplicationContext; /** * $Rev$ */ public class JMXTest extends TestCase { public void testSimple() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/xbean/jmx/jmx-simple.xml"); try { Object jmxService = context.getBean("jmxService"); assertNotNull(jmxService); Object jmxExporter = context.getBean("jmxExporter"); assertNotNull(jmxExporter); } finally { context.destroy(); } } }
Change Discogs URL from http to https
<?php namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class DiscogsResourceOwner extends GenericOAuth1ResourceOwner { /** * {@inheritDoc} */ protected $paths = array( 'identifier' => 'id', 'nickname' => 'username' ); /** * {@inheritDoc} */ protected function configureOptions(OptionsResolverInterface $resolver) { parent::configureOptions($resolver); $resolver->setDefaults(array( 'authorization_url' => 'https://www.discogs.com/oauth/authorize', 'request_token_url' => 'https://api.discogs.com/oauth/request_token', 'access_token_url' => 'https://api.discogs.com/oauth/access_token', 'infos_url' => 'https://api.discogs.com/oauth/identity', )); } }
<?php namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class DiscogsResourceOwner extends GenericOAuth1ResourceOwner { /** * {@inheritDoc} */ protected $paths = array( 'identifier' => 'id', 'nickname' => 'username' ); /** * {@inheritDoc} */ protected function configureOptions(OptionsResolverInterface $resolver) { parent::configureOptions($resolver); $resolver->setDefaults(array( 'authorization_url' => 'http://www.discogs.com/oauth/authorize', 'request_token_url' => 'http://api.discogs.com/oauth/request_token', 'access_token_url' => 'http://api.discogs.com/oauth/access_token', 'infos_url' => 'http://api.discogs.com/oauth/identity', )); } }
Include plan name in trial to active stripe event notification
<?php namespace SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\TrialingToActive; use SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\ActionStatusTest; abstract class TrialingToActiveTest extends ActionStatusTest { abstract protected function getHasCard(); public function testNotificationHasCard() { $this->assertNotificationBodyField('has_card', (int)$this->getHasCard()); } protected function getCurrentSubscriptionStatus() { return 'active'; } protected function getPreviousSubscriptionStatus() { return 'trialing'; } protected function getStripeEventFixturePath() { return $this->getFixturesDataPath() . '/../../StripeEvents/customer.subscription.updated.statuschange.json'; } }
<?php namespace SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\TrialingToActive; use SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\ActionStatusTest; abstract class TrialingToActiveTest extends ActionStatusTest { abstract protected function getHasCard(); public function testNotificationHasCard() { $this->assertNotificationBodyField('has_card', (int)$this->getHasCard()); } public function testNotificationHasPlan() { $this->assertNotificationBodyField('plan', 'agency'); } protected function getCurrentSubscriptionStatus() { return 'active'; } protected function getPreviousSubscriptionStatus() { return 'trialing'; } protected function getStripeEventFixturePath() { return $this->getFixturesDataPath() . '/../../StripeEvents/customer.subscription.updated.statuschange.json'; } }
Revert to relative path for sources.
import os import platform import setuptools # # --- Detect if extensions should be disabled ------------------------------ wrapt_env = os.environ.get('WRAPT_INSTALL_EXTENSIONS') if wrapt_env is None: wrapt_env = os.environ.get('WRAPT_EXTENSIONS') if wrapt_env is not None: disable_extensions = wrapt_env.lower() == 'false' force_extensions = wrapt_env.lower() == 'true' else: disable_extensions = False force_extensions = False if platform.python_implementation() != "CPython": disable_extensions = True # --- C extension ------------------------------------------------------------ extensions = [ setuptools.Extension( "wrapt._wrappers", sources=["src/wrapt/_wrappers.c"], optional=not force_extensions, ) ] # --- Setup ------------------------------------------------------------------ setuptools.setup( ext_modules=[] if disable_extensions else extensions )
import os import platform import setuptools # # --- Detect if extensions should be disabled ------------------------------ wrapt_env = os.environ.get('WRAPT_INSTALL_EXTENSIONS') if wrapt_env is None: wrapt_env = os.environ.get('WRAPT_EXTENSIONS') if wrapt_env is not None: disable_extensions = wrapt_env.lower() == 'false' force_extensions = wrapt_env.lower() == 'true' else: disable_extensions = False force_extensions = False if platform.python_implementation() != "CPython": disable_extensions = True # --- C extension ------------------------------------------------------------ extensions = [ setuptools.Extension( "wrapt._wrappers", sources=[ os.path.realpath(os.path.join(__file__, "..", "src", "wrapt", "_wrappers.c"))], optional=not force_extensions, ) ] # --- Setup ------------------------------------------------------------------ setuptools.setup( ext_modules=[] if disable_extensions else extensions )
Remove superfluous 'is True' from the assert.
""" .. module:: config_parser :platform: linux :synopsis: Module to test the bunch YAML configuration parser. .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/26/15 """ from bunch import Bunch import pytest from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.test import constants @pytest.fixture(scope='module') def fix_parser(): return BunchParser() def test_parse_nonexistent_file(fix_parser, capsys): with pytest.raises(SystemExit): fix_parser.parse('nonexistent') out, err = capsys.readouterr() assert "ERROR: No configuration file" in str(out) def test_parse_bad_file(fix_parser, capsys): config_file = constants.TEST_BAD_CONFIG_FILE with pytest.raises(SystemExit): fix_parser.parse(config_file) out, err = capsys.readouterr() assert "ERROR: Error parsing the configuration file" in str(out) def test_parse_config_file(fix_parser): config_file = constants.TEST_SYSTEM_YAML b = fix_parser.parse(config_file) assert isinstance(b, Bunch)
""" .. module:: config_parser :platform: linux :synopsis: Module to test the bunch YAML configuration parser. .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/26/15 """ from bunch import Bunch import pytest from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.test import constants @pytest.fixture(scope='module') def fix_parser(): return BunchParser() def test_parse_nonexistent_file(fix_parser, capsys): with pytest.raises(SystemExit): fix_parser.parse('nonexistent') out, err = capsys.readouterr() assert "ERROR: No configuration file" in str(out) def test_parse_bad_file(fix_parser, capsys): config_file = constants.TEST_BAD_CONFIG_FILE with pytest.raises(SystemExit): fix_parser.parse(config_file) out, err = capsys.readouterr() assert "ERROR: Error parsing the configuration file" in str(out) def test_parse_config_file(fix_parser): config_file = constants.TEST_SYSTEM_YAML b = fix_parser.parse(config_file) assert isinstance(b, Bunch) is True
Mark login as Index route
import React from 'react'; import { Route } from 'react-router'; import { IndexRoute } from 'react-router'; import Login from './features/login'; import CategoryTileListContainer from './features/categories/components/CategoryTileListContainer'; import ChallengeScreenContainer from './features/challenges/components/ChallengeScreenContainer'; import TodoScreen from './features/todo/TodoScreen'; import Awards from './features/awards'; import Updates from './features/updates'; import Profile from './features/profile'; export default () => ( <Route path="/" > <IndexRoute component={Login} /> <Route path="login" component={Login} /> <Route path="challenges" component={ChallengeScreenContainer} /> <Route path="awards" component={Awards} /> <Route path="updates" component={Updates} /> <Route path="profile" component={Profile} /> <Route path="todo" component={TodoScreen} /> <Route path="categories" component={CategoryTileListContainer} /> </Route> );
import React from 'react'; import { Route } from 'react-router'; import Login from './features/login'; import CategoryTileListContainer from './features/categories/components/CategoryTileListContainer'; import ChallengeScreenContainer from './features/challenges/components/ChallengeScreenContainer'; import TodoScreen from './features/todo/TodoScreen'; import Awards from './features/awards'; import Updates from './features/updates'; import Profile from './features/profile'; export default () => ( <Route path="/" > <Route path="login" component={Login} /> <Route path="challenges" component={ChallengeScreenContainer} /> <Route path="awards" component={Awards} /> <Route path="updates" component={Updates} /> <Route path="profile" component={Profile} /> <Route path="todo" component={TodoScreen} /> <Route path="categories" component={CategoryTileListContainer} /> </Route> );
Use config to build paths
/** * Copyright (c) 2013-2015 Memba Sarl. All rights reserved. * Sources at https://github.com/Memba */ /* jshint node: true, expr: true */ /* globals describe: false, before: false, it: false */ 'use strict'; var request = require('supertest'), util = require('util'), //We cannot define app like this because the server is already running //app = request('../../../webapp/server'); config = require('../../../webapp/config'), app = config.get('uris:webapp:root'); describe('routes/feedRoute', function() { it('it should return an english feed', function(done) { request(app) .get(util.format(config.get('uris:webapp:feed'), 'en')) .expect(200) .expect('Content-Type', /rss/) .end(done); }); it('it should return a french feed', function(done) { request(app) .get(util.format(config.get('uris:webapp:feed'), 'fr')) .expect(200) .expect('Content-Type', /rss/) .end(done); }); });
/** * Copyright (c) 2013-2015 Memba Sarl. All rights reserved. * Sources at https://github.com/Memba */ /* jshint node: true, expr: true */ /* globals describe: false, before: false, it: false */ 'use strict'; var request = require('supertest'), //We cannot define app like this because the server is already running //app = request('../../../webapp/server'); config = require('../../../webapp/config'), app = config.get('uris:webapp:root'); describe('routes/feedRoute', function() { it('it should return an english feed', function(done) { request(app) .get('/en/index.rss') .expect(200) .expect('Content-Type', /rss/) .end(done); }); it('it should return a french feed', function(done) { request(app) .get('/fr/index.rss') .expect(200) .expect('Content-Type', /rss/) .end(done); }); });
Implement __str__ for proper printing in admin
from django.db import models class QuestionGroup(models.Model): heading = models.TextField() text = models.TextField(blank=True) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ". " + self.heading class Question(models.Model): text = models.TextField() question_group = models.ForeignKey(QuestionGroup) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ". " + self.text class Choice(models.Model): text = models.TextField() question = models.ForeignKey(Question) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ". " + self.text class Session(models.Model): name = models.TextField(blank=True) ip = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now=True) date_submitted = models.DateTimeField(null=True) class Response(models.Model): choice = models.ForeignKey(Choice) session = models.ForeignKey(Session) value = models.IntegerField() date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True)
from django.db import models class QuestionGroup(models.Model): heading = models.TextField() text = models.TextField(blank=True) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) class Question(models.Model): text = models.TextField() question_group = models.ForeignKey(QuestionGroup) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) class Choice(models.Model): text = models.TextField() question = models.ForeignKey(Question) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) class Session(models.Model): name = models.TextField(blank=True) ip = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now=True) date_submitted = models.DateTimeField(null=True) class Response(models.Model): choice = models.ForeignKey(Choice) session = models.ForeignKey(Session) value = models.IntegerField() date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True)
Reduce number of concurrent consumers for owner -> node route
/* * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. 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 won.owner.camel.routes.fixed; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; /** * User: LEIH-NB Date: 10.10.13 */ // TODO: change to asyncronous processing maybe public class AmqpToJms extends RouteBuilder { @Override public void configure() { from("seda:outgoingMessages?concurrentConsumers=1").routeId("Owner2NodeRoute").choice() .when(header("remoteBrokerEndpoint").isNull()) .log(LoggingLevel.ERROR, "could not route message: remoteBrokerEndpoint is null") .throwException(new IllegalArgumentException( "could not route message: remoteBrokerEndpoint is null")) .otherwise().recipientList(header("remoteBrokerEndpoint")); } }
/* * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. 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 won.owner.camel.routes.fixed; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; /** * User: LEIH-NB Date: 10.10.13 */ // TODO: change to asyncronous processing maybe public class AmqpToJms extends RouteBuilder { @Override public void configure() { from("seda:outgoingMessages?concurrentConsumers=5").routeId("Owner2NodeRoute").choice() .when(header("remoteBrokerEndpoint").isNull()) .log(LoggingLevel.ERROR, "could not route message: remoteBrokerEndpoint is null") .throwException(new IllegalArgumentException( "could not route message: remoteBrokerEndpoint is null")) .otherwise().recipientList(header("remoteBrokerEndpoint")); } }
Update md test for render fix
from mfr.ext.md import Handler, render from mock import MagicMock def test_render_html(): fakefile = MagicMock(spec=file) fakefile.read.return_value = '# foo' assert render.render_html(fakefile).content == '<h1>foo</h1>' fakefile.read.return_value = '_italic_' assert render.render_html(fakefile).content == '<p><em>italic</em></p>' fakefile.read.return_value = '*italic*' assert render.render_html(fakefile).content == '<p><em>italic</em></p>' fakefile.read.return_value = ''' * one * two''' assert render.render_html(fakefile).content == '''<ul> <li>one</li> <li>two</li> </ul>''' def test_detect(fakefile): test_handler=Handler() fakefile.name='file.notmd' assert test_handler.detect(fakefile) is False fakefile.name='file.md' assert test_handler.detect(fakefile) is True fakefile.name='file.markdown' assert test_handler.detect(fakefile) is True
from mfr.ext.md import Handler, render from mock import MagicMock def test_render_html(): fakefile = MagicMock(spec=file) fakefile.read.return_value = '# foo' assert render.render_html(fakefile) == '<h1>foo</h1>' fakefile.read.return_value = '_italic_' assert render.render_html(fakefile) == '<p><em>italic</em></p>' fakefile.read.return_value = '*italic*' assert render.render_html(fakefile) == '<p><em>italic</em></p>' fakefile.read.return_value = ''' * one * two''' assert render.render_html(fakefile) == '''<ul> <li>one</li> <li>two</li> </ul>''' def test_detect(fakefile): test_handler=Handler() fakefile.name='file.notmd' assert test_handler.detect(fakefile) is False fakefile.name='file.md' assert test_handler.detect(fakefile) is True fakefile.name='file.markdown' assert test_handler.detect(fakefile) is True
Improve error handling without API key
import { getSetting } from 'meteor/vulcan:core'; import googleMaps from '@google/maps' const googleMapsApiKey = getSetting('googleMaps.serverApiKey', null) let googleMapsClient = null if (googleMapsApiKey) { googleMapsClient = googleMaps.createClient({ key: googleMapsApiKey, Promise: Promise }); } else { // eslint-disable-next-line no-console console.log("No Server-side Google maps API key provided, please provide one for proper timezone handling") } export async function getLocalTime(time, googleLocation) { if (!googleMapsClient) { // eslint-disable-next-line no-console console.log("No Server-side Google Maps API key provided, can't resolve local time") return null } try { const { geometry: { location } } = googleLocation const apiResponse = await googleMapsClient.timezone({location, timestamp: new Date(time)}).asPromise() const { json: { dstOffset, rawOffset } } = apiResponse //dstOffset and rawOffset are in the unit of seconds const localTimestamp = new Date(time).getTime() + ((dstOffset + rawOffset)*1000) // Translate seconds to milliseconds return new Date(localTimestamp) } catch(err) { // eslint-disable-next-line no-console console.error("Error in getting local time:", err) throw err } }
import { getSetting } from 'meteor/vulcan:core'; import googleMaps from '@google/maps' const googleMapsApiKey = getSetting('googleMaps.serverApiKey', null) let googleMapsClient = null if (googleMapsApiKey) { googleMapsClient = googleMaps.createClient({ key: googleMapsApiKey, Promise: Promise }); } else { // eslint-disable-next-line no-console console.log("No Google maps API key provided, please provide one for proper geocoding") } export async function getLocalTime(time, googleLocation) { try { const { geometry: { location } } = googleLocation const apiResponse = await googleMapsClient.timezone({location, timestamp: new Date(time)}).asPromise() const { json: { dstOffset, rawOffset } } = apiResponse //dstOffset and rawOffset are in the unit of seconds const localTimestamp = new Date(time).getTime() + ((dstOffset + rawOffset)*1000) // Translate seconds to milliseconds return new Date(localTimestamp) } catch(err) { // eslint-disable-next-line no-console console.error("Error in getting local time:", err) throw err } }
Remove non-standard attribute in test user.
""" A static dictionary with SAML testusers that can be used as response. """ USERS = { "testuser1": { "sn": ["Testsson 1"], "givenName": ["Test 1"], "eduPersonAffiliation": ["student"], "eduPersonScopedAffiliation": ["student@example.com"], "eduPersonPrincipalName": ["test@example.com"], "uid": ["testuser1"], "eduPersonTargetedID": ["one!for!all"], "c": ["SE"], "o": ["Example Co."], "ou": ["IT"], "initials": ["P"], "schacHomeOrganization": ["example.com"], "email": ["test@example.com"], "displayName": ["Test Testsson"], "norEduPersonNIN": ["SE199012315555"] } }
""" A static dictionary with SAML testusers that can be used as response. """ USERS = { "testuser1": { "sn": ["Testsson 1"], "givenName": ["Test 1"], "eduPersonAffiliation": ["student"], "eduPersonScopedAffiliation": ["student@example.com"], "eduPersonPrincipalName": ["test@example.com"], "uid": ["testuser1"], "eduPersonTargetedID": ["one!for!all"], "c": ["SE"], "o": ["Example Co."], "ou": ["IT"], "initials": ["P"], "schacHomeOrganization": ["example.com"], "email": ["test@example.com"], "displayName": ["Test Testsson"], "labeledURL": ["http://www.example.com/haho My homepage"], "norEduPersonNIN": ["SE199012315555"], } }
Fix nofity crash if done callback is not set
'use strict'; var http = require('http'), color = require('cli-color'), defaults = require('../defaults.json'); module.exports = function(hostname, port, done) { var data = 'reload' var options = { hostname: hostname || '127.0.0.1', port: port || defaults.notifyPort, path: '/', method: 'POST', headers: { 'Content-Type': 'text/plain', 'Content-Length': data.length } }; var req = http.request(options, function() { if (typeof done === 'function') { done(); } }); req.on('error', function() { console.error(color.red('LiveReactload: could not send reload notification. Are you sure that reload server is listening?')); }) req.write(data); req.end(); }
'use strict'; var http = require('http'), color = require('cli-color'), defaults = require('../defaults.json'); module.exports = function(hostname, port, done) { var data = 'reload' var options = { hostname: hostname || '127.0.0.1', port: port || defaults.notifyPort, path: '/', method: 'POST', headers: { 'Content-Type': 'text/plain', 'Content-Length': data.length } }; var req = http.request(options, function() { done(); }); req.on('error', function() { console.error(color.red('LiveReactload: could not send reload notification. Are you sure that reload server is listening?')); }) req.write(data); req.end(); }
lxd/lifecycle/storage/pool: Remove projectName arg from StoragePoolAction.Event Storage pools don't have projects. Signed-off-by: Thomas Parrott <6b778ce645fb0e3dde76d79eccad490955b1ae74@canonical.com>
package lifecycle import ( "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/version" ) // StoragePoolAction represents a lifecycle event action for storage pools. type StoragePoolAction string // All supported lifecycle events for storage pools. const ( StoragePoolCreated = StoragePoolAction(api.EventLifecycleStoragePoolCreated) StoragePoolDeleted = StoragePoolAction(api.EventLifecycleStoragePoolDeleted) StoragePoolUpdated = StoragePoolAction(api.EventLifecycleStoragePoolUpdated) ) // Event creates the lifecycle event for an action on an storage pool. func (a StoragePoolAction) Event(name string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle { u := api.NewURL().Path(version.APIVersion, "storage-pools", name) return api.EventLifecycle{ Action: string(a), Source: u.String(), Context: ctx, Requestor: requestor, } }
package lifecycle import ( "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/version" ) // StoragePoolAction represents a lifecycle event action for storage pools. type StoragePoolAction string // All supported lifecycle events for storage pools. const ( StoragePoolCreated = StoragePoolAction(api.EventLifecycleStoragePoolCreated) StoragePoolDeleted = StoragePoolAction(api.EventLifecycleStoragePoolDeleted) StoragePoolUpdated = StoragePoolAction(api.EventLifecycleStoragePoolUpdated) ) // Event creates the lifecycle event for an action on an storage pool. func (a StoragePoolAction) Event(name string, projectName string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle { u := api.NewURL().Path(version.APIVersion, "storage-pools", name).Project(projectName) return api.EventLifecycle{ Action: string(a), Source: u.String(), Context: ctx, Requestor: requestor, } }
Fix prettier config to remove unecessary diff
const webpack = require('webpack') const path = require('path') const fs = require('fs') const output = path.join(__dirname, 'output', 'webpack') const loader = path.join(__dirname, '..', '..') const baseConfig = { entry: path.join(__dirname, 'fixtures/fib.ml'), module: { rules: [ { test: /\.(re|ml)$/, use: { loader, options: { cwd: __dirname } } } ] }, resolve: { extensions: ['.re', '.ml', '.js'] }, output: { path: output, libraryTarget: 'commonjs2' } } it('runs', done => { webpack(baseConfig, err => { expect(err).toBeNull() fs.readdir(output, (err, files) => { expect(err).toBeNull() expect(files.length).toBe(1) const result = require(path.resolve(output, files[0])) expect(result.fib(12)).toBe(233) done() }) }) })
const webpack = require('webpack') const path = require('path') const fs = require('fs') const output = path.join(__dirname, 'output', 'webpack') const loader = path.join(__dirname, '..', '..') const baseConfig = { entry: path.join(__dirname, 'fixtures/fib.ml'), module: { rules: [ { test: /\.(re|ml)$/, use: { loader, options: { cwd: __dirname, }, }, }, ], }, resolve: { extensions: ['.re', '.ml', '.js'], }, output: { path: output, libraryTarget: 'commonjs2', }, } it('runs', done => { webpack(baseConfig, err => { expect(err).toBeNull() fs.readdir(output, (err, files) => { expect(err).toBeNull() expect(files.length).toBe(1) const result = require(path.resolve(output, files[0])) expect(result.fib(12)).toBe(233) done() }) }) })
Change default python string name str to mystr as str is a reserved name
#!/usr/bin/env python -u import cPickle import sys import urllib import base64 # # Output the maximum number of instances of this 'callable' to spawn # The absolute maximum is set in the configuration file via 'warpscript.call.maxcapacity' # print 10 # # Loop, reading stdin, doing our stuff and outputing to stdout # while True: try: # # Read input. 'CALL' will transmit a single string argument from the stack, URL encoding it before transmission. # The 'callable' should describe how its input is to be formatted. # For python callable, we recommend base64 encoded pickle content (generated via ->PICKLE). # line = sys.stdin.readline() line = line.strip() line = urllib.unquote(line.decode('utf-8')) # Remove Base64 encoding mystr = base64.b64decode(line) args = cPickle.loads(mystr) # # Do out stuff # output = 'output' # # Output result (URL encoded UTF-8). # print urllib.quote(output.encode('utf-8')) except Exception as err: # # If returning a content starting with ' ' (not URL encoded), then # the rest of the line is interpreted as a URL encoded UTF-8 of an error message # and will propagate the error to the calling WarpScript # print ' ' + urllib.quote(repr(err).encode('utf-8'))
#!/usr/bin/env python -u import cPickle import sys import urllib import base64 # # Output the maximum number of instances of this 'callable' to spawn # The absolute maximum is set in the configuration file via 'warpscript.call.maxcapacity' # print 10 # # Loop, reading stdin, doing our stuff and outputing to stdout # while True: try: # # Read input. 'CALL' will transmit a single string argument from the stack, URL encoding it before transmission. # The 'callable' should describe how its input is to be formatted. # For python callable, we recommend base64 encoded pickle content (generated via ->PICKLE). # line = sys.stdin.readline() line = line.strip() line = urllib.unquote(line.decode('utf-8')) # Remove Base64 encoding str = base64.b64decode(line) args = cPickle.loads(str) # # Do out stuff # output = 'output' # # Output result (URL encoded UTF-8). # print urllib.quote(output.encode('utf-8')) except Exception as err: # # If returning a content starting with ' ' (not URL encoded), then # the rest of the line is interpreted as a URL encoded UTF-8 of an error message # and will propagate the error to the calling WarpScript # print ' ' + urllib.quote(repr(err).encode('utf-8'))
Fix error with lodash map
var _ = require('lodash'); var Matcher = require('../matcher'); var factory = require('../factory'); var compile = require('../compile'); var s = require('../strummer'); module.exports = factory({ initialize: function(opts) { var matchers = { keys: null, values: null }; if (opts instanceof Matcher) { matchers.values = opts; } else if (typeof opts === 'object') { matchers.keys = opts.keys ? compile.spec(opts.keys) : null; matchers.values = opts.values ? compile.spec(opts.values) : null; } else if (opts) { matchers.values = compile.spec(opts); } this.matchers = matchers; }, match: function(path, obj) { if (obj == null || typeof obj !== 'object') { return [{path: path, value: obj, message: 'should be a hashmap'}]; } var errors = []; if (this.matchers.keys) { var keyErrors = s.array({of: this.matchers.keys}).match(path + '.keys', Object.keys(obj)); errors.push(keyErrors); } if (this.matchers.values) { var self = this; errors.push(_.map(obj, function(val, key) { return self.matchers.values.match(path + '[' + key + ']', val); })); } return _.compact(_.flattenDeep(errors)); } });
var _ = require('lodash'); var Matcher = require('../matcher'); var factory = require('../factory'); var compile = require('../compile'); var s = require('../strummer'); module.exports = factory({ initialize: function(opts) { var matchers = { keys: null, values: null }; if (opts instanceof Matcher) { matchers.values = opts; } else if (typeof opts === 'object') { matchers.keys = opts.keys ? compile.spec(opts.keys) : null; matchers.values = opts.values ? compile.spec(opts.values) : null; } else if (opts) { matchers.values = compile.spec(opts); } this.matchers = matchers; }, match: function(path, obj) { if (obj == null || typeof obj !== 'object') { return [{path: path, value: obj, message: 'should be a hashmap'}]; } var errors = []; if (this.matchers.keys) { var keyErrors = s.array({of: this.matchers.keys}).match(path + '.keys', Object.keys(obj)); errors.push(keyErrors); } if (this.matchers.values) { errors.push(_.map(obj, function(val, key) { return this.matchers.values.match(path + '[' + key + ']', val); }, this)); } return _.compact(_.flattenDeep(errors)); } });
Add fixme comment for user timings on Firefox.
(function() { /** * Browsertime (http://www.browsertime.com) * Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog * and other contributors * Released under the Apache 2.0 License */ // someway the get entries by type isn't working in IE using Selenium, // will spend time fixing this later, now just return empty if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return { measures: [], marks: [] }; } else { // FIXME marks exported from Firefox include "toJSON": "function toJSON() {\n [native code]\n}" return { measures: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType( 'measure') : [], marks: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType('mark') : [] }; } })();
(function() { /** * Browsertime (http://www.browsertime.com) * Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog * and other contributors * Released under the Apache 2.0 License */ // someway the get entries by type isn't working in IE using Selenium, // will spend time fixing this later, now just return empty if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return { measures: [], marks: [] }; } else { return { measures: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType( 'measure') : [], marks: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType('mark') : [] }; } })();
Set the number in sessions and correclty compare the values
// Dependencies var CaptchaPng = require("captchapng"); // Sessions var sessions = {}; // Captcha configuration var serverConfig = { width: 100, height: 30 }; // Get configuration M.emit("captcha.getConfig", function (c) { serverConfig = c; }); // Verify captcha M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer.toString() === sessions[sid].toString()); }); /** * captcha * Serves the captcha image * * @name captcha * @function * @param {Object} link Mono link object * @return */ exports.captcha = function (link) { var res = link.res; // Generate number and store it in sessions cache var number = parseInt(Math.random() * 9000 + 1000); var sid = link.session && link.session._sid; sessions[sid] = number; var cap = new CaptchaPng(serverConfig.width, serverConfig.height, number); cap.color(0, 100, 0, 0); cap.color(80, 80, 80, 255); var img = cap.getBase64(); var imgBase64 = new Buffer(img, "base64"); res.writeHead(200, { "Content-Type": "image/png" }); res.end(imgBase64); };
// Dependencies var CaptchaPng = require("captchapng"); // Sessions var sessions = {}; // Captcha configuration var serverConfig = { width: 100, height: 30 }; // Get configuration M.emit("captcha.getConfig", function (c) { serverConfig = c; }); // Verify captcha M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer === sessions[sid]); }); /** * captcha * Serves the captcha image * * @name captcha * @function * @param {Object} link Mono link object * @return */ exports.captcha = function (link) { var res = link.res; // Generate number and store it in sessions cache var number = parseInt(Math.random() * 9000 + 1000); if (!link.session || !link.session._sid) { sessions[link.session._sid] = number; } var cap = new CaptchaPng(serverConfig.width, serverConfig.height, number); cap.color(0, 100, 0, 0); cap.color(80, 80, 80, 255); var img = cap.getBase64(); var imgBase64 = new Buffer(img, "base64"); res.writeHead(200, { "Content-Type": "image/png" }); res.end(imgBase64); };
Fix errant space in learn more items
/* * * ToolPage * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import Markdown from 'react-remarkable'; import ContentBlock from 'components/ContentBlock'; import LatinThemeProvider from 'components/LatinThemeProvider'; import AdderRemover from 'containers/Tools/AdderRemover'; import { LearnMoreItem, LearnMoreItemLink, LearnMoreItemSource } from 'components/ToolsPageComponents'; // import { makeSelectToolById } from 'containers/Tool/selectors'; import messages from './messages'; export default function ToolLearnMoreItem(props) { // eslint-disable-line react/prefer-stateless-function return ( <LatinThemeProvider> <LearnMoreItem> <ContentBlock> <LearnMoreItemLink href={props.link} target='_blank'>{props.title}</LearnMoreItemLink> {props.source ? (<LearnMoreItemSource> | <Markdown className={'markdown'} source={props.year ? `${props.source}, ${props.year}` : props.source} /></LearnMoreItemSource>) : null } </ContentBlock> </LearnMoreItem> </LatinThemeProvider> ); }
/* * * ToolPage * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import Markdown from 'react-remarkable'; import ContentBlock from 'components/ContentBlock'; import LatinThemeProvider from 'components/LatinThemeProvider'; import AdderRemover from 'containers/Tools/AdderRemover'; import { LearnMoreItem, LearnMoreItemLink, LearnMoreItemSource } from 'components/ToolsPageComponents'; // import { makeSelectToolById } from 'containers/Tool/selectors'; import messages from './messages'; export default function ToolLearnMoreItem(props) { // eslint-disable-line react/prefer-stateless-function return ( <LatinThemeProvider> <LearnMoreItem> <ContentBlock> <LearnMoreItemLink href={props.link} target='_blank'>{props.title}</LearnMoreItemLink> {props.source !== '' ? (<LearnMoreItemSource> | <Markdown className={'markdown'} source={props.source} /> </LearnMoreItemSource>) : null } {props.year ? `, ${props.year}` : ''} </ContentBlock> </LearnMoreItem> </LatinThemeProvider> ); }
Change the create need title
; import angular from 'angular'; function genComponentConf() { let template = ` <nav class="create-need-title" ng-cloak ng-show="{{true}}"> <div class="cntb__inner"> <a class="cntb__inner__left clickable" ng-click="self.back()"> <img src="generated/icon-sprite.svg#ico27_close" class="cntb__icon"> </a> <h1 class="cntb__inner__center cntb__title">Hey, everyone!</div> </div> </nav> `; class Controller { constructor() { //this.testVar = 42; } back() { window.history.back() } } return { restrict: 'E', controller: Controller, controllerAs: 'self', template: template, bindToController: true, //scope-bindings -> ctrl scope: { } } } export default angular.module('won.owner.components.createNeedTitleBar', []) .directive('wonCreateNeedTitleBar', genComponentConf) .name;
; import angular from 'angular'; function genComponentConf() { let template = ` <nav class="create-need-title" ng-cloak ng-show="{{true}}"> <div class="cntb__inner"> <a class="cntb__inner__left clickable" ng-click="self.back()"> <img src="generated/icon-sprite.svg#ico27_close" class="cntb__icon"> </a> <h1 class="cntb__inner__center cntb__title">What is your need?</div> </div> </nav> `; class Controller { constructor() { //this.testVar = 42; } back() { window.history.back() } } return { restrict: 'E', controller: Controller, controllerAs: 'self', template: template, bindToController: true, //scope-bindings -> ctrl scope: { } } } export default angular.module('won.owner.components.createNeedTitleBar', []) .directive('wonCreateNeedTitleBar', genComponentConf) .name;
Return the stream for each task
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var jasmine = require('gulp-jasmine'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); gulp.task('lint', function () { return gulp.src('./*.js') .pipe(jshint('jshintrc.json')) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('test', function () { return gulp.src('test.js') .pipe(jasmine()); }); gulp.task('uglify', function () { return gulp.src('lambada.js') .pipe(uglify()) .pipe(rename('lambada.min.js')) .pipe(gulp.dest('.')); }); gulp.task('default', ['lint', 'test']);
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var jasmine = require('gulp-jasmine'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); gulp.task('lint', function () { gulp.src('./*.js') .pipe(jshint('jshintrc.json')) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('test', function () { gulp.src('test.js') .pipe(jasmine()); }); gulp.task('uglify', function () { gulp.src('lambada.js') .pipe(uglify()) .pipe(rename('lambada.min.js')) .pipe(gulp.dest('.')); }); gulp.task('default', ['lint', 'test']);
Use full path as cache key
from functools import wraps from django.conf import settings from django.core.cache import cache from django.template.response import ContentNotRenderedError from django.utils.decorators import available_attrs def cache_view(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(view, *args, **kwargs): cache_key = view.request.get_full_path() cached_response = cache.get(cache_key) if cached_response and not view.request.user.is_authenticated(): return cached_response response = view_func(view, *args, **kwargs) if response.status_code == 200 and not view.request.user.is_authenticated(): try: set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) except ContentNotRenderedError: response.add_post_render_callback( lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) ) return response return _wrapped_view_func def set_cache_after_rendering(cache_key, response, timeout): cache.set(cache_key, response, timeout)
from functools import wraps from django.conf import settings from django.core.cache import cache from django.template.response import ContentNotRenderedError from django.utils.decorators import available_attrs def cache_view(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(view, *args, **kwargs): cache_key = view.request.path cached_response = cache.get(cache_key) if cached_response and not view.request.user.is_authenticated(): return cached_response response = view_func(view, *args, **kwargs) if response.status_code == 200 and not view.request.user.is_authenticated(): try: set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) except ContentNotRenderedError: response.add_post_render_callback( lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) ) return response return _wrapped_view_func def set_cache_after_rendering(cache_key, response, timeout): cache.set(cache_key, response, timeout)
Fix greenlet and essential objects startup order
try: from gevent import monkey except ImportError: pass else: monkey.patch_all() from tendrl.commons import CommonNS from tendrl.node_agent.objects.definition import Definition from tendrl.node_agent.objects.config import Config from tendrl.node_agent.objects.node_context import NodeContext from tendrl.node_agent.objects.detected_cluster import DetectedCluster from tendrl.node_agent.objects.platform import Platform from tendrl.node_agent.objects.tendrl_context import TendrlContext from tendrl.node_agent.objects.service import Service from tendrl.node_agent.objects.cpu import Cpu from tendrl.node_agent.objects.disk import Disk from tendrl.node_agent.objects.file import File from tendrl.node_agent.objects.memory import Memory from tendrl.node_agent.objects.node import Node from tendrl.node_agent.objects.os import Os from tendrl.node_agent.objects.package import Package from tendrl.node_agent.objects.platform import Platform from tendrl.node_agent.flows.import_cluster import ImportCluster class NodeAgentNS(CommonNS): def __init__(self): # Create the "tendrl_ns.node_agent" namespace self.to_str = "tendrl.node_agent" self.type = 'node' super(NodeAgentNS, self).__init__() NodeAgentNS()
try: from gevent import monkey except ImportError: pass else: monkey.patch_all() from tendrl.commons import CommonNS from tendrl.node_agent.objects.definition import Definition from tendrl.node_agent.objects.config import Config from tendrl.node_agent.objects.node_context import NodeContext from tendrl.node_agent.objects.detected_cluster import DetectedCluster from tendrl.node_agent.objects.platform import Platform from tendrl.node_agent.objects.tendrl_context import TendrlContext from tendrl.node_agent.objects.service import Service from tendrl.node_agent.objects.cpu import Cpu from tendrl.node_agent.objects.disk import Disk from tendrl.node_agent.objects.file import File from tendrl.node_agent.objects.memory import Memory from tendrl.node_agent.objects.node import Node from tendrl.node_agent.objects.os import Os from tendrl.node_agent.objects.package import Package from tendrl.node_agent.objects.platform import Platform from tendrl.node_agent.flows.import_cluster import ImportCluster class NodeAgentNS(CommonNS): def __init__(self): # Create the "tendrl_ns.node_agent" namespace self.to_str = "tendrl.node_agent" self.type = 'node' super(NodeAgentNS, self).__init__() import __builtin__ __builtin__.tendrl_ns = NodeAgentNS()
Implement hbs partial auto detecting and registering
const fs = require(`fs`); const glob = require(`glob`); const Handlebars = require(`handlebars`); const htmlclean = require(`htmlclean`); const mkdir = require(`mkdirp`); const path = require(`path`); const viewsDirectory = path.join(process.cwd(), `resources`, `views`); const views = glob.sync(path.join(viewsDirectory, `**`, `*.hbs`)); views.forEach((view) => { const partialName = view.replace(`${viewsDirectory}/`, ``).replace(`.hbs`, ``); Handlebars.registerPartial(partialName, fs.readFileSync(view, `utf8`)); }); module.exports = (template, data, outputFile) => { let html = htmlclean(Handlebars.compile(template)(data)); // Fix <pre> indentation. const pattern = html.match(/\s*\n[\t\s]*/); html = html.replace(new RegExp(pattern, `g`), `\n`); try { mkdir.sync(path.parse(outputFile).dir); fs.writeFileSync(outputFile, html); } catch (error) { // eslint-disable-next-line no-console console.log(error); } };
const fs = require(`fs`); const Handlebars = require(`handlebars`); const htmlclean = require(`htmlclean`); const mkdir = require(`mkdirp`); const path = require(`path`); const layoutHbs = path.join(process.cwd(), `resources`, `views`, `layouts`, `main.hbs`); Handlebars.registerPartial(`layouts/main`, fs.readFileSync(layoutHbs, `utf8`)); const headerHbs = path.join(process.cwd(), `resources`, `views`, `partials`, `header.hbs`); Handlebars.registerPartial(`partials/header`, fs.readFileSync(headerHbs, `utf8`)); const footerHbs = path.join(process.cwd(), `resources`, `views`, `partials`, `footer.hbs`); Handlebars.registerPartial(`partials/footer`, fs.readFileSync(footerHbs, `utf8`)); module.exports = (template, data, outputFile) => { let html = htmlclean(Handlebars.compile(template)(data)); // Fix <pre> indentation. const pattern = html.match(/\s*\n[\t\s]*/); html = html.replace(new RegExp(pattern, `g`), `\n`); try { mkdir.sync(path.parse(outputFile).dir); fs.writeFileSync(outputFile, html); } catch (error) { // eslint-disable-next-line no-console console.log(error); } };
Add owner level to logger
const pino = require('pino') const serializers = require('./serializers.js') function createLogger (shardID) { return pino({ base: { shardID: String(shardID) }, customLevels: { owner: 35 }, prettyPrint: { translateTime: 'yyyy-mm-dd HH:MM:ss', messageFormat: `[{shardID}] \x1b[0m{msg}`, ignore: 'hostname,shardID' }, serializers: { guild: serializers.guild, textChannel: serializers.textChannel, role: serializers.textChannel, user: serializers.user, error: pino.stdSerializers.err }, enabled: !process.env.TEST_ENV }) } module.exports = createLogger
const pino = require('pino') const serializers = require('./serializers.js') function createLogger (shardID) { return pino({ base: { shardID: String(shardID) }, prettyPrint: { translateTime: 'yyyy-mm-dd HH:MM:ss', messageFormat: `[{shardID}] \x1b[0m{msg}`, ignore: 'hostname,shardID' }, serializers: { guild: serializers.guild, textChannel: serializers.textChannel, role: serializers.textChannel, user: serializers.user, error: pino.stdSerializers.err }, enabled: !process.env.TEST_ENV }) } module.exports = createLogger
Allow papers/maxout to be tested without MNIST data
import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.algorithm._set_monitoring_dataset(train.dataset) train.main_loop()
import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.main_loop()
Delete children when deleting dms folder
package com.axelor.dms.db.repo; import java.util.List; import java.util.Map; import org.joda.time.LocalDateTime; import com.axelor.db.JpaRepository; import com.axelor.dms.db.DMSFile; public class DMSFileRepository extends JpaRepository<DMSFile> { public DMSFileRepository() { super(DMSFile.class); } @Override public void remove(DMSFile entity) { // remove all children if (entity.getIsDirectory() == Boolean.TRUE) { final List<DMSFile> children = all().filter("self.parent.id = ?", entity.getId()).fetch(); for (DMSFile child : children) { if (child != entity) { remove(child);; } } } super.remove(entity); } @Override public Map<String, Object> populate(Map<String, Object> json) { final Object id = json.get("id"); if (id == null) { return json; } final DMSFile file = find((Long) id); if (file == null) { return json; } boolean isFile = file.getIsDirectory() != Boolean.TRUE; LocalDateTime dt = file.getUpdatedOn(); if (dt == null) { dt = file.getCreatedOn(); } json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder"); json.put("lastModified", dt); return json; } }
package com.axelor.dms.db.repo; import java.util.Map; import org.joda.time.LocalDateTime; import com.axelor.db.JpaRepository; import com.axelor.dms.db.DMSFile; public class DMSFileRepository extends JpaRepository<DMSFile> { public DMSFileRepository() { super(DMSFile.class); } @Override public Map<String, Object> populate(Map<String, Object> json) { final Object id = json.get("id"); if (id == null) { return json; } final DMSFile file = find((Long) id); if (file == null) { return json; } boolean isFile = file.getIsDirectory() != Boolean.TRUE; LocalDateTime dt = file.getUpdatedOn(); if (dt == null) { dt = file.getCreatedOn(); } json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder"); json.put("lastModified", dt); return json; } }
Correct method signature for BaseModel create
"""Interface for Models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf from keras import models from tf_trainer.common import text_preprocessor from tf_trainer.common import types from typing import Callable class BaseModel(abc.ABC): """Tentative interface for all model classes. Although the code doesn't take advantage of this interface yet, all models should subclass this one. """ @staticmethod def create( estimator_fn: Callable[[str], tf.estimator.Estimator]) -> 'BaseModel': class Model(BaseModel): def estimator(self, model_dir): return estimator_fn(model_dir) return Model() @abc.abstractmethod def estimator(self, model_dir: str) -> tf.estimator.Estimator: pass
"""Interface for Models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf from keras import models from tf_trainer.common import text_preprocessor from tf_trainer.common import types from typing import Callable class BaseModel(abc.ABC): """Tentative interface for all model classes. Although the code doesn't take advantage of this interface yet, all models should subclass this one. """ @staticmethod def create( estimator_fn: Callable[[str], tf.estimator.Estimator]) -> 'BaseModel': class Model(BaseModel): def estimator(model_dir): return estimator_fn(model_dir) return Model() @abc.abstractmethod def estimator(self, model_dir: str) -> tf.estimator.Estimator: pass
Upgrade migrate library to avoid using sqlite lib.
package migrator import ( _ "github.com/mattes/migrate/driver/postgres" "github.com/mattes/migrate/migrate" "github.com/resourced/resourced-master/config" ) func New(generalConfig config.GeneralConfig) *Migrator { m := &Migrator{} m.AppGeneralConfig = generalConfig return m } type Migrator struct { AppGeneralConfig config.GeneralConfig } func (m *Migrator) CoreMigrateUp() ([]error, bool) { return migrate.UpSync(m.AppGeneralConfig.DSN, "./migrations/core") } func (m *Migrator) TSWatchersMigrateUp() ([]error, bool) { for _, dsn := range m.AppGeneralConfig.Watchers.DSNs { errs, ok := migrate.UpSync(dsn, "./migrations/ts-watchers") if errs != nil && len(errs) > 0 { return errs, ok } } return nil, true } func (m *Migrator) TSMetricsMigrateUp() ([]error, bool) { for _, dsn := range m.AppGeneralConfig.Metrics.DSNs { errs, ok := migrate.UpSync(dsn, "./migrations/ts-metrics") if errs != nil && len(errs) > 0 { return errs, ok } } return nil, true }
package migrator import ( "github.com/mattes/migrate/migrate" "github.com/resourced/resourced-master/config" ) func New(generalConfig config.GeneralConfig) *Migrator { m := &Migrator{} m.AppGeneralConfig = generalConfig return m } type Migrator struct { AppGeneralConfig config.GeneralConfig } func (m *Migrator) CoreMigrateUp() ([]error, bool) { return migrate.UpSync(m.AppGeneralConfig.DSN, "./migrations/core") } func (m *Migrator) TSWatchersMigrateUp() ([]error, bool) { for _, dsn := range m.AppGeneralConfig.Watchers.DSNs { errs, ok := migrate.UpSync(dsn, "./migrations/ts-watchers") if errs != nil && len(errs) > 0 { return errs, ok } } return nil, true } func (m *Migrator) TSMetricsMigrateUp() ([]error, bool) { for _, dsn := range m.AppGeneralConfig.Metrics.DSNs { errs, ok := migrate.UpSync(dsn, "./migrations/ts-metrics") if errs != nil && len(errs) > 0 { return errs, ok } } return nil, true }
Enable background start of Cordova Android apps This closes #322
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 __ID__; import android.os.Bundle; import org.apache.cordova.*; public class __ACTIVITY__ extends CordovaActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // enable Cordova apps to be started in the background Bundle extras = getIntent().getExtras(); if (extras != null && extras.getBoolean("cdvStartInBackground", false)) { moveTaskToBack(true); } // Set by <content src="index.html" /> in config.xml loadUrl(launchUrl); } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 __ID__; import android.os.Bundle; import org.apache.cordova.*; public class __ACTIVITY__ extends CordovaActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set by <content src="index.html" /> in config.xml loadUrl(launchUrl); } }
Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105 Patch #3605769 by Legoktm Because of various issues [1], using wikidata.org may cause random problems. Using www.wikidata.org will fix these. [1] https://bugzilla.wikimedia.org/show_bug.cgi?id=45005
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
Fix action node overflow, background
import React from 'react'; import JSONTree from './JSONTree'; const styles = { actionBar: { paddingTop: 8, paddingBottom: 7, paddingLeft: 16 }, payload: { margin: 0, overflow: 'auto' } }; export default class LogMonitorAction extends React.Component { renderPayload(payload) { return ( <div style={{ ...styles.payload, backgroundColor: this.props.theme.base00 }}> { Object.keys(payload).length > 0 ? <JSONTree theme={this.props.theme} keyName={'action'} data={payload}/> : '' } </div> ); } render() { const { type, ...payload } = this.props.action; return ( <div style={{ backgroundColor: this.props.theme.base02, color: this.props.theme.base06, ...this.props.style }}> <div style={styles.actionBar} onClick={this.props.onClick}> {type} </div> {!this.props.collapsed ? this.renderPayload(payload) : ''} </div> ); } }
import React from 'react'; import JSONTree from './JSONTree'; const styles = { actionBar: { paddingTop: 8, paddingBottom: 7, paddingLeft: 16 }, payload: { paddingLeft: 15 } }; export default class LogMonitorAction extends React.Component { renderPayload(payload) { return ( <div style={{ ...styles.payload, backgroundColor: this.props.theme.base01 }}> { Object.keys(payload).length > 0 ? <JSONTree theme={this.props.theme} keyName={'action'} data={payload}/> : '' } </div> ); } render() { const { type, ...payload } = this.props.action; return ( <div style={{ backgroundColor: this.props.theme.base02, color: this.props.theme.base06, ...this.props.style }} onClick={this.props.onClick}> <div style={styles.actionBar}>{type}</div> {!this.props.collapsed ? this.renderPayload(payload) : ''} </div> ); } }
Change api for better semantics
class SimpleTest { constructor() { this.passed = 0; this.failed = 0; this.total = 0; } addAssert(condition, label = 'Unknown') { this.total++; if (!condition) { this.failed++; console.error('Test failed: ' + label); } else { this.passed++; } return this; } results() { if (this.passed === this.total) { console.log('All tests passed. (' + this.total + ')'); } else { console.log('Passed:' + this.passed + '/' + this.total); console.log('Failed:' + this.failed + '/' + this.total); } return this; } reset() { this.constructor(); return this; } } tests = new SimpleTest; Meteor.methods({ runTests: function() { tests.showResults(); }, });
class SimpleTest { constructor() { this.passed = 0; this.failed = 0; this.total = 0; } assert(condition, label = 'Unknown') { this.total++; if (!condition) { this.failed++; console.error('Test failed: ' + label); } else { this.passed++; } return this; } showResults() { if (this.passed === this.total) { console.log('All tests passed. (' + this.total + ')'); } else { console.log('Passed:' + this.passed + '/' + this.total); console.log('Failed:' + this.failed + '/' + this.total); } return this; } reset() { this.constructor(); return this; } } tests = new SimpleTest; Meteor.methods({ runTests: function() { tests.showResults(); }, });
Fix incompatibility with recent factory_boy postgeneration.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import factory from django.contrib.auth.models import User, Group from django.contrib.auth.hashers import make_password class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): if not create: return return make_password('password') @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import factory from django.contrib.auth.models import User, Group class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = User @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
Add new release task w/ API doc prebuilding
from os.path import join from shutil import rmtree, move from invoke import Collection, ctask as task from invocations import docs as _docs from invocations.packaging import publish d = 'sites' # Usage doc/API site (published as docs.paramiko.org) docs_path = join(d, 'docs') docs_build = join(docs_path, '_build') docs = Collection.from_module(_docs, name='docs', config={ 'sphinx.source': docs_path, 'sphinx.target': docs_build, }) # Main/about/changelog site ((www.)?paramiko.org) www_path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ 'sphinx.source': www_path, 'sphinx.target': join(www_path, '_build'), }) # Until we move to spec-based testing @task def test(ctx): ctx.run("python test.py --verbose") @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") # Until we stop bundling docs w/ releases. Need to discover use cases first. @task('docs') # Will invoke the API doc site build def release(ctx): # Move the built docs into where Epydocs used to live rmtree('docs') move(docs_build, 'docs') # Publish publish(ctx) ns = Collection(test, coverage, release, docs=docs, www=www)
from os.path import join from invoke import Collection, ctask as task from invocations import docs as _docs d = 'sites' # Usage doc/API site (published as docs.paramiko.org) path = join(d, 'docs') docs = Collection.from_module(_docs, name='docs', config={ 'sphinx.source': path, 'sphinx.target': join(path, '_build'), }) # Main/about/changelog site ((www.)?paramiko.org) path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ 'sphinx.source': path, 'sphinx.target': join(path, '_build'), }) # Until we move to spec-based testing @task def test(ctx): ctx.run("python test.py --verbose") @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") ns = Collection(test, coverage, docs=docs, www=www)
Fix ongov customs settings formatting.
''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":[ "id", "verifiableOrgId", "doingBusinessAsId", "locationTypeId", "municipality", "province" ] } } }
''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":{ "id", "verifiableOrgId", "doingBusinessAsId", "locationTypeId", "municipality", "province" } } } }
Allow _ in service and project ids We use dash to nest projects (infra-internal), so it cannot be used for word separation (depot_tools). R=vadimsh@chromium.org BUG= Review URL: https://codereview.chromium.org/1185823003.
# Copyright 2015 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. import re ################################################################################ ## Config set patterns. SERVICE_ID_PATTERN = '[a-z0-9\-_]+' SERVICE_ID_RGX = re.compile('^%s$' % SERVICE_ID_PATTERN) SERVICE_CONFIG_SET_RGX = re.compile('^services/(%s)$' % SERVICE_ID_PATTERN) PROJECT_ID_PATTERN = SERVICE_ID_PATTERN PROJECT_ID_RGX = re.compile('^%s$' % PROJECT_ID_PATTERN) PROJECT_CONFIG_SET_RGX = re.compile('^projects/(%s)$' % PROJECT_ID_PATTERN) REF_CONFIG_SET_RGX = re.compile( '^projects/(%s)/refs/.+$' % PROJECT_ID_PATTERN) ################################################################################ ## Known config file names. # luci-config configs. PROJECT_REGISTRY_FILENAME = 'projects.cfg' ACL_FILENAME = 'acl.cfg' # Project configs. PROJECT_METADATA_FILENAME = 'project.cfg' REFS_FILENAME = 'refs.cfg'
# Copyright 2015 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. import re ################################################################################ ## Config set patterns. SERVICE_ID_PATTERN = '[a-z0-9\-]+' SERVICE_ID_RGX = re.compile('^%s$' % SERVICE_ID_PATTERN) SERVICE_CONFIG_SET_RGX = re.compile('^services/(%s)$' % SERVICE_ID_PATTERN) PROJECT_ID_PATTERN = SERVICE_ID_PATTERN PROJECT_ID_RGX = re.compile('^%s$' % PROJECT_ID_PATTERN) PROJECT_CONFIG_SET_RGX = re.compile('^projects/(%s)$' % PROJECT_ID_PATTERN) REF_CONFIG_SET_RGX = re.compile( '^projects/(%s)/refs/.+$' % PROJECT_ID_PATTERN) ################################################################################ ## Known config file names. # luci-config configs. PROJECT_REGISTRY_FILENAME = 'projects.cfg' ACL_FILENAME = 'acl.cfg' # Project configs. PROJECT_METADATA_FILENAME = 'project.cfg' REFS_FILENAME = 'refs.cfg'
Update ansible version number to 2.8.0.dev0
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type __version__ = '2.8.0.dev0' __author__ = 'Ansible, Inc.' __codename__ = 'TBD'
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type __version__ = '2.7.0.a1.post0' __author__ = 'Ansible, Inc.' __codename__ = 'In the Light'
Delete project reminder on backend When a reminder is deleted on the front-end ensure that it is also deleted on the backend.
class MCProjectHomeRemindersComponentController { /*@ngInject*/ constructor(projectsAPI) { this.projectsAPI = projectsAPI; } removeReminder(index) { this.project.reminders.splice(index, 1); this.projectsAPI.updateProject(this.project.id, {reminders: this.project.reminders}); } addReminder() { this.project.reminders.push({note: '', status: 'none'}); } updateReminders() { this.projectsAPI.updateProject(this.project.id, {reminders: this.project.reminders}); } } angular.module('materialscommons').component('mcProjectHomeReminders', { templateUrl: 'app/project/home/mc-project-home-reminders.html', controller: MCProjectHomeRemindersComponentController, bindings: { project: '<' } });
class MCProjectHomeRemindersComponentController { /*@ngInject*/ constructor(projectsAPI) { this.projectsAPI = projectsAPI; } removeReminder(index) { this.project.reminders.splice(index, 1); } addReminder() { this.project.reminders.push({note: '', status: 'none'}); } updateReminders() { this.projectsAPI.updateProject(this.project.id, {reminders: this.project.reminders}); } } angular.module('materialscommons').component('mcProjectHomeReminders', { templateUrl: 'app/project/home/mc-project-home-reminders.html', controller: MCProjectHomeRemindersComponentController, bindings: { project: '<' } });
Create a closure for click handlers in a loop
var d = new Discovery(); var controller; $("button#discovery").bind("click", function(e){ d.start(function(data) { $("output .progress").append(data.host).append("<br/>"); controller = new NetiaController(data.host, data.port); fillActions($("output .controller"), controller); }); }) $("button#custom_controller").bind("click", function(e){ var host = $("input#host").val(); var port = $("input#port").val(); controller = new NetiaController(host, port); $("output .progress").append(host + ":" + port).append("<br/>"); fillActions($("output .controller"), controller); }) var fillActions = function(div, controller) { var that = this; div.empty(); for (var action in controller) { if (action.indexOf("sendKey") == 0 ) { div.append('<button id="' + action + '">' + action + '</button>'); div.find("button#"+action).bind("click", getActionClickHandler(action)) } } } var getActionClickHandler = function (action) { return function () { controller[action]() } }
var d = new Discovery(); var controller; $("button#discovery").bind("click", function(e){ d.start(function(data) { $("output .progress").append(data.host).append("<br/>"); controller = new NetiaController(data.host, data.port); fillActions($("output .controller"), controller); }); }) $("button#custom_controller").bind("click", function(e){ var host = $("input#host").val(); var port = $("input#port").val(); controller = new NetiaController(host, port); $("output .progress").append(host + ":" + port).append("<br/>"); fillActions($("output .controller"), controller); }) var fillActions = function(div, controller) { var that = this; div.empty(); document.getElementsByClassName("controller")[0].onclick = function(e) { that.controller[e.srcElement.getAttribute('id')](); }; for (var action in controller) { if (action.indexOf("sendKey") == 0 ) { div.append('<button id="' + action + '">' + action + '</button>'); //TODO: why this is not working ??? ask guru, hm ... grze do you know ? //div.find("button#"+action).bind("click", function(e) { controller[action](); }) } } }
Move `||` at the beginning of lines to end of previous line
<?php declare (strict_types = 1); \Jentil()->utilities->loader->loadPartial('header'); if (!\Jentil()->utilities->page->is('singular')) { if (($jentil_title = \Jentil()->utilities->page->title->themeMod()->get()) || \Jentil()->utilities->page->is('customize_preview') ) { ?> <header class="page-header"> <?php \do_action('jentil_before_title'); ?> <h1 class="page-title" itemprop="name mainEntityOfPage"><?php echo $jentil_title; ?></h1> <?php \do_action('jentil_after_title'); ?> </header> <?php } } /** * Prevent calls to `global $jentil_title`. */ unset($jentil_title); \do_action('jentil_before_content'); if (\Jentil()->utilities->page->is('404') || !($jentil_posts = \Jentil()->utilities->page->posts->render()) ) { \Jentil()->utilities->loader->loadPartial('none'); } else { echo $jentil_posts; } /** * Prevent calls to `global $jentil_posts`. */ unset($jentil_posts); \do_action('jentil_after_content'); \Jentil()->utilities->loader->loadPartial('footer');
<?php declare (strict_types = 1); \Jentil()->utilities->loader->loadPartial('header'); if (!\Jentil()->utilities->page->is('singular')) { if (($jentil_title = \Jentil()->utilities->page->title->themeMod()->get()) || \Jentil()->utilities->page->is('customize_preview') ) { ?> <header class="page-header"> <?php \do_action('jentil_before_title'); ?> <h1 class="page-title" itemprop="name mainEntityOfPage"><?php echo $jentil_title; ?></h1> <?php \do_action('jentil_after_title'); ?> </header> <?php } } /** * Prevent calls to `global $jentil_title`. */ unset($jentil_title); \do_action('jentil_before_content'); if (\Jentil()->utilities->page->is('404') || !($jentil_posts = \Jentil()->utilities->page->posts->render()) ) { \Jentil()->utilities->loader->loadPartial('none'); } else { echo $jentil_posts; } /** * Prevent calls to `global $jentil_posts`. */ unset($jentil_posts); \do_action('jentil_after_content'); \Jentil()->utilities->loader->loadPartial('footer');
Fix incorrect login after confirming token
<?php namespace Flarum\Core\Handlers\Commands; use Flarum\Core\Repositories\UserRepositoryInterface as UserRepository; use Flarum\Core\Events\UserWillBeSaved; use Flarum\Core\Support\DispatchesEvents; use Flarum\Core\Exceptions\InvalidConfirmationTokenException; use Flarum\Core\Models\EmailToken; class ConfirmEmailCommandHandler { use DispatchesEvents; protected $users; public function __construct(UserRepository $users) { $this->users = $users; } public function handle($command) { $token = EmailToken::find($command->token); if (! $token) { throw new InvalidConfirmationTokenException; } $user = $token->user; $user->changeEmail($token->email); if (! $user->is_activated) { $user->activate(); } event(new UserWillBeSaved($user, $command)); $user->save(); $this->dispatchEventsFor($user); $token->delete(); return $user; } }
<?php namespace Flarum\Core\Handlers\Commands; use Flarum\Core\Repositories\UserRepositoryInterface as UserRepository; use Flarum\Core\Events\UserWillBeSaved; use Flarum\Core\Support\DispatchesEvents; use Flarum\Core\Exceptions\InvalidConfirmationTokenException; use Flarum\Core\Models\EmailToken; class ConfirmEmailCommandHandler { use DispatchesEvents; protected $users; public function __construct(UserRepository $users) { $this->users = $users; } public function handle($command) { $token = EmailToken::find($command->token)->first(); if (! $token) { throw new InvalidConfirmationTokenException; } $user = $token->user; $user->changeEmail($token->email); if (! $user->is_activated) { $user->activate(); } event(new UserWillBeSaved($user, $command)); $user->save(); $this->dispatchEventsFor($user); $token->delete(); return $user; } }
Set charset in DSN string
<?php /** * This file is part of the Krystal Framework * * Copyright (c) No Global State Lab * * For the full copyright and license information, please view * the license file that was distributed with this source code. */ namespace Krystal\Db\Sql\Connector; use PDO; final class MySQL implements ConnectorInterface { /** * {@inheritDoc} */ public function getArgs(array $config) { $dsn = 'mysql:host='.$config['host']; if (isset($config['dbname'])) { $dsn .= ';dbname='.$config['dbname']; } $dsn .= ';charset=utf8'; return array($dsn, $config['username'], $config['password'], array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => true, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Disable STRICT mode PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' )); } }
<?php /** * This file is part of the Krystal Framework * * Copyright (c) No Global State Lab * * For the full copyright and license information, please view * the license file that was distributed with this source code. */ namespace Krystal\Db\Sql\Connector; use PDO; final class MySQL implements ConnectorInterface { /** * {@inheritDoc} */ public function getArgs(array $config) { $dsn = 'mysql:host='.$config['host']; if (isset($config['dbname'])) { $dsn .= ';dbname='.$config['dbname']; } return array($dsn, $config['username'], $config['password'], array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8', PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => true, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Disable STRICT mode PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' )); } }
Fix impl of the phase handler interfaces
package main import ( "fmt" "log" "github.com/ghthor/engine/rpg2d" "github.com/ghthor/engine/rpg2d/quad" "github.com/ghthor/engine/sim/stime" ) type inputPhase struct{} type narrowPhase struct{} func (inputPhase) ApplyInputsIn(c quad.Chunk, now stime.Time) quad.Chunk { for _, e := range c.Entities { switch a := e.(type) { case actor: input := a.ReadInput() fmt.Println(input) // Naively apply input to actor } } return c } func (narrowPhase) ResolveCollisions(c quad.Chunk, now stime.Time) quad.Chunk { return c } func main() { simDef := rpg2d.SimulationDef{ FPS: 40, InputPhaseHandler: inputPhase{}, NarrowPhaseHandler: narrowPhase{}, } _, err := simDef.Begin() if err != nil { log.Fatal(err) } }
package main import ( "fmt" "log" "github.com/ghthor/engine/rpg2d" "github.com/ghthor/engine/rpg2d/quad" ) type inputPhase struct{} type narrowPhase struct{} func (inputPhase) ApplyInputsIn(c quad.Chunk) quad.Chunk { for _, e := range c.Entities { switch a := e.(type) { case actor: input := a.ReadInput() fmt.Println(input) // Naively apply input to actor } } return c } func (narrowPhase) ResolveCollisions(c quad.Chunk) quad.Chunk { return c } func main() { simDef := rpg2d.SimulationDef{ FPS: 40, InputPhaseHandler: inputPhase{}, NarrowPhaseHandler: narrowPhase{}, } _, err := simDef.Begin() if err != nil { log.Fatal(err) } }
Startup: Make test room shorter for ease of testing
import sge from . import config from . import game from . import player from . import rooms def initialize(config): """Load assets and initialize the game objects""" sge.game = game.Game( width=config.GAME_WINDOW_WIDTH, height=config.GAME_WINDOW_HEIGHT, fps=config.GAME_FPS, window_text=config.GAME_WINDOW_TITLE) player_obj = player.Player( config.PLAYER_SPRITES, sge.game.width / 2, sge.game.height / 2) sge.game.start_room = rooms.ScrollableLevel( player=player_obj, width=2000, ruler=True) sge.game.mouse_visible = False def run(): """Start the game running""" sge.game.start() if __name__ == '__main__': initialize(config) run()
import sge from . import config from . import game from . import player from . import rooms def initialize(config): """Load assets and initialize the game objects""" sge.game = game.Game( width=config.GAME_WINDOW_WIDTH, height=config.GAME_WINDOW_HEIGHT, fps=config.GAME_FPS, window_text=config.GAME_WINDOW_TITLE) player_obj = player.Player( config.PLAYER_SPRITES, sge.game.width / 2, sge.game.height / 2) sge.game.start_room = rooms.ScrollableLevel( player=player_obj, width=10000, ruler=True) sge.game.mouse_visible = False def run(): """Start the game running""" sge.game.start() if __name__ == '__main__': initialize(config) run()
Add example to escapeURI function.
/** * Escape URI components utility. * * Site Kit by Google, 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. */ /** * Escapes URI components in a template string as a tag function. * * @example * // escape redirect url * const redirectTo = 'http://localhost/admin/'; * const loginUrl = escapeURI`http://localhost/login?redirect=${ redirectTo }`; * * @since n.e.x.t * * @param {string[]} strings The array of static strings in the template. * @param {...*} values The array of expressions used in the template. * @return {string} Escaped URI string. */ export function escapeURI( strings, ...values ) { return strings.reduce( ( acc, string, idx ) => { return acc + string + encodeURIComponent( values[ idx ] || '' ); }, '' ); }
/** * Escape URI components utility. * * Site Kit by Google, 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. */ /** * Escapes URI components in a template string as a tag function. * * @since n.e.x.t * * @param {string[]} strings The array of static strings in the template. * @param {...*} values The array of expressions used in the template. * @return {string} Escaped URI string. */ export function escapeURI( strings, ...values ) { return strings.reduce( ( acc, string, idx ) => { return acc + string + encodeURIComponent( values[ idx ] || '' ); }, '' ); }
Remove slash from asset paths.
var ready = function(fn) { if (document.readyState != 'loading') { fn(); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fn); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState != 'loading') fn(); }); } } ready(function() { LazyLoad.css('https://fonts.googleapis.com/css?family=Raleway:400,700'); LazyLoad.js('https://cdnjs.cloudflare.com/ajax/libs/blazy/1.6.2/blazy.min.js', function() { new Blazy({ offset: 500, }); }); LazyLoad.css('dist/extended.css'); LazyLoad.js('https://cdnjs.cloudflare.com/ajax/libs/feature.js/1.0.1/feature.min.js', function() { if (feature.cssTransform && feature.cssTransition && feature.viewportUnit) { LazyLoad.css('dist/full.css'); } }); });
var ready = function(fn) { if (document.readyState != 'loading') { fn(); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fn); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState != 'loading') fn(); }); } } ready(function() { LazyLoad.css('https://fonts.googleapis.com/css?family=Raleway:400,700'); LazyLoad.js('https://cdnjs.cloudflare.com/ajax/libs/blazy/1.6.2/blazy.min.js', function() { new Blazy({ offset: 500, }); }); LazyLoad.css('/dist/extended.css'); LazyLoad.js('https://cdnjs.cloudflare.com/ajax/libs/feature.js/1.0.1/feature.min.js', function() { if (feature.cssTransform && feature.cssTransition && feature.viewportUnit) { LazyLoad.css('/dist/full.css'); } }); });
Copy space separeted title and url to clipboard
function copyToClipboard(str){ 'use strict'; // Copy str to clipboard var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = str; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); } window.addEventListener('load', function(){ 'use strict'; // Get elements var title = document.getElementById('page_title'); var url = document.getElementById('page_url'); var copyTitle = document.getElementById('copy_title'); var copyUrl = document.getElementById('copy_url'); var copyAll = document.getElementById('copy_all'); // Get tab info chrome.tabs.query({ active: true }, function(tabs){ 'use strict'; // Show title and url title.innerHTML = tabs[0].title; url.innerHTML = tabs[0].url; // Add click listener to copy button copyTitle.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].title); }); copyUrl.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].url); }); copyAll.addEventListener('click', function(){ 'use strict'; copyToClipboard(tabs[0].title + ' ' + tabs[0].url); }); }); });
function copyToClipboard(str){ 'use strict'; // Copy str to clipboard var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = str; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); } window.addEventListener('load', function(){ 'use strict'; // Get elements var title = document.getElementById('page_title'); var url = document.getElementById('page_url'); var copyTitle = document.getElementById('copy_title'); var copyUrl = document.getElementById('copy_url'); // Get tab info chrome.tabs.query({ active: true }, function(tabs){ 'use strict'; // Show title and url title.innerHTML = tabs[0].title; url.innerHTML = tabs[0].url; // Add click listener to copy button copyTitle.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].title); }); copyUrl.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].url); }); }); });
Bump version to 0.1.post1 to re-release on PyPi correctly packaged
#!/usr/bin/env python # # The Template-Python distribution is Copyright (C) Sean McAfee 2007-2008, # derived from the Perl Template Toolkit Copyright (C) 1996-2007 Andy # Wardley. All Rights Reserved. # # The file "LICENSE" at the top level of this source distribution describes # the terms under which this file may be distributed. # from distutils.core import setup setup(name = 'Template-Python', version = '0.1.post1', description = 'Python port of the Template Toolkit', author = 'Sean McAfee', author_email = 'eefacm@gmail.com', url = 'http://template-toolkit.org/python/', packages = ['template', 'template.plugin', 'template.namespace'], package_dir = { 'template.plugin': 'template/plugin', 'template.namespace': 'template/namespace' }, )
#!/usr/bin/env python # # The Template-Python distribution is Copyright (C) Sean McAfee 2007-2008, # derived from the Perl Template Toolkit Copyright (C) 1996-2007 Andy # Wardley. All Rights Reserved. # # The file "LICENSE" at the top level of this source distribution describes # the terms under which this file may be distributed. # from distutils.core import setup setup(name = 'Template-Python', version = '0.1', description = 'Python port of the Template Toolkit', author = 'Sean McAfee', author_email = 'eefacm@gmail.com', url = 'http://template-toolkit.org/python/', packages = ['template', 'template.plugin', 'template.namespace'], package_dir = { 'template.plugin': 'template/plugin', 'template.namespace': 'template/namespace' }, )
Add data base root commands
/** * Created by Eduardo veras on 19-Jun-16. * Edited by Siclait on 19-Juu-16 */ import Entity.*; import Service.*; import java.util.List; public class DatabaseManager { // Singleton Constructor private DatabaseManager(){ } public static void BootDataBase(){ List<User> users = UserORMService.GetInstance().FindAll(); if(users.size() == 0) { System.out.println("\n\nCreating Admins ..."); UserORMService.GetInstance().Create(new User("admin", "Administrator", "The", "admin", true)); UserORMService.GetInstance().Create(new User("Wardo", "Eduardo", "Veras", "1234", true)); UserORMService.GetInstance().Create(new User("EmmJ", "Emmanuel", "Jaquez", "1234", true)); UserORMService.GetInstance().Create(new User("Djsiclait", "Djidjelly", "Siclait", "1234", true)); System.out.println("Admins created successfully!\n"); } else System.out.println("\n\nDatabase already created!\n"); } // Database Commands public static boolean CheckUserCredentials(String option){ return false; } public static void MakeAdmin(){ } }
/** * Created by Eduardo veras on 19-Jun-16. * Edited by Siclait on 19-Juu-16 */ import Entity.*; import Service.*; import java.util.List; public class DatabaseManager { // Singleton Constructor private DatabaseManager(){ } public static void BootDataBase(){ List<User> users = UserORMService.GetInstance().FindAll(); if(users.size() == 0) { System.out.println("\n\nCreating Admins ..."); UserORMService.GetInstance().Create(new User("admin", "Administrator", "The", "admin", true)); UserORMService.GetInstance().Create(new User("Wardo", "Eduardo", "Veras", "1234", true)); UserORMService.GetInstance().Create(new User("EmmJ", "Emmanuel", "Jaquez", "1234", true)); UserORMService.GetInstance().Create(new User("Djsiclait", "Djidjelly", "Siclait", "1234", true)); System.out.println("Admins created successfully!\n"); } else System.out.println("\n\nDatabase already created!\n"); } }
Update how we set the connection information for MongoDB to support Mongo 3.0.5 Signed-off-by: Robert Dempsey <715b5a941e732be1613fdd9d94dfd8e50c02b187@gmail.com>
# -*- coding: utf-8 -*- from flask import Flask, render_template from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface import configparser from .momentjs import momentjs app = Flask(__name__) # Security WTF_CSRF_ENABLED = True app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR' app.jinja_env.globals['momentjs'] = momentjs # App Config config = configparser.ConfigParser() config.read('config/config.ini') app.config['MONGODB_DB_SETTINGS'] = { 'name': config['MongoDB']['db_name'], 'host': config['MongoDB']['host'], 'port': int(config['MongoDB']['port']), 'username': config['MongoDB']['username'], 'password': config['MongoDB']['password']} db = MongoEngine(app) def register_blueprints(app): # Prevents circular imports from weighttracker.views.measurement_views import measurements app.register_blueprint(measurements) from weighttracker.views.inspiration_views import inspirations app.register_blueprint(inspirations) from weighttracker.views.foodjournal_views import foodjournals app.register_blueprint(foodjournals) register_blueprints(app) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template('index.html') if __name__ == '__main__': app.run()
# -*- coding: utf-8 -*- from flask import Flask, render_template from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface import configparser from .momentjs import momentjs app = Flask(__name__) # Security WTF_CSRF_ENABLED = True app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR' app.jinja_env.globals['momentjs'] = momentjs # App Config config = configparser.ConfigParser() config.read('config/config.ini') app.config['MONGODB_DB'] = config['MongoDB']['db_name'] app.config['MONGODB_HOST'] = config['MongoDB']['host'] app.config['MONGODB_PORT'] = int(config['MongoDB']['port']) app.config['MONGODB_USERNAME'] = config['MongoDB']['username'] app.config['MONGODB_PASSWORD'] = config['MongoDB']['password'] db = MongoEngine(app) def register_blueprints(app): # Prevents circular imports from weighttracker.views.measurement_views import measurements app.register_blueprint(measurements) from weighttracker.views.inspiration_views import inspirations app.register_blueprint(inspirations) from weighttracker.views.foodjournal_views import foodjournals app.register_blueprint(foodjournals) register_blueprints(app) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template('index.html') if __name__ == '__main__': app.run()
Insert new sections into collection.
Template.addSection.events({ 'click #add-section-button': function (event, template) { /* / Add new section to the course */ // Get current sections, before adding new section if (this.sections) { // If sections exists, use them var sections = this.sections; } else { // otherwise create empty sections array var sections = []; } // Get the title of new section var title = template.find('#section-title').value; // Set section title in new section object var newSection = {'title': title}; // Insert new section into database var newSectionID = Sections.insert(newSection); // Add section ID to existing sections sections.push(newSectionID); // Update the course with new section Courses.update(this._id, {$set: {'sections': sections}}); // Reset the value of section title field $("#section-title").val(""); } });
Template.addSection.events({ 'click #add-section-button': function (event, template) { /* / Add new section to the course */ // Get current sections, before adding new section if (this.sections) { // If sections exists, use them var sections = this.sections; } else { // otherwise create empty sections array var sections = []; } // Get the title of new section var title = template.find('#section-title').value; // Set section title in new section object var newSection = {'title': title}; // Add section to end of existing sections sections.push(newSection); // Update the course with new section Courses.update(this._id, {$set: {'sections': sections}}); // Reset the value of section title field $("#section-title").val(""); } });
Set DB's Error if get any validation error
package validations import ( "errors" "fmt" "github.com/jinzhu/gorm" ) var settingKey = "validations:errors" func AddError(db *gorm.DB, resource interface{}, err string) { var validationErrors = GetErrors(db) var scope = db.NewScope(resource) key := fmt.Sprintf("%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue()) validationErrors[key] = append(validationErrors[key], err) db.InstantSet(settingKey, validationErrors).Error = errors.New(err) } func AddErrorForColumn(db *gorm.DB, resource interface{}, column, err string) { var validationErrors = GetErrors(db) var scope = db.NewScope(resource) key := fmt.Sprintf("%v_%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue(), column) validationErrors[key] = append(validationErrors[key], err) db.InstantSet(settingKey, validationErrors).Error = errors.New(err) } func GetErrors(db *gorm.DB) map[string][]string { var validationErrors = map[string][]string{} if errors, ok := db.Get(settingKey); ok { validationErrors = errors.(map[string][]string) } return validationErrors }
package validations import ( "fmt" "github.com/jinzhu/gorm" ) var settingKey = "validations:errors" func AddError(db *gorm.DB, resource interface{}, err string) { var errors = GetErrors(db) var scope = db.NewScope(resource) key := fmt.Sprintf("%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue()) errors[key] = append(errors[key], err) db.InstantSet(settingKey, errors) } func AddErrorForColumn(db *gorm.DB, resource interface{}, column, err string) { var errors = GetErrors(db) var scope = db.NewScope(resource) key := fmt.Sprintf("%v_%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue(), column) errors[key] = append(errors[key], err) db.InstantSet(settingKey, errors) } func GetErrors(db *gorm.DB) map[string][]string { var errors = map[string][]string{} if e, ok := db.Get(settingKey); ok { errors = e.(map[string][]string) } return errors }
Change the generated markup so that attribute names are properly marked.
# Lame substitute for a fine script to generate the table from ast.txt from compiler import astgen AST_DEF = '../compiler/ast.txt' def sort(l): l = l[:] l.sort(lambda a, b: cmp(a.name, b.name)) return l def main(): nodes = astgen.parse_spec(AST_DEF) print "\\begin{longtableiii}{lll}{class}{Node type}{Attribute}{Value}" print for node in sort(nodes): if node.argnames: print "\\lineiii{%s}{%s}{}" % (node.name, node.argnames[0]) else: print "\\lineiii{%s}{}{}" % node.name for arg in node.argnames[1:]: print "\\lineiii{}{\\member{%s}}{}" % arg print "\\hline", "\n" print "\\end{longtableiii}" if __name__ == "__main__": main()
# Lame substitute for a fine script to generate the table from ast.txt from compiler import astgen AST_DEF = '../compiler/ast.txt' def sort(l): l = l[:] l.sort(lambda a, b: cmp(a.name, b.name)) return l def main(): nodes = astgen.parse_spec(AST_DEF) print "\\begin{longtableiii}{lll}{class}{Node type}{Attribute}{Value}" print for node in sort(nodes): if node.argnames: print "\\lineiii{%s}{%s}{}" % (node.name, node.argnames[0]) else: print "\\lineiii{%s}{}{}" % node.name for arg in node.argnames[1:]: print "\\lineiii{}{%s}{}" % arg print "\\hline", "\n" print "\\end{longtableiii}" if __name__ == "__main__": main()
Improve logging for unknown/empty messages
/* * Copyright 2016 higherfrequencytrading.com * * 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 net.openhft.chronicle.queue; import net.openhft.chronicle.wire.MessageHistory; /** * Created by peter on 27/03/16. */ public enum NoMessageHistory implements MessageHistory { INSTANCE; @Override public int timings() { return 0; } @Override public long timing(int n) { return -1; } @Override public int sources() { return 0; } @Override public int sourceId(int n) { return -1; } @Override public long sourceIndex(int n) { return -1; } @Override public void reset(int sourceId, long sourceIndex) { // ignored } @Override public int lastSourceId() { return -1; } @Override public long lastSourceIndex() { return -1; } }
/* * Copyright 2016 higherfrequencytrading.com * * 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 net.openhft.chronicle.queue; import net.openhft.chronicle.wire.MessageHistory; /** * Created by peter on 27/03/16. */ public enum NoMessageHistory implements MessageHistory { INSTANCE; @Override public int timings() { return 0; } @Override public long timing(int n) { return -1; } @Override public int sources() { return 0; } @Override public int sourceId(int n) { return -1; } @Override public long sourceIndex(int n) { return -1; } @Override public void reset(int sourceId, long sourceIndex) { // ignored } }
Add default FS root to new FS objects
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var DirectoryEntry = require('./DirectoryEntry'); /** * An interface representing a file system * * @constructor * {DOMString} name the unique name of the file system (readonly) * {DirectoryEntry} root directory of the file system (readonly) */ var FileSystem = function(name, root) { this.name = name || null; if (root) { this.root = new DirectoryEntry(root.name, root.fullPath, this); } else { this.root = new DirectoryEntry(this.name, '/', this); } }; FileSystem.prototype.__format__ = function(fullPath) { return fullPath; }; module.exports = FileSystem;
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var DirectoryEntry = require('./DirectoryEntry'); /** * An interface representing a file system * * @constructor * {DOMString} name the unique name of the file system (readonly) * {DirectoryEntry} root directory of the file system (readonly) */ var FileSystem = function(name, root) { this.name = name || null; if (root) { this.root = new DirectoryEntry(root.name, root.fullPath, this); } }; FileSystem.prototype.__format__ = function(fullPath) { return fullPath; }; module.exports = FileSystem;
Update fields helper to use relative keystone path - @morenoh149
var fs = require('fs'), keystone = require('../index'); exports.init = function (shouldRunTests) { keystone.init(); var typesLoc = __dirname + '/../fields/types'; var types = fs.readdirSync(typesLoc); types.forEach(function(name) { var serverTestLoc = typesLoc + '/' + name + '/test/server.js'; if (!fs.existsSync(serverTestLoc)) return; console.log(keystone.mongoose); var List = keystone.List(name + "Test", { nocreate: true }); var test = require(serverTestLoc); if (test.initList) { test.initList(List); } List.register(); if (shouldRunTests && test.testFieldType) { describe(name, function () { test.testFieldType(List); }); } }); };
var fs = require('fs'), keystone = require('keystone'); exports.init = function (shouldRunTests) { keystone.init(); var typesLoc = __dirname + '/../fields/types'; var types = fs.readdirSync(typesLoc); types.forEach(function(name) { var serverTestLoc = typesLoc + '/' + name + '/test/server.js'; if (!fs.existsSync(serverTestLoc)) return; console.log(keystone.mongoose); var List = keystone.List(name + "Test", { nocreate: true }); var test = require(serverTestLoc); if (test.initList) { test.initList(List); } List.register(); if (shouldRunTests && test.testFieldType) { describe(name, function () { test.testFieldType(List); }); } }); };
Use yaml for file format...
package config import ( "io/ioutil" "gopkg.in/yaml.v2" ) type Config struct { ConfigFile string Paths map[string]string } func (c *Config) readConfig() error { c.Paths = make(map[string]string) content, err := ioutil.ReadFile(c.ConfigFile) if err != nil { return err } m := make(map[interface{}]interface{}) err = yaml.Unmarshal(content, &m) if err != nil { return err } for k, v := range m { c.Paths[k.(string)] = v.(string) } return nil } func (c *Config) WriteConfig() error { content, err := yaml.Marshal(&(c.Paths)) if err != nil { return err } err = ioutil.WriteFile(c.ConfigFile, content, 0644) if err != nil { return err } return nil } func NewConfig(filename string) (*Config, error) { c := Config{ConfigFile: filename} if err := c.readConfig(); err == nil { return &c, nil } else { return nil, err } }
package config import ( "bufio" "fmt" "os" "strings" ) type Config struct { ConfigFile string Paths map[string]string } func (c *Config) readConfig() error { c.Paths = make(map[string]string) file, err := os.Open(c.ConfigFile) defer file.Close() if err == nil { scanner := bufio.NewScanner(file) for scanner.Scan() { s := scanner.Text() ss := strings.Split(s, "|") c.Paths[strings.Trim(ss[0], " \t")] = strings.Trim(ss[1], " \t") } return scanner.Err() } else { return err } } func (c *Config) WriteConfig() error { file, err := os.Create(c.ConfigFile) defer file.Close() if err != nil { return err } for k, v := range c.Paths { if _, err := file.WriteString(fmt.Sprintf("%s| %s\n", k, v)); err != nil { return err } } return nil } func NewConfig(filename string) (*Config, error) { c := Config{ConfigFile: filename} if err := c.readConfig(); err == nil { return &c, nil } else { return nil, err } }
Add return type to __toString()
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http\LoginLink; /** * @author Ryan Weaver <ryan@symfonycasts.com> */ class LoginLinkDetails { private $url; private $expiresAt; public function __construct(string $url, \DateTimeImmutable $expiresAt) { $this->url = $url; $this->expiresAt = $expiresAt; } public function getUrl(): string { return $this->url; } public function getExpiresAt(): \DateTimeImmutable { return $this->expiresAt; } public function __toString(): string { return $this->url; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http\LoginLink; /** * @author Ryan Weaver <ryan@symfonycasts.com> */ class LoginLinkDetails { private $url; private $expiresAt; public function __construct(string $url, \DateTimeImmutable $expiresAt) { $this->url = $url; $this->expiresAt = $expiresAt; } public function getUrl(): string { return $this->url; } public function getExpiresAt(): \DateTimeImmutable { return $this->expiresAt; } public function __toString() { return $this->url; } }
Change watcher to include the lib dir
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { RTCReceiver: { src: './RTCReceiver/main.js', dest: '../webservice/public/js/builds/RTCReceiver.js' }, RTCSender: { src: './RTCSender/main.js', dest: '../webservice/public/js/builds/RTCSender.js' } }, watch: { scripts: { files: ['RTC*/**/*.js', 'lib/*.js'], tasks: ['browserify'], options: { spawn: false, }, }, } }); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('brow', ['browserify']); grunt.registerTask('default', 'Log some stuff.', function() { var message = 'Tasks: \n'; message += "browserify: \n"; message += "\tRTCReceiver \n"; message += "\tRTCSender \n"; grunt.log.write(message).ok(); }); }
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { RTCReceiver: { src: './RTCReceiver/main.js', dest: '../webservice/public/js/builds/RTCReceiver.js' }, RTCSender: { src: './RTCSender/main.js', dest: '../webservice/public/js/builds/RTCSender.js' } }, watch: { scripts: { files: ['RTC*/**/*.js'], tasks: ['browserify'], options: { spawn: false, }, }, } }); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('brow', ['browserify']); grunt.registerTask('default', 'Log some stuff.', function() { var message = 'Tasks: \n'; message += "browserify: \n"; message += "\tRTCReceiver \n"; message += "\tRTCSender \n"; grunt.log.write(message).ok(); }); }
Remove duplicate Flask-Login session protection setting
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
chore(repl): Use process argv as inspection source
var UDF = require( '..' ) var BlockDevice = require( 'blockdevice' ) var util = require( 'util' ) var fs = require( 'fs' ) var path = require( 'path' ) var argv = process.argv.slice(2) function inspect( value ) { return util.inspect( value, { depth: null, colors: process.stdout.isTTY, }) } var EOL = '\n' console.log( EOL + 'UDF', inspect( UDF ) ) var imagePath = path.resolve( argv.shift() ) var stats = fs.statSync( imagePath ) console.log( EOL + 'stats', inspect( stats ) ) var device = new BlockDevice({ blockSize: 512, path: imagePath, size: stats.size, mode: 'r', }) var volume = new UDF.Volume( device ) device.open( function( error ) { if( error ) throw error volume.open( function( error, desc ) { console.log( '' ) // console.log( buffer ) console.log( desc ) console.log( '' ) console.log( error || inspect( volume ) ) }) })
var UDF = require( '..' ) var BlockDevice = require( 'blockdevice' ) var util = require( 'util' ) var fs = require( 'fs' ) var path = require( 'path' ) function inspect( value ) { return util.inspect( value, { depth: null, colors: process.stdout.isTTY, }) } var EOL = '\n' console.log( EOL + 'UDF', inspect( UDF ) ) var imagePath = path.join( process.env.HOME, 'Downloads', 'image.iso' ) var stats = fs.statSync( imagePath ) console.log( EOL + 'stats', inspect( stats ) ) var device = new BlockDevice({ blockSize: 512, path: imagePath, size: stats.size, mode: 'r', }) var volume = new UDF.Volume( device ) device.open( function( error ) { if( error ) throw error volume.open( function( error, desc ) { console.log( '' ) // console.log( buffer ) console.log( desc ) console.log( '' ) console.log( error || inspect( volume ) ) }) })
Tidy up upload response a bit
import os.path from flask import abort, request, jsonify, redirect, url_for from IATISimpleTester import app, db from IATISimpleTester.models import SuppliedData @app.route('/upload', methods=['GET', 'POST']) def upload(): source_url = request.args.get('source_url') file = request.files.get('file') raw_text = request.args.get('paste') form_name = None if source_url: form_name = 'url_form' elif raw_text: form_name = 'text_form' elif file: form_name = 'upload_form' if not form_name: return abort(404) data = SuppliedData(source_url, file, raw_text, form_name) db.session.add(data) db.session.commit() if request.args.get('output') == 'json': resp = {} resp['success'] = True resp['data'] = { 'id': data.id, 'original_file': data.original_file, } return jsonify(resp) return redirect(url_for('explore', uuid=data.id))
import os.path from flask import request, jsonify, redirect, url_for from IATISimpleTester import app, db from IATISimpleTester.models import SuppliedData @app.route('/upload', methods=['GET', 'POST']) def upload(): resp = {} source_url = request.args.get('source_url') file = request.files.get('file') raw_text = request.args.get('paste') form_name = None if source_url: form_name = 'url_form' elif raw_text: form_name = 'text_form' elif file: form_name = 'upload_form' if form_name: data = SuppliedData(source_url, file, raw_text, form_name) db.session.add(data) db.session.commit() resp['success'] = True resp['data'] = { 'id': data.id, 'original_file': data.original_file, } if request.args.get('output') == 'json': return jsonify(resp) return redirect(url_for('explore', uuid=data.id))
Stop forwarding flash by default, it breaks more than it doesn't. git-svn-id: 87d19257dd11500985d055ec4730e446075a5f07@1279 78c7df6f-8922-0410-bcd3-9426b1ad491b
# Copyright (c) 2006-2007 Open Source Applications Foundation # Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com> # # 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. import wsgi, convergence forwarding_conditions = [ lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url'], lambda e : 'mozilla.org/en-US/firefox/livebookmarks.html' not in e['reconstructed_url'], lambda e : e.get('CONTENT_TYPE') != 'application/x-shockwave-flash', ] def add_forward_condition(condition): forwarding_conditions.append(condition) def remove_forward_condition(condition): while condition in forwarding_conditions: forwarding_conditions.remove(condition)
# Copyright (c) 2006-2007 Open Source Applications Foundation # Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com> # # 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. import wsgi, convergence forwarding_conditions = [ lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url'], lambda e : 'mozilla.org/en-US/firefox/livebookmarks.html' not in e['reconstructed_url'], ] def add_forward_condition(condition): forwarding_conditions.append(condition) def remove_forward_condition(condition): while condition in forwarding_conditions: forwarding_conditions.remove(condition)
Use min version of jQuery
const path = require('path') const webpack = require('webpack') const pkg = require('./package') module.exports = { mode: 'production', entry: { main: [ path.resolve(__dirname, 'node_modules/jquery/dist/jquery.js'), path.resolve(__dirname, 'node_modules/css-modal/modal.js'), path.resolve(__dirname, 'src/js/transition.js'), path.resolve(__dirname, 'src/js/zoom.js'), path.resolve(__dirname, 'src/js/effects.js'), path.resolve(__dirname, 'src/js/form.js'), path.resolve(__dirname, 'src/js/toc.js'), path.resolve(__dirname, 'src/js/main.js'), path.resolve(__dirname, 'src/js/scroll-top.js'), path.resolve(__dirname, 'src/js/testimonial.js'), path.resolve(__dirname, 'src/js/track.js'), ], }, output: { path: path.resolve(__dirname, 'public/dist/', pkg.version), filename: `c.js` }, }
const path = require('path') const webpack = require('webpack') const pkg = require('./package') module.exports = { mode: 'production', entry: { main: [ path.resolve(__dirname, 'node_modules/jquery/dist/jquery.min.js'), path.resolve(__dirname, 'node_modules/css-modal/modal.js'), path.resolve(__dirname, 'src/js/transition.js'), path.resolve(__dirname, 'src/js/zoom.js'), path.resolve(__dirname, 'src/js/effects.js'), path.resolve(__dirname, 'src/js/form.js'), path.resolve(__dirname, 'src/js/toc.js'), path.resolve(__dirname, 'src/js/main.js'), path.resolve(__dirname, 'src/js/scroll-top.js'), path.resolve(__dirname, 'src/js/testimonial.js'), path.resolve(__dirname, 'src/js/track.js'), ], }, output: { path: path.resolve(__dirname, 'public/dist/', pkg.version), filename: `c.js` }, }
Move form creation to containers for new project
const React = require('react'); const ReactRedux = require('react-redux'); const ReduxForm = require('redux-form'); const selectors = require('@state/selectors'); const PropTypes = require('@root/prop-types'); const CreateProject = require('@components/new-project'); const { connect } = ReactRedux; const { reduxForm } = ReduxForm; const { orgByIdSelector } = selectors; const NewProjectForm = reduxForm({ form: 'create-project', destroyOnUnmount: false, forceUnregisterOnUnmount: true })(CreateProject); const NewProject = (props) => { const { org, push } = props; const onCancel = (values) => push(`/${org.id}/projects`); const onSubmit = (values) => push(`/${org.id}/new-project/billing`); return ( <NewProjectForm onCancel={onCancel} onSubmit={onSubmit} org={org} /> ); }; NewProject.propTypes = { org: PropTypes.org.isRequired, push: React.PropTypes.func }; // TODO we'll need to know whether there any cards // otherwise go to new billing straight away const mapStateToProps = (state, { match = { params: {} } }) => ({ org: orgByIdSelector(match.params.org)(state), router: state.app.router }); const mapDispatchToProps = (dispatch) => ({}); module.exports = connect( mapStateToProps, mapDispatchToProps )(NewProject);
const React = require('react'); const ReactRedux = require('react-redux'); const ReduxForm = require('redux-form'); const selectors = require('@state/selectors'); const selectors = require('@state/selectors'); const PropTypes = require('@root/prop-types'); const CreateProject = require('@components/new-project'); const { connect } = ReactRedux; const { reduxForm } = ReduxForm; const { orgByIdSelector } = selectors; const NewProjectForm = reduxForm({ form: 'create-project', destroyOnUnmount: false, forceUnregisterOnUnmount: true })(CreateProject); const NewProject = (props) => { const { org, push } = props; const onCancel = (values) => push(`/${org.id}/projects`); const onSubmit = (values) => push(`/${org.id}/new-project/billing`); return ( <NewProjectForm onCancel={onCancel} onSubmit={onSubmit} org={org} /> ); }; NewProject.propTypes = { org: PropTypes.org.isRequired, push: React.PropTypes.func }; // TODO we'll need to know whether there any cards // otherwise go to new billing straight away const mapStateToProps = (state, { match = { params: {} } }) => ({ org: orgByIdSelector(match.params.org)(state), router: state.app.router }); const mapDispatchToProps = (dispatch) => ({}); module.exports = connect( mapStateToProps, mapDispatchToProps )(NewProject);
Use DefaultRouter which includes a default API root view.
from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from rest_framework.authtoken.views import obtain_auth_token from grd import views router = routers.DefaultRouter() router.register(r'devices', views.DeviceView) urlpatterns = [ # Examples: # url(r'^$', 'ereuse.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include(router.urls)),#, namespace='api')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', obtain_auth_token), url(r'^api/register/$', views.Register.as_view(), name='do-register'), url(r'^api/devices/(?P<pk>[^/.]+)/log/$', views.DeviceLog.as_view({'get': 'list'}), name='device-log'), ]
from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from rest_framework.authtoken.views import obtain_auth_token from grd import views router = routers.SimpleRouter() router.register(r'devices', views.DeviceView) urlpatterns = [ # Examples: # url(r'^$', 'ereuse.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include(router.urls)),#, namespace='api')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', obtain_auth_token), url(r'^api/register/$', views.Register.as_view(), name='do-register'), url(r'^api/devices/(?P<pk>[^/.]+)/log/$', views.DeviceLog.as_view({'get': 'list'}), name='device-log'), ]
Add docstrings to view classes
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): """ get: Return a list of all registered drilling organizations post: Create a new drilling organization instance """ queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): """ get: Return the specified drilling organization patch: Updates the specified drilling organization with the fields/values provided in the request body delete: Removes the specified drilling organization record """ queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
Fix screenName parameter in ScreenHit class Changed property dp to cd to match Google Analytics screen hit request reference See https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide *Request* `` v=1 // Version. &tid=UA-XXXXX-Y // Tracking ID / Property ID. &cid=555 // Anonymous Client ID. &t=screenview // Screenview hit type. &an=funTimes // App name. &av=1.5.0 // App version. &aid=com.foo.App // App Id. &aiid=com.android.vending // App Installer Id. &cd=Home // Screen name / content description. ``
export class Serializable { constructor(props) { this.properties = props || {}; } toObject() { return this.properties; } toString() { return JSON.stringify(this.toObject()); } toJSON() { return JSON.stringify(this.properties); } toQueryString() { var str = []; var obj = this.toObject(); for (var p in obj) { if (obj.hasOwnProperty(p) && obj[p]) { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); } } return str.join('&'); } } class Hit extends Serializable { sent = false constructor(props){ super(props); } } export class PageHit extends Hit { constructor(screenName) { super({ dp: screenName, t: 'pageview' }); } } export class ScreenHit extends Hit { constructor(screenName) { super({ cd: screenName, t: 'screenview' }); } } export class Event extends Hit { constructor(category, action, label, value) { super({ ec: category, ea: action, el: label, ev: value, t: 'event' }); } }
export class Serializable { constructor(props) { this.properties = props || {}; } toObject() { return this.properties; } toString() { return JSON.stringify(this.toObject()); } toJSON() { return JSON.stringify(this.properties); } toQueryString() { var str = []; var obj = this.toObject(); for (var p in obj) { if (obj.hasOwnProperty(p) && obj[p]) { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); } } return str.join('&'); } } class Hit extends Serializable { sent = false constructor(props){ super(props); } } export class PageHit extends Hit { constructor(screenName) { super({ dp: screenName, t: 'pageview' }); } } export class ScreenHit extends Hit { constructor(screenName) { super({ dp: screenName, t: 'screenview' }); } } export class Event extends Hit { constructor(category, action, label, value) { super({ ec: category, ea: action, el: label, ev: value, t: 'event' }); } }
Update to make sure the auth date is on utc for time zone support on devices
from django.contrib.auth.models import * from django.contrib.auth.backends import ModelBackend from django.utils.translation import ugettext_lazy as _ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * import datetime import string import random import hashlib import time from authy.api import AuthyApiClient ################# # Account Model # ################# class DeviceUser(OctaBaseModel): User = models.ForeignKey('OctaHomeCore.CustomUser') Secret = models.CharField(max_length=30) def createDeviceSetupToken(self, host): self.Secret = ''.join(random.choice(string.ascii_uppercase) for i in range(30)) self.save() return {"host":host, "user":self.id, "password":self.Secret } def checkToken(self, token): salt = datetime.datetime.utcnow().strftime("%H:%M-%d/%m/%Y") hashpassword = hashlib.sha512(self.Secret.encode('utf-8') + salt.encode('utf-8')).hexdigest().upper() if (hashpassword == token): return True else: return False class Meta: db_table = u'DeviceUser'
from django.contrib.auth.models import * from django.contrib.auth.backends import ModelBackend from django.utils.translation import ugettext_lazy as _ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * import string import random import hashlib import time from authy.api import AuthyApiClient ################# # Account Model # ################# class DeviceUser(OctaBaseModel): User = models.ForeignKey('OctaHomeCore.CustomUser') Secret = models.CharField(max_length=30) def createDeviceSetupToken(self, host): self.Secret = ''.join(random.choice(string.ascii_uppercase) for i in range(30)) self.save() return {"host":host, "user":self.id, "password":self.Secret } def checkToken(self, token): salt = time.strftime("%H:%M-%d/%m/%Y") hashpassword = hashlib.sha512(self.Secret.encode('utf-8') + salt.encode('utf-8')).hexdigest().upper() if (hashpassword == token): return True else: return False class Meta: db_table = u'DeviceUser'
Add test for deleting message
import React from 'react'; import expect from 'expect'; import { mount } from 'enzyme'; import styles from '../../src/chat.scss'; import Message from '../../src/components/messages/Message'; const props = { message: { id: 1, name: 'John', avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/oagra/128.jpg', msg: 'Hello, Marry!', time: 1444428192, sender: 1 }, me: { id: 2 }, isMine: id => props.me.id === id, withPhoto: true, onDelete: (message, success) => { success(); } }; describe('Message', () => { it('should render message', () => { const wrapper = mount(<Message {...props} />); expect(wrapper.find('div').at(0).prop('className')).toBe(styles.msgBox); const parentDiv = wrapper.find('.' + styles.msgBox).children(); expect(parentDiv.length).toBe(3); expect(wrapper.find('.' + styles.msgBox).childAt(0).prop('className')).toBe(styles.avatar); }); }); describe('Message', () => { it('should delete message', () => { const wrapper = mount(<Message {...props} />); expect(wrapper.node.state.deleted).toBe(false); wrapper.find('.' + styles.msgOptions).childAt(0).simulate('click'); expect(wrapper.node.state.deleted).toBe(true); }); });
import React from 'react'; import expect from 'expect'; import { mount } from 'enzyme'; import styles from '../../src/chat.scss'; import Message from '../../src/components/messages/Message'; const props = { message: { id: 1, name: 'John', avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/oagra/128.jpg', msg: 'Hello, Marry!', time: 1444428192, sender: 1 }, me: { id: 2 }, isMine: id => props.me.id === id, withPhoto: true }; describe('Message', () => { it('should render message', () => { const wrapper = mount(<Message {...props} />); expect(wrapper.find('div').at(0).prop('className')).toBe(styles.msgBox); const parentDiv = wrapper.find('.' + styles.msgBox).children(); expect(parentDiv.length).toBe(3); expect(wrapper.find('.' + styles.msgBox).childAt(0).prop('className')).toBe(styles.avatar); }); });
Remove static import, code is more readable like this
package com.nelsonjrodrigues.pchud.net; public class Extractor { private byte[] buffer; private int offset; private int length; public Extractor(byte[] buffer, int offset, int length) { this.buffer = buffer; this.offset = offset; this.length = length; } public int u8() { if (offset > length) { throw new ArrayIndexOutOfBoundsException(); } return Byte.toUnsignedInt(buffer[offset++]); } public int u16() { return u8() ^ u8() << 8; } public float f32() { return Float.intBitsToFloat(u8() ^ u8() << 8 ^ u8() << 16 ^ u8() << 24); } }
package com.nelsonjrodrigues.pchud.net; import static java.lang.Byte.toUnsignedInt; public class Extractor { private byte[] buffer; private int offset; private int length; public Extractor(byte[] buffer, int offset, int length) { this.buffer = buffer; this.offset = offset; this.length = length; } public int u8() { if (offset > length) { throw new ArrayIndexOutOfBoundsException(); } return toUnsignedInt(buffer[offset++]); } public int u16() { return u8() ^ u8() << 8; } public float f32() { return Float.intBitsToFloat(u8() ^ u8() << 8 ^ u8() << 16 ^ u8() << 24); } }
Throw explicit error when we can't find a skin.
const { getSkinToReview } = require("../../s3"); const Utils = require("../utils"); async function reviewSkin(message) { const skin = await getSkinToReview(); if(skin == null) { throw new Error("No skins to review"); } const {md5, filename} = skin; await Utils.postSkin({ md5, title: filename => `Review: ${filename}`, dest: message.channel }); } async function handler(message, args) { let count = args[0] || 1; if (count > 50) { message.channel.send(`You can only review up to ${count} skins at a time.`); message.channel.send(`Going to show ${count} skins to review`); count = 50; } message.channel.send(`Going to show ${count} skins to review.`); let i = Number(count); while (i--) { await reviewSkin(message); } if (count > 1) { message.channel.send(`Done reviewing ${count} skins. Thanks!`); } } module.exports = { command: "review", handler, usage: "[<number>]", description: "Post a <number> of skins to be reviewed for inclusion in the Twitter bot. Defaults to 1" };
const { getSkinToReview } = require("../../s3"); const Utils = require("../utils"); async function reviewSkin(message) { const { md5 } = await getSkinToReview(); await Utils.postSkin({ md5, title: filename => `Review: ${filename}`, dest: message.channel }); } async function handler(message, args) { let count = args[0] || 1; if (count > 50) { message.channel.send(`You can only review up to ${count} skins at a time.`); message.channel.send(`Going to show ${count} skins to review`); count = 50; } message.channel.send(`Going to show ${count} skins to review.`); let i = Number(count); while (i--) { await reviewSkin(message); } if (count > 1) { message.channel.send(`Done reviewing ${count} skins. Thanks!`); } } module.exports = { command: "review", handler, usage: "[<number>]", description: "Post a <number> of skins to be reviewed for inclusion in the Twitter bot. Defaults to 1" };
Fix response tests in py3
import json from echo.response import EchoResponse, EchoSimplePlainTextResponse from echo.tests import BaseEchoTestCase class TestEchoSimplePlainTextResponse(BaseEchoTestCase): def test_populates_text_in_response(self): """The Plain text response should populate the outputSpeech""" expected = "This is the text" response = EchoSimplePlainTextResponse(expected) data = json.loads(response.content.decode()) assert data['response']['outputSpeech']['type'] == EchoResponse.PLAIN_TEXT_OUTPUT assert data['response']['outputSpeech']['text'] == expected def test_populates_session(self): """The Plain text response should populate the session attributes""" expected = {'apple': 'red', 'orange': 'orange'} response = EchoSimplePlainTextResponse('text', session=expected) data = json.loads(response.content.decode()) assert data['sessionAttributes'] == expected def test_sets_end_session_bool(self): """The Plain text response should be able to set the end_session bool""" response = EchoSimplePlainTextResponse('text', end_session=False) data = json.loads(response.content.decode()) assert not data['response']['shouldEndSession']
import json from echo.response import EchoResponse, EchoSimplePlainTextResponse from echo.tests import BaseEchoTestCase class TestEchoSimplePlainTextResponse(BaseEchoTestCase): def test_populates_text_in_response(self): """The Plain text response should populate the outputSpeech""" expected = "This is the text" response = EchoSimplePlainTextResponse(expected) data = json.loads(response.content) assert data['response']['outputSpeech']['type'] == EchoResponse.PLAIN_TEXT_OUTPUT assert data['response']['outputSpeech']['text'] == expected def test_populates_session(self): """The Plain text response should populate the session attributes""" expected = {'apple': 'red', 'orange': 'orange'} response = EchoSimplePlainTextResponse('text', session=expected) data = json.loads(response.content) assert data['sessionAttributes'] == expected def test_sets_end_session_bool(self): """The Plain text response should be able to set the end_session bool""" response = EchoSimplePlainTextResponse('text', end_session=False) data = json.loads(response.content) assert not data['response']['shouldEndSession']
Adjust migration for cumulative field.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateModifiersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('amazo_mods', function (Blueprint $table) { $table->increments('id'); $table->integer('parent_id')->unsigned()->default('1')->required(); $table->integer('damage_type_id')->unsigned()->default('1')->required(); $table->decimal('amount',14,4)->default('1')->required(); $table->boolean('cumulative')->default('0')->required(); $table->enum('mod_type', ['*', '+'])->default('*'); $table->foreign('parent_id')->references('id')->on('damage_types')->onDelete('cascade'); $table->foreign('damage_type_id')->references('id')->on('damage_types')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('amazo_mods'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateModifiersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('amazo_mods', function (Blueprint $table) { $table->increments('id'); $table->integer('parent_id')->unsigned()->default('1')->required(); $table->integer('damage_type_id')->unsigned()->default('1')->required(); $table->decimal('amount',14,4)->default('1')->required(); $table->enum('mod_type', ['*', '+'])->default('*'); $table->foreign('parent_id')->references('id')->on('damage_types')->onDelete('cascade'); $table->foreign('damage_type_id')->references('id')->on('damage_types')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('amazo_mods'); } }
Fix for no role in admin access wrapper
from flask import redirect as _redirect, url_for, render_template, g from functools import wraps def login_required(f, redirect='login'): """Redirects non-logged in users to a specified location. Usage: `@login_required`, `@login_required(redirect=<url>)` """ @wraps(f) def decorated_function(*args, **kwargs): if not g.logged_in: return _redirect(url_for(redirect)) return f(*args, **kwargs) return decorated_function def admin_access_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not g.logged_in: return _redirect(url_for('login')) if not g.user.get_role() or not g.user.get_role().can_access_admin: return render_template('403.html'), 403 return f(*args, **kwargs) return decorated_function
from flask import redirect as _redirect, url_for, render_template, g from functools import wraps def login_required(f, redirect='login'): """Redirects non-logged in users to a specified location. Usage: `@login_required`, `@login_required(redirect=<url>)` """ @wraps(f) def decorated_function(*args, **kwargs): if not g.logged_in: return _redirect(url_for(redirect)) return f(*args, **kwargs) return decorated_function def admin_access_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not g.logged_in: return _redirect(url_for('login')) if not g.user.get_role().can_access_admin: return render_template('403.html'), 403 return f(*args, **kwargs) return decorated_function
FIX example for both Win and NIX TODO: tasks wont work
import asyncio import sys from contextlib import suppress sys.path.append("..") from asynccmd import Cmd class Commander(Cmd): def __init__(self, intro, prompt): if sys.platform == 'win32': super().__init__(mode="Run", run_loop=False) else: super().__init__(mode="Reader", run_loop=False) self.intro = intro self.prompt = prompt self.loop = None def do_tasks(self, arg): """ Fake command. Type "prodigy {arg}" :param arg: args occurred from cmd after command :return: """ print(print(asyncio.Task.all_tasks(loop=self.loop))) def start(self, loop=None): self.loop = loop super().cmdloop(loop) if sys.platform == 'win32': loop = asyncio.ProactorEventLoop() else: loop = asyncio.get_event_loop() cmd = Commander(intro="This is example", prompt="example> ") cmd.start(loop) try: loop.run_forever() except KeyboardInterrupt: loop.stop() pending = asyncio.Task.all_tasks(loop=loop) for task in pending: task.cancel() with suppress(asyncio.CancelledError): loop.run_until_complete(task)
import asyncio import sys from contextlib import suppress sys.path.append("..") from asynccmd import Cmd class Commander(Cmd): def __init__(self, intro, prompt): if sys.platform == 'win32': super().__init__(mode="Run", run_loop=False) else: super().__init__(mode="Reader", run_loop=False) self.intro = intro self.prompt = prompt self.loop = None def do_tasks(self, arg): """ Fake command. Type "prodigy {arg}" :param arg: args occurred from cmd after command :return: """ print(print(asyncio.Task.all_tasks(loop=self.loop))) def start(self, loop=None): self.loop = loop super().cmdloop(loop) loop = asyncio.ProactorEventLoop() #loop = asyncio.get_event_loop() cmd = Commander(intro="This is example", prompt="example> ") cmd.start(loop) try: loop.run_forever() except KeyboardInterrupt: loop.stop() pending = asyncio.Task.all_tasks(loop=loop) for task in pending: task.cancel() with suppress(asyncio.CancelledError): loop.run_until_complete(task)
Fix name of command sent by send_dialogue action.
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class SendDialogueAction(ConversationAction): action_name = 'send_dialogue' action_display_name = 'Send Dialogue' needs_confirmation = True needs_group = True needs_running = True def check_disabled(self): if self._conv.has_channel_supporting(generic_sends=True): return None return ("This action needs channels capable of sending" " messages attached to this conversation.") def perform_action(self, action_data): return self.send_command( 'send_dialogue', batch_id=self._conv.get_latest_batch_key(), msg_options={}, is_client_initiated=False, delivery_class=self._conv.delivery_class) class DownloadUserDataAction(ConversationAction): action_name = 'download_user_data' action_display_name = 'Download User Data' redirect_to = 'user_data' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'dialogue' actions = ( SendDialogueAction, DownloadUserDataAction, )
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class SendDialogueAction(ConversationAction): action_name = 'send_dialogue' action_display_name = 'Send Dialogue' needs_confirmation = True needs_group = True needs_running = True def check_disabled(self): if self._conv.has_channel_supporting(generic_sends=True): return None return ("This action needs channels capable of sending" " messages attached to this conversation.") def perform_action(self, action_data): return self.send_command( 'send_survey', batch_id=self._conv.get_latest_batch_key(), msg_options={}, is_client_initiated=False, delivery_class=self._conv.delivery_class) class DownloadUserDataAction(ConversationAction): action_name = 'download_user_data' action_display_name = 'Download User Data' redirect_to = 'user_data' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'dialogue' actions = ( SendDialogueAction, DownloadUserDataAction, )
Convert price to float to compare
<?php function GetAuctionData($gameID){ $data = json_decode(file_get_contents('https://www.g2a.com/marketplace/product/auctions/?id=' . $gameID), true); $data = array_values(array_values($data)[0])[0]; $result = array(); $result['price'] = (float) $data['p']; $result['rating'] = $data['r']; $result['sells'] = $data['tr']; $result['country'] = GetCountry($data['c']); return $result; } function GetCountry($code){ $data = json_decode(file_get_contents('http://restcountries.eu/rest/v1/alpha/' . $code), true); return $data['name']; } function GetLowestPrice($gameID){ $data = GetAuctionData($gameID); return $data[0]; } /* Finds a game's entity ID (needed for using the G2A API) by extracting it from the game's page on G2A */ function GetGameEntityID($gameURL){ $gameSite = file_get_contents($gameURL); /* Find the game's ID in the page's HTML */ preg_match("/(?<=productID = )(.*)(?=;)/", $gameSite, $entityID); if (count($entityID) >= 1){ return $entityID[0]; } else { return false; } } function IsPriceLowEnough($price, $limit){ return $price <= $limit; } ?>
<?php function GetAuctionData($gameID){ $data = json_decode(file_get_contents('https://www.g2a.com/marketplace/product/auctions/?id=' . $gameID), true); $data = array_values(array_values($data)[0])[0]; $result = array(); $result['price'] = $data['p']; $result['rating'] = $data['r']; $result['sells'] = $data['tr']; $result['country'] = GetCountry($data['c']); return $result; } function GetCountry($code){ $data = json_decode(file_get_contents('http://restcountries.eu/rest/v1/alpha/' . $code), true); return $data['name']; } function GetLowestPrice($gameID){ $data = GetAuctionData($gameID); return $data[0]; } /* Finds a game's entity ID (needed for using the G2A API) by extracting it from the game's page on G2A */ function GetGameEntityID($gameURL){ $gameSite = file_get_contents($gameURL); /* Find the game's ID in the page's HTML */ preg_match("/(?<=productID = )(.*)(?=;)/", $gameSite, $entityID); if (count($entityID) >= 1){ return $entityID[0]; } else { return false; } } function IsPriceLowEnough($price, $limit){ return $price <= $limit; } ?>