text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Make pause dependant on annotation text length
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" for annotation in reversed(annotations): pause_time = len(annotation["text"]) * 0.4 current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point, audio=False) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" pause_time = 1 for annotation in reversed(annotations): current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
Add nc and state as attributes. Change name of gpio_num to gpio
import RPi.GPIO as GPIO class relay(): def __init__(self, gpio_num, NC=False): self.gpio = gpio_num self.nc = NC GPIO.setmode(GPIO.BCM) try: GPIO.input(self.gpio) raise LookupError("Relay is already in use!") except RuntimeError: GPIO.setup(self.gpio, GPIO.OUT) except ValueError: raise LookupError("Relay number invalid!") if self.nc: self.on() else: self.off() def on(self): GPIO.output(self.gpio, GPIO.HIGH) self.state = True def off(self): GPIO.output(self.gpio, GPIO.LOW) self.state = False def get_state(self): return self.state def cleanup(self): GPIO.cleanup(self.gpio)
import RPi.GPIO as GPIO class relay(): def __init__(self, gpio_num, NC=False): self.gpio_num = gpio_num GPIO.setmode(GPIO.BCM) try: GPIO.input(self.gpio_num) raise LookupError("Relay is already in use!") except RuntimeError: GPIO.setup(self.gpio_num, GPIO.OUT) except ValueError: raise LookupError("Relay number invalid!") if NC: self.on() else: self.off() def on(self): GPIO.output(self.gpio_num, GPIO.HIGH) def off(self): GPIO.output(self.gpio_num, GPIO.LOW) def get_state(self): return GPIO.input(self.gpio_num) def cleanup(self): GPIO.cleanup(self.gpio_num)
Add addDirective method to add directive
<?php namespace CodeGen\Frameworks\Apache2; class BaseDirectiveGroup { protected $tag; protected $dynamicDirectives = []; public function __construct($tag) { $this->tag = $tag; } public function __call($method, $args) { $directiveName = ucfirst(str_replace('set', '', $method)); $value = $args[0]; $this->dynamicDirectives[] = "{$directiveName} {$value}"; return $this; } public function addDirective($directive) { $this->dynamicDirectives[] = $directive; } protected function buildDynamicDirectives(array &$out) { foreach ($this->dynamicDirectives as $directive) { $out[] = $directive; } } }
<?php namespace CodeGen\Frameworks\Apache2; class BaseDirectiveGroup { protected $tag; protected $dynamicDirectives = []; public function __construct($tag) { $this->tag = $tag; } public function __call($method, $args) { $directiveName = ucfirst(str_replace('set', '', $method)); $value = $args[0]; $this->dynamicDirectives[] = "{$directiveName} {$value}"; return $this; } protected function buildDynamicDirectives(array &$out) { foreach ($this->dynamicDirectives as $directive) { $out[] = $directive; } } }
Clean links list for each new cycle.
package com.urlcrawler; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LineParserImpl implements LineParser { private Pattern regPattern; private List<URL> links = new ArrayList<URL>(); public List<URL> extractUrl(String line) { links.clear(); Matcher m = regPattern.matcher(line); while (m.find()) { try { System.out.println("Converting string to URL: " + m.group(1)); URL url = new URL(m.group(1)); links.add(url); } catch (MalformedURLException e) { } } return links; } public void setRegularExpression(String regex) { this.regPattern = Pattern.compile(regex); } }
package com.urlcrawler; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LineParserImpl implements LineParser { private Pattern regPattern; private List<URL> links = new ArrayList<URL>(); public List<URL> extractUrl(String line) { Matcher m = regPattern.matcher(line); while (m.find()) { try { System.out.println("Converting string to URL: " + m.group(1)); URL url = new URL(m.group(1)); links.add(url); } catch (MalformedURLException e) { } } return links; } public void setRegularExpression(String regex) { this.regPattern = Pattern.compile(regex); } }
Move positional argument to the end. This doesn't seem to work on a Mac when option comes after the positional argument, not sure why this is, something to do with options parsing.
#!/usr/bin/env python from integrationtest import IntegrationTest, main import unittest class TestCreate(IntegrationTest, unittest.TestCase): def test_junctions_create(self): bam1 = self.inputFiles("test_hcc1395.bam")[0] output_file = self.tempFile("create.out") print "BAM1 is ", bam1 for anchor in ["", "30"]: expected_file = self.inputFiles("junctions-create/expected-a" + anchor + ".out")[0] if anchor != "": anchor = "-a " + anchor params = [ "junctions", "create", anchor, "-o", output_file, bam1 ] rv, err = self.execute(params) self.assertEqual(rv, 0) #self.assertEqual('', err) self.assertFilesEqual(expected_file, output_file) if __name__ == "__main__": main()
#!/usr/bin/env python from integrationtest import IntegrationTest, main import unittest class TestCreate(IntegrationTest, unittest.TestCase): def test_junctions_create(self): bam1 = self.inputFiles("test_hcc1395.bam")[0] output_file = self.tempFile("create.out") print "BAM1 is ", bam1 for anchor in ["", "30"]: expected_file = self.inputFiles("junctions-create/expected-a" + anchor + ".out")[0] if anchor != "": anchor = "-a " + anchor params = [ "junctions", "create", bam1, anchor, "-o", output_file] rv, err = self.execute(params) self.assertEqual(rv, 0) #self.assertEqual('', err) self.assertFilesEqual(expected_file, output_file) if __name__ == "__main__": main()
Add cached-property to the dependencies
from setuptools import setup, find_packages import populous requirements = [ "click", "cached-property", ] setup( name="populous", version=populous.__version__, url=populous.__url__, description=populous.__doc__, author=populous.__author__, license=populous.__license__, long_description="TODO", packages=find_packages(), install_requires=requirements, entry_points={ 'console_scripts': [ 'populous = populous.__main__:cli' ] }, classifiers=[ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Utilities", ], keywords='populous populate database', )
from setuptools import setup, find_packages import populous requirements = [ "click", ] setup( name="populous", version=populous.__version__, url=populous.__url__, description=populous.__doc__, author=populous.__author__, license=populous.__license__, long_description="TODO", packages=find_packages(), install_requires=requirements, entry_points={ 'console_scripts': [ 'populous = populous.__main__:cli' ] }, classifiers=[ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Utilities", ], keywords='populous populate database', )
Change name for Half Operator to Half-Op
package com.iskrembilen.quasseldroid; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * User: Stian * Date: 05.07.12 * Time: 20:14 */ public enum IrcMode { /* * Declare in order of rank, this way values() will naturally * return the different modes based on rank */ OWNER ("Owner","q", "(s)", R.drawable.irc_operator), ADMIN ("Admin","a", "(s)", R.drawable.irc_operator), OPERATOR ("Operator","o", "(s)", R.drawable.irc_operator), HALF_OPERATOR ("Half-Op","h", "(s)", R.drawable.irc_voice), VOICE ("Voiced","v", "", R.drawable.irc_voice), USER ("User","", "(s)", R.drawable.im_user); //This will work as a catch-all for unknown modes public final String modeName; public final String shortModeName; public final String pluralization; public final int iconResource; IrcMode(String modeName, String shortModeName, String pluralization, int iconResource) { this.modeName = modeName; this.shortModeName = shortModeName; this.pluralization = pluralization; this.iconResource = iconResource; } }
package com.iskrembilen.quasseldroid; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * User: Stian * Date: 05.07.12 * Time: 20:14 */ public enum IrcMode { /* * Declare in order of rank, this way values() will naturally * return the different modes based on rank */ OWNER ("Owner","q", "(s)", R.drawable.irc_operator), ADMIN ("Admin","a", "(s)", R.drawable.irc_operator), OPERATOR ("Operator","o", "(s)", R.drawable.irc_operator), HALF_OPERATOR ("Half Operator","h", "(s)", R.drawable.irc_voice), VOICE ("Voiced","v", "", R.drawable.irc_voice), USER ("User","", "(s)", R.drawable.im_user); //This will work as a catch-all for unknown modes public final String modeName; public final String shortModeName; public final String pluralization; public final int iconResource; IrcMode(String modeName, String shortModeName, String pluralization, int iconResource) { this.modeName = modeName; this.shortModeName = shortModeName; this.pluralization = pluralization; this.iconResource = iconResource; } }
Fix test on grid search
import pytest import torch from torch import Tensor import syft as sy def test_virtual_grid(workers): """This tests our ability to simplify tuple types. This test is pretty simple since tuples just serialize to themselves, with a tuple wrapper with the correct ID (1) for tuples so that the detailer knows how to interpret it.""" print(len(workers)) print(workers) bob = workers["bob"] alice = workers["alice"] james = workers["james"] grid = sy.grid.VirtualGrid(*[bob, alice, james]) x = torch.tensor([1, 2, 3, 4]).tag("#bob", "#male").send(bob) y = torch.tensor([1, 2, 3, 4]).tag("#alice", "#female").send(alice) z = torch.tensor([1, 2, 3, 4]).tag("#james", "#male").send(james) results, tags = grid.search() assert len(results) == 3 assert "bob" in results.keys() assert "alice" in results.keys() assert "james" in results.keys() results, tags = grid.search("#bob") assert len(results["bob"]) == 1 assert "alice" not in results assert "james" not in results results, tags = grid.search("#male") assert len(results["bob"]) == 1 assert "alice" not in results assert len(results["james"]) == 1
import pytest import torch from torch import Tensor import syft as sy def test_virtual_grid(workers): """This tests our ability to simplify tuple types. This test is pretty simple since tuples just serialize to themselves, with a tuple wrapper with the correct ID (1) for tuples so that the detailer knows how to interpret it.""" print(len(workers)) print(workers) bob = workers["bob"] alice = workers["alice"] james = workers["james"] grid = sy.grid.VirtualGrid(*[bob, alice, james]) x = torch.tensor([1, 2, 3, 4]).tag("#bob", "#male").send(bob) y = torch.tensor([1, 2, 3, 4]).tag("#alice", "#female").send(alice) z = torch.tensor([1, 2, 3, 4]).tag("#james", "#male").send(james) results, tags = grid.search("#bob") assert len(results) == 3 assert "bob" in results.keys() assert "alice" in results.keys() assert "james" in results.keys() results, tags = grid.search("#bob") assert len(results["bob"]) == 1 assert len(results["alice"]) == 0 assert len(results["james"]) == 0 results, tags = grid.search("#male") assert len(results["bob"]) == 1 assert len(results["alice"]) == 0 assert len(results["james"]) == 1
Remove unnecessary async in migration function
export function up(knex) { return knex.schema .table('users', (table) => table.boolean('is_protected').defaultTo(false).notNullable()) .raw('update users set is_protected = (is_private or not is_visible_to_anonymous)') .raw('alter table users add constraint users_is_protected_check check (is_protected or not is_private)') .table('users', (table) => { table.dropIndex('', 'is_visible_to_anonymous_idx'); table.dropColumn('is_visible_to_anonymous'); table.index('is_protected', 'users_is_protected_idx', 'btree'); }); } export function down(knex) { return knex.schema .table('users', (table) => table.boolean('is_visible_to_anonymous').defaultTo(true).notNullable()) .raw('update users set is_visible_to_anonymous = (not is_private and not is_protected)') .raw('alter table users drop constraint users_is_protected_check') .table('users', (table) => { table.dropIndex('', 'users_is_protected_idx'); table.dropColumn('is_protected'); table.index('is_visible_to_anonymous', 'is_visible_to_anonymous_idx', 'btree'); }); }
export function up(knex) { return knex.schema .table('users', (table) => table.boolean('is_protected').defaultTo(false).notNullable()) .raw('update users set is_protected = (is_private or not is_visible_to_anonymous)') .raw('alter table users add constraint users_is_protected_check check (is_protected or not is_private)') .table('users', (table) => { table.dropIndex('', 'is_visible_to_anonymous_idx'); table.dropColumn('is_visible_to_anonymous'); table.index('is_protected', 'users_is_protected_idx', 'btree'); }); } export async function down(knex) { return knex.schema .table('users', (table) => table.boolean('is_visible_to_anonymous').defaultTo(true).notNullable()) .raw('update users set is_visible_to_anonymous = (not is_private and not is_protected)') .raw('alter table users drop constraint users_is_protected_check') .table('users', (table) => { table.dropIndex('', 'users_is_protected_idx'); table.dropColumn('is_protected'); table.index('is_visible_to_anonymous', 'is_visible_to_anonymous_idx', 'btree'); }); }
Fix Duration.__str__ to show Conference name and code
from django.core.validators import MinValueValidator from django.db import models from django.utils.translation import ugettext_lazy as _ class Duration(models.Model): conference = models.ForeignKey( "conferences.Conference", on_delete=models.CASCADE, verbose_name=_("conference"), related_name="durations", ) name = models.CharField(_("name"), max_length=100) duration = models.PositiveIntegerField( _("duration"), validators=[MinValueValidator(1)] ) notes = models.TextField(_("notes"), blank=True) allowed_submission_types = models.ManyToManyField( "submissions.SubmissionType", verbose_name=_("allowed submission types") ) def __str__(self): return ( f"{self.name} - {self.duration} mins (at Conference " f"{self.conference.name} <{self.conference.code}>)" ) class Meta: verbose_name = _("Duration") verbose_name_plural = _("Durations")
from django.core.validators import MinValueValidator from django.db import models from django.utils.translation import ugettext_lazy as _ class Duration(models.Model): conference = models.ForeignKey( "conferences.Conference", on_delete=models.CASCADE, verbose_name=_("conference"), related_name="durations", ) name = models.CharField(_("name"), max_length=100) duration = models.PositiveIntegerField( _("duration"), validators=[MinValueValidator(1)] ) notes = models.TextField(_("notes"), blank=True) allowed_submission_types = models.ManyToManyField( "submissions.SubmissionType", verbose_name=_("allowed submission types") ) def __str__(self): return f"{self.name} - {self.duration} mins ({self.conference_id})" class Meta: verbose_name = _("Duration") verbose_name_plural = _("Durations")
Use Discord as the imagehost
//META{"name":"agif"}*// var agif = function () {}; agif.prototype.convert = function () { $(".image canvas").each(function() { var src = $(this).attr("src"); if(src != undefined) { $(this).replaceWith('<img src="'+src+'"></img>'); } }); }; agif.prototype.onMessage = function () { this.convert(); }; agif.prototype.onSwitch = function () { this.convert(); }; agif.prototype.start = function () { this.convert(); }; agif.prototype.load = function () {}; agif.prototype.unload = function () {}; agif.prototype.stop = function () {}; agif.prototype.getSettingsPanel = function () { return ""; }; agif.prototype.getName = function () { return "Autogif"; }; agif.prototype.getDescription = function () { return "Autoplay gifs without having to hover."; }; agif.prototype.getVersion = function () { return "0.1.0"; }; agif.prototype.getAuthor = function () { return "Jiiks"; };
//META{"name":"agif"}*// var agif = function () {}; agif.prototype.convert = function () { $(".image canvas").each(function() { var href = $(this).attr("href"); if(href != undefined) { if(href.endsWith(".gif")) { href = href.replace("http:", "https:"); $(this).replaceWith('<img src="'+href+'"></img>'); } } }); }; agif.prototype.onMessage = function () { this.convert(); }; agif.prototype.onSwitch = function () { this.convert(); }; agif.prototype.start = function () { this.convert(); }; agif.prototype.load = function () {}; agif.prototype.unload = function () {}; agif.prototype.stop = function () {}; agif.prototype.getSettingsPanel = function () { return ""; }; agif.prototype.getName = function () { return "Autogif"; }; agif.prototype.getDescription = function () { return "Autoplay gifs without having to hover."; }; agif.prototype.getVersion = function () { return "0.1.0"; }; agif.prototype.getAuthor = function () { return "Jiiks"; };
Fix up migrations, part 2
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name='python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name=b'python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
Fix tests failing on long line
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import tempfile __version__ = '0.1.11' DB = os.path.join( tempfile.gettempdir(), 'fake_useragent_{version}.json'.format( version=__version__, ), ) CACHE_SERVER = 'https://fake-useragent.herokuapp.com/browsers/{version}'.format( # noqa version=__version__, ) BROWSERS_STATS_PAGE = 'https://www.w3schools.com/browsers/default.asp' BROWSER_BASE_PAGE = 'http://useragentstring.com/pages/useragentstring.php?name={browser}' # noqa BROWSERS_COUNT_LIMIT = 50 REPLACEMENTS = { ' ': '', '_': '', } SHORTCUTS = { 'internet explorer': 'internetexplorer', 'ie': 'internetexplorer', 'msie': 'internetexplorer', 'edge': 'internetexplorer', 'google': 'chrome', 'googlechrome': 'chrome', 'ff': 'firefox', } OVERRIDES = { 'Edge/IE': 'Internet Explorer', 'IE/Edge': 'Internet Explorer', } HTTP_TIMEOUT = 5 HTTP_RETRIES = 2 HTTP_DELAY = 0.1
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import tempfile __version__ = '0.1.11' DB = os.path.join( tempfile.gettempdir(), 'fake_useragent_{version}.json'.format( version=__version__, ), ) CACHE_SERVER = 'https://fake-useragent.herokuapp.com/browsers/{version}'.format( version=__version__, ) BROWSERS_STATS_PAGE = 'https://www.w3schools.com/browsers/default.asp' BROWSER_BASE_PAGE = 'http://useragentstring.com/pages/useragentstring.php?name={browser}' # noqa BROWSERS_COUNT_LIMIT = 50 REPLACEMENTS = { ' ': '', '_': '', } SHORTCUTS = { 'internet explorer': 'internetexplorer', 'ie': 'internetexplorer', 'msie': 'internetexplorer', 'edge': 'internetexplorer', 'google': 'chrome', 'googlechrome': 'chrome', 'ff': 'firefox', } OVERRIDES = { 'Edge/IE': 'Internet Explorer', 'IE/Edge': 'Internet Explorer', } HTTP_TIMEOUT = 5 HTTP_RETRIES = 2 HTTP_DELAY = 0.1
Make defensive copies of the "see also" and "other" lists
package com.github.therapi.runtimejavadoc; import java.util.List; import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.unmodifiableDefensiveCopy; public abstract class BaseJavadoc { private final String name; private final Comment comment; private final List<SeeAlsoJavadoc> seeAlso; private final List<OtherJavadoc> other; BaseJavadoc(String name, Comment comment, List<SeeAlsoJavadoc> seeAlso, List<OtherJavadoc> other) { this.name = name; this.comment = comment; this.other = unmodifiableDefensiveCopy(other); this.seeAlso = unmodifiableDefensiveCopy(seeAlso); } public String getName() { return name; } public Comment getComment() { return comment; } public List<SeeAlsoJavadoc> getSeeAlso() { return seeAlso; } public List<OtherJavadoc> getOther() { return other; } }
package com.github.therapi.runtimejavadoc; import java.util.List; public abstract class BaseJavadoc { private final String name; private final Comment comment; private final List<SeeAlsoJavadoc> seeAlso; private final List<OtherJavadoc> other; BaseJavadoc(String name, Comment comment, List<SeeAlsoJavadoc> seeAlso, List<OtherJavadoc> other) { this.name = name; this.comment = comment; this.other = other; this.seeAlso = seeAlso; } public String getName() { return name; } public Comment getComment() { return comment; } public List<SeeAlsoJavadoc> getSeeAlso() { return seeAlso; } public List<OtherJavadoc> getOther() { return other; } }
Update user POST and GET routes
import {Router} from 'express' import models from '../models'; import tasks from './tasks' export default () => { let app = Router({mergeParams: true}) app.use('/:userId/tasks', tasks()) app.get('/:id', (req, res) => { models.User.find(req.params.id).then((users) => { res.send(users) }) }) app.get('/new', (req, res) => { res.render('users/new') }) app.get('/:id', (req, res) => { models.User.find({ where: { id: req.params.id }, include: [models.Task] }).then((user) => { res.render('users/show', {user}) }) }) app.post('/', (req, res) => { models.User.create(req.body).then((user) => { req.session.userId = user.dataValues.id req.app.locals.userId = user.dataValues.id req.session.save() // add validations and errors res.send(user); }) }) return app }
import {Router} from 'express' import models from '../models'; import tasks from './tasks' export default () => { let app = Router({mergeParams: true}) app.use('/:userId/tasks', tasks()) app.get('/', (req, res) => { models.User.findAll({ attributes: ['id', 'email'] }).then((users) => { res.send(users) }) }) app.get('/new', (req, res) => { res.render('users/new') }) app.get('/:id', (req, res) => { models.User.find({ where: { id: req.params.id }, include: [models.Task] }).then((user) => { res.render('users/show', {user}) }) }) app.post('/', (req, res) => { models.User.create(req.body).then((user) => { req.session.userId = user.dataValues.id req.app.locals.userId = user.dataValues.id req.session.save() // add validations and errors res.send(user); }) }) return app }
Use strict comparison to determine honeypot field value
<?php namespace Cerbero\Auth\Http\Middleware; use Closure; use Cerbero\Auth\Exceptions\DisplayException; /** * Protect from spam and bots. * * @author Andrea Marco Sartori */ class Honeypot { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(config('_auth.honeypot.enabled')) { $value = $request->input(config('_auth.honeypot.field')); $this->checkHoneypot($value); } return $next($request); } /** * Throw an exception if the honeypot field is not empty. * * @author Andrea Marco Sartori * @param string $value * @return void */ protected function checkHoneypot($value) { if($value !== null) { throw new DisplayException('auth::honeypot.error'); } } }
<?php namespace Cerbero\Auth\Http\Middleware; use Closure; use Cerbero\Auth\Exceptions\DisplayException; /** * Protect from spam and bots. * * @author Andrea Marco Sartori */ class Honeypot { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(config('_auth.honeypot.enabled')) { $value = $request->input(config('_auth.honeypot.field')); $this->checkHoneypot($value); } return $next($request); } /** * Throw an exception if the honeypot field is not empty. * * @author Andrea Marco Sartori * @param string $value * @return void */ protected function checkHoneypot($value) { if($value != null) { throw new DisplayException('auth::honeypot.error'); } } }
Use labels definied on relation if available
'use strict'; var d = require('es5-ext/lib/Object/descriptor') , Db = require('dbjs') , DOMText = require('./_text') , getValue = Object.getOwnPropertyDescriptor(DOMText.prototype, 'value').get , Base = Db.Base , Text; Text = function (document, ns, options) { this.document = document; this.ns = ns; this.relation = options && options.relation; this.text = new DOMText(document, Base); this.dom = this.text.dom; }; Text.prototype = Object.create(DOMText.prototype, { constructor: d(Text), value: d.gs(getValue, function (value) { var rel; if (value == null) { this.text.dismiss(); this.text.value = value; return; } if (value.valueOf()) { rel = (this.relation && this.relation.__trueLabel.__value) ? this.relation._trueLabel : this.ns._trueLabel; } else { rel = (this.relation && this.relation.__falseLabel.__value) ? this.relation._falseLabel : this.ns._falseLabel; } rel.assignDOMText(this.text); }) }); module.exports = Object.defineProperty(Db.Boolean, 'DOMText', d(Text));
'use strict'; var d = require('es5-ext/lib/Object/descriptor') , Db = require('dbjs') , DOMText = require('./_text') , getValue = Object.getOwnPropertyDescriptor(DOMText.prototype, 'value').get , Base = Db.Base , Text; Text = function (document, ns) { this.document = document; this.ns = ns; this.text = new DOMText(document, Base); this.dom = this.text.dom; }; Text.prototype = Object.create(DOMText.prototype, { constructor: d(Text), value: d.gs(getValue, function (value) { if (value == null) { this.text.dismiss(); this.text.value = value; return; } this.ns[value.valueOf() ? '_trueLabel' : '_falseLabel'] .assignDOMText(this.text); }) }); module.exports = Object.defineProperty(Db.Boolean, 'DOMText', d(Text));
Make field nullable instead of set default value
<?php /* * This file is part of the ws/array-field-type-extension package. * * (c) Benjamin Georgeault <github@wedgesama.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Bolt\Extension\WS\ArrayFieldExtension; use Bolt\Field\FieldInterface; /** * ArrayField * * @author Benjamin Georgeault <github@wedgesama.fr> */ class ArrayField implements FieldInterface { public function getName() { return 'array'; } public function getTemplate() { return '_array.twig'; } public function getStorageType() { return 'array'; } public function getStorageOptions() { return array( 'children' => array(), 'nullable' => true, ); } }
<?php /* * This file is part of the ws/array-field-type-extension package. * * (c) Benjamin Georgeault <github@wedgesama.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Bolt\Extension\WS\ArrayFieldExtension; use Bolt\Field\FieldInterface; /** * ArrayField * * @author Benjamin Georgeault <github@wedgesama.fr> */ class ArrayField implements FieldInterface { public function getName() { return 'array'; } public function getTemplate() { return '_array.twig'; } public function getStorageType() { return 'array'; } public function getStorageOptions() { return array( 'children' => array(), 'default' => '' ); } }
Set logging in overwrite mode
# Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging from barf import BARF import analysis import core import arch # Setup logging module. logging.basicConfig( filename="barf.log", format="%(asctime)s: %(name)s:%(levelname)s: %(message)s", filemode='w', level=logging.DEBUG )
# Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging from barf import BARF import analysis import core import arch # Setup logging module. logging.basicConfig( filename="barf.log", format="%(asctime)s: %(name)s:%(levelname)s: %(message)s", level=logging.DEBUG )
Make the default backend be a multi-backend
# 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. from cryptography.hazmat.backends import openssl from cryptography.hazmat.backends.multibackend import MultiBackend from cryptography.hazmat.bindings.commoncrypto.binding import ( Binding as CommonCryptoBinding ) _ALL_BACKENDS = [openssl.backend] if CommonCryptoBinding.is_available(): from cryptography.hazmat.backends import commoncrypto _ALL_BACKENDS.append(commoncrypto.backend) _default_backend = MultiBackend(_ALL_BACKENDS) def default_backend(): return _default_backend
# 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. from cryptography.hazmat.backends import openssl from cryptography.hazmat.bindings.commoncrypto.binding import ( Binding as CommonCryptoBinding ) _ALL_BACKENDS = [openssl.backend] if CommonCryptoBinding.is_available(): from cryptography.hazmat.backends import commoncrypto _ALL_BACKENDS.append(commoncrypto.backend) def default_backend(): return openssl.backend
Fix broken comment in slug function
var updatableSlug = true; /* jQuery because BS brings it in; trivial to remove */ function sluggify(str) { if (!str) { return ""; } /* we could check for the existence of a slug too */ return str.toLowerCase() /* no uppercase in slug */ .replace(/[^a-z0-9-]/g, "-") /* get rid of non-alphanumerics/hyphen */ .replace(/--+/g, "-") /* get rid of doubled up hyphens */ .replace(/-$/g, "") /* get rid of trailing hyphens */ .replace(/^-/g, "") /* and leading ones too */; } function updateSlugMaybe(source) { if (updatableSlug) { $("#slug").val(sluggify($(source).val())) } } /* if the slug box has its own value entered, don't overwrite */ function slugBlur(source) { /* is the slug empty, or is the same as a sluggified name? if so, make it changeable */ var val = $(source).val(); updatableSlug = !val || (sluggify($("#name").val()) == val); }
var updatableSlug = true; /* jQuery because BS brings it in; trivial to remove */ function sluggify(str) { if (!str) { return ""; } /* we could check for the existence of a slug too */ return str.toLowerCase() /* no uppercase in slug */ .replace(/[^a-z0-9-]/g, "-") /* get rid of non-alphanumerics/hyphen .replace(/--+/g, "-") /* get rid of doubled up hyphens */ .replace(/-$/g, "") /* get rid of trailing hyphens */ .replace(/^-/g, "") /* and leading ones too */; } function updateSlugMaybe(source) { if (updatableSlug) { $("#slug").val(sluggify($(source).val())) } } /* if the slug box has its own value entered, don't overwrite */ function slugBlur(source) { /* is the slug empty, or is the same as a sluggified name? if so, make it changeable */ var val = $(source).val(); updatableSlug = !val || (sluggify($("#name").val()) == val); }
Add more tests for Basic Authentication parser
"use strict"; var Server = require("../server"); exports.testMissingAuthorizationHeader = function (test) { var parser = Server.prototype._basicAuthentication({ "headers": {} }); parser().fail(function (err) { test.equal(401, err.statusCode); test.done(); }); }; exports.testValidAuthorizationHeader = function (test) { var parser = Server.prototype._basicAuthentication({ "headers": { "authorization": "Basic Zm9vOmJhcg==" } }); parser().then(function (result) { test.deepEqual(["foo", "bar"], result); test.done(); }); }; exports.testBlatantlyWrongAuthorizationHeader = function (test) { var parser = Server.prototype._basicAuthentication({ "headers": { "authorization": "What the heck is this" } }); parser().fail(function (err) { test.equal(400, err.statusCode); test.done(); }); }; exports.testInvalidAuthorizationHeader = function (test) { var parser = Server.prototype._basicAuthentication({ "headers": { "authorization": "Derp Zm9vOmJhcg==" } }); parser().fail(function (err) { test.equal(400, err.statusCode); test.done(); }); };
"use strict"; var Server = require("../server"); exports.testMissingBasicHeader = function (test) { var parser = Server.prototype._basicAuthentication({ "headers": {} }); parser().fail(function (err) { test.equal(401, err.statusCode); test.done(); }); }; exports.testValidBasicHeader = function (test) { var parser = Server.prototype._basicAuthentication({ "headers": { "authorization": "Basic Zm9vOmJhcg==" } }); parser().then(function (result) { test.deepEqual(["foo", "bar"], result); test.done(); }); }; exports.testInvalidBasicHeader = function (test) { var parser = Server.prototype._basicAuthentication({ "headers": { "authorization": "What the heck is this" } }); parser().fail(function (err) { test.equal(400, err.statusCode); test.done(); }); };
Remove badges from pypi description
from setuptools import setup from os import path project_dir = path.abspath(path.dirname(__file__)) def read_from(filename): with open(path.join(project_dir, filename), encoding='utf-8') as f: return f.read().strip() setup( name='nlist', version=read_from('VERSION'), description='A lightweight multidimensional list in Python', long_description='\n'.join(read_from('README.rst').splitlines()[3:]), url='https://github.com/swarmer/nlist', author='Anton Barkovsky', author_email='anton@swarmer.me', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], keywords='array list container multidimensional', py_modules=['nlist'], install_requires=[], include_package_data=True, )
from setuptools import setup from os import path project_dir = path.abspath(path.dirname(__file__)) def read_from(filename): with open(path.join(project_dir, filename), encoding='utf-8') as f: return f.read().strip() setup( name='nlist', version=read_from('VERSION'), description='A lightweight multidimensional list in Python', long_description=read_from('README.rst'), url='https://github.com/swarmer/nlist', author='Anton Barkovsky', author_email='anton@swarmer.me', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], keywords='array list container multidimensional', py_modules=['nlist'], install_requires=[], include_package_data=True, )
Add "push" and "replace" handy methods There are also two handy methods of history API that allow not to specify state object during transitions: * `push(path[, state])` * `replace(path[, state])`
import { ROUTER_DID_CHANGE, REPLACE_ROUTES, HISTORY_API } from './constants'; /** * Action creator for signaling that the router has changed. * @private * @param {RouterState} state - New router state * @return {Action} Action object */ export function routerDidChange(state) { return { type: ROUTER_DID_CHANGE, payload: state }; } /** * Action creator that replaces the current route config * @private * @param {Array<Route>|ReactElement} routes - New routes */ export function replaceRoutes(routes) { return { type: REPLACE_ROUTES, payload: routes }; } /** * Creates an action creator for calling a history API method. * @param {string} method - Name of method * @returns {ActionCreator} Action creator with same parameters as corresponding * history method */ export function historyAPI(method) { return (...args) => ({ type: HISTORY_API, payload: { method, args } }); } export const pushState = historyAPI('pushState'); export const push = historyAPI('push'); export const replaceState = historyAPI('replaceState'); export const replace = historyAPI('replace'); export const setState = historyAPI('setState'); export const go = historyAPI('go'); export const goBack = historyAPI('goBack'); export const goForward = historyAPI('goForward');
import { ROUTER_DID_CHANGE, REPLACE_ROUTES, HISTORY_API } from './constants'; /** * Action creator for signaling that the router has changed. * @private * @param {RouterState} state - New router state * @return {Action} Action object */ export function routerDidChange(state) { return { type: ROUTER_DID_CHANGE, payload: state }; } /** * Action creator that replaces the current route config * @private * @param {Array<Route>|ReactElement} routes - New routes */ export function replaceRoutes(routes) { return { type: REPLACE_ROUTES, payload: routes }; } /** * Creates an action creator for calling a history API method. * @param {string} method - Name of method * @returns {ActionCreator} Action creator with same parameters as corresponding * history method */ export function historyAPI(method) { return (...args) => ({ type: HISTORY_API, payload: { method, args } }); } export const pushState = historyAPI('pushState'); export const replaceState = historyAPI('replaceState'); export const setState = historyAPI('setState'); export const go = historyAPI('go'); export const goBack = historyAPI('goBack'); export const goForward = historyAPI('goForward');
Remove extraneous println during tests
// +build go1.7 package providertests import ( "testing" saml2 "github.com/russellhaering/gosaml2" "github.com/stretchr/testify/require" ) func ExerciseProviderTestScenarios(t *testing.T, scenarios []ProviderTestScenario) { for _, scenario := range scenarios { t.Run(scenario.ScenarioName, func(t *testing.T) { _, err := saml2.DecodeUnverifiedBaseResponse(scenario.Response) // DecodeUnverifiedBaseResponse is more permissive than RetrieveAssertionInfo. // If an error _is_ returned it should match, but it is OK for no error to be // returned even when one is expected during full validation. if err != nil { scenario.CheckError(t, err) } assertionInfo, err := scenario.ServiceProvider.RetrieveAssertionInfo(scenario.Response) if scenario.CheckError != nil { scenario.CheckError(t, err) } else { require.NoError(t, err) } if err == nil { if scenario.CheckWarningInfo != nil { scenario.CheckWarningInfo(t, assertionInfo.WarningInfo) } else { require.False(t, assertionInfo.WarningInfo.InvalidTime) require.False(t, assertionInfo.WarningInfo.NotInAudience) } } }) } }
// +build go1.7 package providertests import ( "testing" saml2 "github.com/russellhaering/gosaml2" "github.com/stretchr/testify/require" ) func ExerciseProviderTestScenarios(t *testing.T, scenarios []ProviderTestScenario) { println("TESTING") for _, scenario := range scenarios { t.Run(scenario.ScenarioName, func(t *testing.T) { _, err := saml2.DecodeUnverifiedBaseResponse(scenario.Response) // DecodeUnverifiedBaseResponse is more permissive than RetrieveAssertionInfo. // If an error _is_ returned it should match, but it is OK for no error to be // returned even when one is expected during full validation. if err != nil { scenario.CheckError(t, err) } assertionInfo, err := scenario.ServiceProvider.RetrieveAssertionInfo(scenario.Response) if scenario.CheckError != nil { scenario.CheckError(t, err) } else { require.NoError(t, err) } if err == nil { if scenario.CheckWarningInfo != nil { scenario.CheckWarningInfo(t, assertionInfo.WarningInfo) } else { require.False(t, assertionInfo.WarningInfo.InvalidTime) require.False(t, assertionInfo.WarningInfo.NotInAudience) } } }) } }
Refactor for two factor authentification
package at.ac.tuwien.inso.service; import at.ac.tuwien.inso.controller.lecturer.GradeAuthorizationDTO; import at.ac.tuwien.inso.entity.*; import org.springframework.security.access.prepost.*; import org.springframework.stereotype.*; import java.util.*; @Service public interface GradeService { @PreAuthorize("hasRole('LECTURER')") GradeAuthorizationDTO getDefaultGradeAuthorizationDTOForStudentAndCourse(Long studentId, Long courseId); @PreAuthorize("hasRole('LECTURER')") Grade saveNewGradeForStudentAndCourse(GradeAuthorizationDTO grade); @PreAuthorize("hasRole('LECTURER')") List<Grade> getGradesForCourseOfLoggedInLecturer(Long courseId); @PreAuthorize("hasRole('STUDENT')") List<Grade> getGradesForLoggedInStudent(); Grade getForValidation(String identifier); @PreAuthorize("isAuthenticated()") List<Grade> findAllOfStudent(Student student); @PreAuthorize("isAuthenticated()") List<Mark> getMarkOptions(); }
package at.ac.tuwien.inso.service; import at.ac.tuwien.inso.entity.*; import org.springframework.security.access.prepost.*; import org.springframework.stereotype.*; import java.util.*; @Service public interface GradeService { @PreAuthorize("hasRole('LECTURER')") Grade getDefaultGradeForStudentAndCourse(Long studentId, Long courseId); @PreAuthorize("hasRole('LECTURER')") Grade saveNewGradeForStudentAndCourse(Grade grade); @PreAuthorize("hasRole('LECTURER')") List<Grade> getGradesForCourseOfLoggedInLecturer(Long courseId); @PreAuthorize("hasRole('STUDENT')") List<Grade> getGradesForLoggedInStudent(); Grade getForValidation(String identifier); @PreAuthorize("isAuthenticated()") List<Grade> findAllOfStudent(Student student); }
Add Laravel Scout user agent to Algolia queries
<?php namespace Laravel\Scout; use Illuminate\Support\Manager; use AlgoliaSearch\Client as Algolia; use AlgoliaSearch\Version as AlgoliaUserAgent; use Laravel\Scout\Engines\NullEngine; use Laravel\Scout\Engines\AlgoliaEngine; class EngineManager extends Manager { /** * Get a driver instance. * * @param string|null $name * @return mixed */ public function engine($name = null) { return $this->driver($name); } /** * Create an Algolia engine instance. * * @return \Laravel\Scout\Engines\AlgoliaEngine */ public function createAlgoliaDriver() { AlgoliaUserAgent::$custom_value = '; Laravel Scout integration'; return new AlgoliaEngine(new Algolia( config('scout.algolia.id'), config('scout.algolia.secret') )); } /** * Create a Null engine instance. * * @return \Laravel\Scout\Engines\NullEngine */ public function createNullDriver() { return new NullEngine; } /** * Get the default session driver name. * * @return string */ public function getDefaultDriver() { return $this->app['config']['scout.driver']; } }
<?php namespace Laravel\Scout; use Illuminate\Support\Manager; use AlgoliaSearch\Client as Algolia; use Laravel\Scout\Engines\NullEngine; use Laravel\Scout\Engines\AlgoliaEngine; class EngineManager extends Manager { /** * Get a driver instance. * * @param string|null $name * @return mixed */ public function engine($name = null) { return $this->driver($name); } /** * Create an Algolia engine instance. * * @return \Laravel\Scout\Engines\AlgoliaEngine */ public function createAlgoliaDriver() { return new AlgoliaEngine(new Algolia( config('scout.algolia.id'), config('scout.algolia.secret') )); } /** * Create a Null engine instance. * * @return \Laravel\Scout\Engines\NullEngine */ public function createNullDriver() { return new NullEngine; } /** * Get the default session driver name. * * @return string */ public function getDefaultDriver() { return $this->app['config']['scout.driver']; } }
Convert bmp to byte array
// Get JAFFE database from http://www.kasrl.org/jaffe_info.html // Extract pics in folder named "jaffe" // package image_test; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class svq { public static void main(String[] args) { // read image BufferedImage input = null; try { input = ImageIO.read(new File("jaffe/KA.AN1.39.tiff.bmp")); } catch (IOException e) { throw new RuntimeException(e); } // to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write( input, "bmp", baos ); baos.flush(); } catch (IOException e) { } byte[] bytearray = baos.toByteArray(); System.out.println("Done!"); } }
// Get JAFFE database from http://www.kasrl.org/jaffe_info.html // Extract pics in folder named "jaffe" // package image_test; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class svq { public static void main(String[] args) { // read image BufferedImage input = null; try { input = ImageIO.read(new File("jaffe/KA.AN1.39.tiff.bmp")); } catch (IOException e) { throw new RuntimeException(e); } System.out.println("Done!"); } }
Trim unnecessary interactive prop from tooltip
import React from 'react'; import {Tooltip} from 'reactjs-components'; import Icon from '../Icon'; const FormGroupContainer = (props) => { let removeButton = null; if (props.onRemove != null) { removeButton = ( <div className="form-group-container-action-button-group"> <Tooltip content="Delete" maxWidth={300} scrollContainer=".gm-scroll-view" wrapText={true}> <a className="button button-primary-link" onClick={props.onRemove}> <Icon id="close" color="grey" size="tiny" family="tiny"/> </a> </Tooltip> </div> ); } return ( <div className="panel pod-short"> <div className="pod-narrow pod-short"> {removeButton} {props.children} </div> </div> ); }; FormGroupContainer.defaultProps = { onRemove: null }; FormGroupContainer.propTypes = { children: React.PropTypes.node, onRemove: React.PropTypes.func }; module.exports = FormGroupContainer;
import React from 'react'; import {Tooltip} from 'reactjs-components'; import Icon from '../Icon'; const FormGroupContainer = (props) => { let removeButton = null; if (props.onRemove != null) { removeButton = ( <div className="form-group-container-action-button-group"> <Tooltip content="Delete" interactive={true} maxWidth={300} scrollContainer=".gm-scroll-view" wrapText={true}> <a className="button button-primary-link" onClick={props.onRemove}> <Icon id="close" color="grey" size="tiny" family="tiny"/> </a> </Tooltip> </div> ); } return ( <div className="panel pod-short"> <div className="pod-narrow pod-short"> {removeButton} {props.children} </div> </div> ); }; FormGroupContainer.defaultProps = { onRemove: null }; FormGroupContainer.propTypes = { children: React.PropTypes.node, onRemove: React.PropTypes.func }; module.exports = FormGroupContainer;
Update comments to properly run the test
function hex2bin(s) { // discuss at: http://phpjs.org/functions/hex2bin/ // original by: Dumitru Uzun (http://duzun.me) // example 1: hex2bin('44696d61'); // returns 1: 'Dima' // example 2: hex2bin('00'); // returns 2: '\x00' // example 3: hex2bin('2f1q') // returns 3: false var ret = [], i = 0, l; s += ''; for ( l = s.length ; i < l; i+=2 ) { var c = parseInt(s.substr(i, 1), 16); var k = parseInt(s.substr(i+1, 1), 16); if(isNaN(c) || isNaN(k)) return false; ret.push( (c << 4) | k ); } return String.fromCharCode.apply(String, ret); }
function hex2bin(s) { // discuss at: http://phpjs.org/functions/hex2bin/ // original by: Dumitru Uzun (http://duzun.me) // example 1: bin2hex('44696d61'); // returns 1: 'Dima' // example 2: bin2hex('00'); // returns 2: '\x00' // example 3: bin2hex('2f1q') // returns 3: false var ret = [], i = 0, l; s += ''; for ( l = s.length ; i < l; i+=2 ) { var c = parseInt(s.substr(i, 1), 16); var k = parseInt(s.substr(i+1, 1), 16); if(isNaN(c) || isNaN(k)) return false; ret.push( (c << 4) | k ); } return String.fromCharCode.apply(String, ret); }
Select search text on click
'use strict'; import React from 'react/addons'; import Icon from './Icon.js'; import LeftColumnActions from '../actions/LeftColumnActions.js'; import SearchActions from '../actions/SearchActions.js'; class MenuButton extends React.Component { constructor(props) { super(props); this._onClick = this._onClick.bind(this); } render() { return ( <div className="menu-button" onClick={this._onClick}> <Icon icon="menu-hamburger"/> </div> ); } _onClick() { LeftColumnActions.toggleVisibility(); } } export default class Top extends React.Component { constructor(props) { super(props); this._onChange = this._onChange.bind(this); this._onClick = this._onClick.bind(this); } render() { return ( <div> <MenuButton /> <div className="search"> <Icon icon="search" /> <input type="text" name="search" placeholder="Search Music" onChange={this._onChange} onClick={this._onClick} /> </div> </div> ); } _onChange(e) { SearchActions.search(e.currentTarget.value); } _onClick(e) { e.currentTarget.select(); } }
'use strict'; import React from 'react/addons'; import Icon from './Icon.js'; import LeftColumnActions from '../actions/LeftColumnActions.js'; import SearchActions from '../actions/SearchActions.js'; class MenuButton extends React.Component { constructor(props) { super(props); this._onClick = this._onClick.bind(this); } render() { return ( <div className="menu-button" onClick={this._onClick}> <Icon icon="menu-hamburger"/> </div> ); } _onClick() { LeftColumnActions.toggleVisibility(); } } export default class Top extends React.Component { constructor(props) { super(props); this._onChange = this._onChange.bind(this); } render() { return ( <div> <MenuButton /> <div className="search"> <Icon icon="search" /> <input type="text" name="search" placeholder="Search Music" onChange={this._onChange} /> </div> </div> ); } _onChange(e) { SearchActions.search(e.currentTarget.value); } }
Allow other_paths to be passed into TraceViewerProject This allows external embedders to subclass TraceViewerProject and thus use trace viewer.
# Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import os from tvcm import project as project_module class TraceViewerProject(project_module.Project): trace_viewer_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..')) src_path = os.path.abspath(os.path.join( trace_viewer_path, 'trace_viewer')) trace_viewer_third_party_path = os.path.abspath(os.path.join( trace_viewer_path, 'third_party')) jszip_path = os.path.abspath(os.path.join( trace_viewer_third_party_path, 'jszip')) test_data_path = os.path.join(trace_viewer_path, 'test_data') skp_data_path = os.path.join(trace_viewer_path, 'skp_data') def __init__(self, other_paths=None): paths = [self.src_path, self.jszip_path] if other_paths: paths.extend(other_paths) super(TraceViewerProject, self).__init__( paths)
# Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import os from tvcm import project as project_module class TraceViewerProject(project_module.Project): trace_viewer_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..')) src_path = os.path.abspath(os.path.join( trace_viewer_path, 'trace_viewer')) trace_viewer_third_party_path = os.path.abspath(os.path.join( trace_viewer_path, 'third_party')) jszip_path = os.path.abspath(os.path.join( trace_viewer_third_party_path, 'jszip')) test_data_path = os.path.join(trace_viewer_path, 'test_data') skp_data_path = os.path.join(trace_viewer_path, 'skp_data') def __init__(self): super(TraceViewerProject, self).__init__( [self.src_path, self.jszip_path])
Add communicator split to forking test.
#!/usr/bin/env python from __future__ import absolute_import, division, print_function, unicode_literals, with_statement from mpi4py import MPI import sys import os import numpy as np import scipy as sc from astropy.io import fits import argparse import subprocess as sp import pympit as pt parser = argparse.ArgumentParser(description='Run an MPI test in python with subprocess forking') args = parser.parse_args() comm = MPI.COMM_WORLD rank = comm.rank nproc = comm.size ngroup = int(nproc / 4) group = int(rank / ngroup) group_rank = rank % ngroup comm_group = comm.Split(color=group, key=group_rank) comm_rank = comm.Split(color=group_rank, key=group) start = MPI.Wtime() if group_rank == 0: print("Group {} of {} has {} processes".format(group+1, ngroup, comm_group.size)) comm_group.barrier() comm_rank.barrier() comm.barrier() local_out = [] proc = sp.Popen(['pympit_worker.py'], stdout=sp.PIPE, stderr=sp.PIPE) outs, errs = proc.communicate() proc.wait() local_out.append(outs) stop = MPI.Wtime() elapsed = stop - start comm.barrier() for p in range(comm.size): if p == comm.rank: print("proc {:02d} {:.3f}s:".format(p, elapsed)) for line in local_out: print(" {}".format(line.rstrip())) comm.barrier()
#!/usr/bin/env python from __future__ import absolute_import, division, print_function, unicode_literals, with_statement from mpi4py import MPI import sys import os import numpy as np import scipy as sc from astropy.io import fits import argparse import subprocess as sp import pympit as pt parser = argparse.ArgumentParser(description='Run an MPI test in python with subprocess forking') args = parser.parse_args() comm = MPI.COMM_WORLD start = MPI.Wtime() local_out = [] proc = sp.Popen(['pympit_worker.py'], stdout=sp.PIPE, stderr=sp.PIPE) outs, errs = proc.communicate() proc.wait() local_out.append(outs) stop = MPI.Wtime() elapsed = stop - start comm.Barrier() for p in range(comm.size): if p == comm.rank: print("proc {:02d} {:.3f}s:".format(p, elapsed)) for line in local_out: print(" {}".format(line.rstrip())) comm.Barrier()
react: Allow Dashboard `height` to accept a string with unit
const PropTypes = require('prop-types') const UppyCore = require('@uppy/core').Uppy // The `uppy` prop receives the Uppy core instance. const uppy = PropTypes.instanceOf(UppyCore).isRequired // A list of plugins to mount inside this component. const plugins = PropTypes.arrayOf(PropTypes.string) // Language strings for this component. const locale = PropTypes.shape({ strings: PropTypes.object, pluralize: PropTypes.func }) // List of meta fields for the editor in the Dashboard. const metaField = PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, placeholder: PropTypes.string }) const metaFields = PropTypes.arrayOf(metaField) // A size in pixels (number) or with some other unit (string). const cssSize = PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]) // Common props for dashboardy components (Dashboard and DashboardModal). const dashboard = { uppy, inline: PropTypes.bool, plugins, width: cssSize, height: cssSize, showProgressDetails: PropTypes.bool, hideUploadButton: PropTypes.bool, hideProgressAfterFinish: PropTypes.bool, note: PropTypes.string, metaFields, proudlyDisplayPoweredByUppy: PropTypes.bool, disableStatusBar: PropTypes.bool, disableInformer: PropTypes.bool, disableThumbnailGenerator: PropTypes.bool, locale } module.exports = { uppy, locale, dashboard }
const PropTypes = require('prop-types') const UppyCore = require('@uppy/core').Uppy // The `uppy` prop receives the Uppy core instance. const uppy = PropTypes.instanceOf(UppyCore).isRequired // A list of plugins to mount inside this component. const plugins = PropTypes.arrayOf(PropTypes.string) // Language strings for this component. const locale = PropTypes.shape({ strings: PropTypes.object, pluralize: PropTypes.func }) // List of meta fields for the editor in the Dashboard. const metaField = PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, placeholder: PropTypes.string }) const metaFields = PropTypes.arrayOf(metaField) // Common props for dashboardy components (Dashboard and DashboardModal). const dashboard = { uppy, inline: PropTypes.bool, plugins, width: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]), height: PropTypes.number, showProgressDetails: PropTypes.bool, hideUploadButton: PropTypes.bool, hideProgressAfterFinish: PropTypes.bool, note: PropTypes.string, metaFields, proudlyDisplayPoweredByUppy: PropTypes.bool, disableStatusBar: PropTypes.bool, disableInformer: PropTypes.bool, disableThumbnailGenerator: PropTypes.bool, locale } module.exports = { uppy, locale, dashboard }
Extend the IServerMessage thing instead
<?php /* WildPHP - a modular and easily extendable IRC bot written in PHP Copyright (C) 2015 WildPHP This program 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. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ namespace WildPHP\IRC; /** * Represents an incoming PRIVMSG command. */ template ICommandPRIVMSG extends IServerMessage { /** * Returns the sender name. * @return string Username of sender */ public function getSenderName(); /** * Returns the target user/channel name. * @return string Name of the target user/channel of this message. */ public function getTargetName(); /** * Returns the sender hostname. * @return string Hostname of sender. */ public function getSenderHostname(); /** * Returns the sent message. * @return string The message which was sent. */ public function getUserMessage(); }
<?php /* WildPHP - a modular and easily extendable IRC bot written in PHP Copyright (C) 2015 WildPHP This program 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. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ namespace WildPHP\IRC; /** * Represents an incoming PRIVMSG command. */ template ICommandPRIVMSG { /** * Returns the complete IRC message as it was received from the server. * @return string Full IRC message. */ public function getIRCMessage(); /** * Returns the sender name. * @return string Username of sender */ public function getSenderName(); /** * Returns the target user/channel name. * @return string Name of the target user/channel of this message. */ public function getTargetName(); /** * Returns the sender hostname. * @return string Hostname of sender. */ public function getSenderHostname(); /** * Returns the sent message. * @return string The message which was sent. */ public function getMessage(); }
Put the generator instanciation in the setUp
try: from unittest2 import TestCase except ImportError: from unittest import TestCase # flake8: noqa import six from mock import patch from daybed.backends.id_generators import KoremutakeGenerator class KoremutakeGeneratorTest(TestCase): def setUp(self): self.generator = KoremutakeGenerator() def test_it_defaults_the_max_bytes_to_4(self): self.assertEquals(generator.max_bytes, 4) @patch('koremutake.encode') def test_it_doesnt_reuse_a_name_twice(self, encode): encode.side_effect = ['existing-value', 'new-value'] created = ['existing-value'] def _exists(key): return key in created self.assertEquals(self.generator(key_exist=_exists), 'new-value') def test_it_returns_a_string_with_a_max_size(self): uid = self.generator() self.assertTrue(len(uid) <= 24) self.assertIsInstance(uid, six.text_type)
try: from unittest2 import TestCase except ImportError: from unittest import TestCase # flake8: noqa import six from mock import patch from daybed.backends.id_generators import KoremutakeGenerator class KoremutakeGeneratorTest(TestCase): def test_it_defaults_the_max_bytes_to_4(self): generator = KoremutakeGenerator() self.assertEquals(generator.max_bytes, 4) @patch('koremutake.encode') def test_it_doesnt_reuse_a_name_twice(self, encode): encode.side_effect = ['existing-value', 'new-value'] created = ['existing-value'] def _exists(key): return key in created generator = KoremutakeGenerator() self.assertEquals(generator(key_exist=_exists), 'new-value') def test_it_returns_a_string_with_a_max_size(self): generator = KoremutakeGenerator() uid = generator() self.assertTrue(len(uid) <= 24) self.assertIsInstance(uid, six.text_type)
Enable exportNamespaceFrom plugin for Babylon parser.
"use strict"; const babylon = require("babylon"); exports.options = { allowImportExportEverywhere: true, allowReturnOutsideFunction: true, plugins: [ "*", "flow", "jsx", // The "*" glob no longer seems to include the following plugins: "asyncGenerators", "bigInt", "classPrivateMethods", "classPrivateProperties", "classProperties", "decorators", "doExpressions", "dynamicImport", "exportDefaultFrom", "exportExtensions", "exportNamespaceFrom", "functionBind", "functionSent", "importMeta", "nullishCoalescingOperator", "numericSeparator", "objectRestSpread", "optionalCatchBinding", "optionalChaining", "pipelineOperator", "throwExpressions", // Other experimental plugins that we could enable: // https://github.com/babel/babylon#plugins ], sourceType: "module", strictMode: false }; function parse(code) { return babylon.parse(code, exports.options); } exports.parse = parse;
"use strict"; const babylon = require("babylon"); exports.options = { allowImportExportEverywhere: true, allowReturnOutsideFunction: true, plugins: [ "*", "flow", "jsx", // The "*" glob no longer seems to include the following plugins: "asyncGenerators", "bigInt", "classPrivateMethods", "classPrivateProperties", "classProperties", "decorators", "doExpressions", "dynamicImport", "exportExtensions", "exportDefaultFrom", "functionBind", "functionSent", "importMeta", "nullishCoalescingOperator", "numericSeparator", "objectRestSpread", "optionalCatchBinding", "optionalChaining", "pipelineOperator", "throwExpressions", // Other experimental plugins that we could enable: // https://github.com/babel/babylon#plugins ], sourceType: "module", strictMode: false }; function parse(code) { return babylon.parse(code, exports.options); } exports.parse = parse;
Add back fail_state to context manager
from .models import System class transition(object): "Transition context manager." def __init__(self, obj, state, event=None, start_time=None, message=None, exception_fail=True, fail_state='Fail'): self.system = System.get(obj) self.transition = self.system.start_transition(event=event, start_time=start_time) self.state = state self.message = message self.exception_fail = exception_fail self.fail_state = fail_state def __enter__(self): return self.transition def __exit__(self, exc_type, exc_value, traceback): if exc_type and self.exception_fail: failed = True else: failed = False # Use the locally set message message = self.transition.message or self.message state = self.fail_state if failed else self.state # End the transition self.system.end_transition(state, message=message, failed=failed)
from .models import System class transition(object): "Transition context manager." def __init__(self, obj, state, event=None, start_time=None, message=None, exception_fail=True): self.system = System.get(obj) self.transition = self.system.start_transition(event=event, start_time=start_time) self.state = state self.message = message self.exception_fail = exception_fail def __enter__(self): return self.transition def __exit__(self, exc_type, exc_value, traceback): if exc_type and self.exception_fail: failed = True else: failed = None # Use the locally set message message = self.transition.message or self.message # End the transition self.system.end_transition(self.state, message=message, failed=failed)
Change my email to avoid Yahoo, which decided to brake my scraper script recently.
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- from setuptools import setup setup( name = 'TracMasterTickets', version = '2.1.1', packages = ['mastertickets'], package_data = { 'mastertickets': ['templates/*.html', 'htdocs/*.js', 'htdocs/*.css' ] }, author = "Noah Kantrowitz", author_email = "noah@coderanger.net", description = "Provides support for ticket dependencies and master tickets.", license = "BSD", keywords = "trac plugin ticket dependencies master", url = "http://trac-hacks.org/wiki/MasterTicketsPlugin", classifiers = [ 'Framework :: Trac', ], install_requires = ['Trac', 'Genshi >= 0.5.dev-r698,==dev'], entry_points = { 'trac.plugins': [ 'mastertickets.web_ui = mastertickets.web_ui', 'mastertickets.api = mastertickets.api', ] } )
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- from setuptools import setup setup( name = 'TracMasterTickets', version = '2.1.1', packages = ['mastertickets'], package_data = { 'mastertickets': ['templates/*.html', 'htdocs/*.js', 'htdocs/*.css' ] }, author = "Noah Kantrowitz", author_email = "coderanger@yahoo.com", description = "Provides support for ticket dependencies and master tickets.", license = "BSD", keywords = "trac plugin ticket dependencies master", url = "http://trac-hacks.org/wiki/MasterTicketsPlugin", classifiers = [ 'Framework :: Trac', ], install_requires = ['Trac', 'Genshi >= 0.5.dev-r698,==dev'], entry_points = { 'trac.plugins': [ 'mastertickets.web_ui = mastertickets.web_ui', 'mastertickets.api = mastertickets.api', ] } )
Add -lm as floor() is used This fixes build on armv7hl: /usr/bin/ld: build/temp.linux-armv8l-3.10/src/numbers.o: in function `_PyFloat_is_Intlike': /home/iurt/rpmbuild/BUILD/fastnumbers-3.2.1/src/numbers.c:69: undefined reference to `floor'
#! /usr/bin/env python # -*- coding: utf-8 -*- # Std lib imports import glob import os # Non-std lib imports from setuptools import Extension, find_packages, setup # Define how to build the extension module. # All other data is in the setup.cfg file. setup( name="fastnumbers", version="3.2.1", python_requires=">=3.6", packages=find_packages(where="src"), package_dir={"": "src"}, package_data={"fastnumbers": ["py.typed", "*.pyi"]}, zip_safe=False, ext_modules=[ Extension( "fastnumbers.fastnumbers", sorted(glob.glob("src/*.c")), include_dirs=[os.path.abspath(os.path.join("include"))], extra_compile_args=[], extra_link_args=["-lm"], ) ], )
#! /usr/bin/env python # -*- coding: utf-8 -*- # Std lib imports import glob import os # Non-std lib imports from setuptools import Extension, find_packages, setup # Define how to build the extension module. # All other data is in the setup.cfg file. setup( name="fastnumbers", version="3.2.1", python_requires=">=3.6", packages=find_packages(where="src"), package_dir={"": "src"}, package_data={"fastnumbers": ["py.typed", "*.pyi"]}, zip_safe=False, ext_modules=[ Extension( "fastnumbers.fastnumbers", sorted(glob.glob("src/*.c")), include_dirs=[os.path.abspath(os.path.join("include"))], extra_compile_args=[], ) ], )
Change from Oc Sms ---> SMS Looks cleaner and more like the design.
<?php /** * ownCloud - ocsms * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Loic Blot <loic.blot@unix-experience.fr> * @copyright Loic Blot 2014 */ namespace OCA\OcSms\AppInfo; \OCP\App::addNavigationEntry(array( // the string under which your app will be referenced in owncloud 'id' => 'ocsms', // sorting weight for the navigation. The higher the number, the higher // will it be listed in the navigation 'order' => 10, // the route that will be shown on startup 'href' => \OCP\Util::linkToRoute('ocsms.sms.index'), // the icon that will be shown in the navigation // this file needs to exist in img/ 'icon' => \OCP\Util::imagePath('ocsms', 'app.svg'), // the title of your application. This will be used in the // navigation or on the settings page of your app 'name' => \OCP\Util::getL10N('ocsms')->t('SMS') ));
<?php /** * ownCloud - ocsms * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Loic Blot <loic.blot@unix-experience.fr> * @copyright Loic Blot 2014 */ namespace OCA\OcSms\AppInfo; \OCP\App::addNavigationEntry(array( // the string under which your app will be referenced in owncloud 'id' => 'ocsms', // sorting weight for the navigation. The higher the number, the higher // will it be listed in the navigation 'order' => 10, // the route that will be shown on startup 'href' => \OCP\Util::linkToRoute('ocsms.sms.index'), // the icon that will be shown in the navigation // this file needs to exist in img/ 'icon' => \OCP\Util::imagePath('ocsms', 'app.svg'), // the title of your application. This will be used in the // navigation or on the settings page of your app 'name' => \OCP\Util::getL10N('ocsms')->t('Oc Sms') ));
Fix for new column names
#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.config import config from downstream_node.models import Challenges, Files from heartbeat import Heartbeat from downstream_node.startup import db __all__ = ['create_token', 'delete_token', 'add_file', 'remove_file', 'gen_challenges', 'update_challenges'] def create_token(*args, **kwargs): raise NotImplementedError def delete_token(*args, **kwargs): raise NotImplementedError def add_file(*args, **kwargs): raise NotImplementedError def remove_file(*args, **kwargs): raise NotImplementedError def gen_challenges(filepath, root_seed): secret = getattr(config, 'HEARTBEAT_SECRET') hb = Heartbeat(filepath, secret=secret) hb.generate_challenges(1000, root_seed) files = Files(name=filepath) db.session.add(files) for challenge in hb.challenges: chal = Challenges( filename=filepath, rootseed=root_seed, block=challenge.block, seed=challenge.seed, response=challenge.response, ) db.session.add(chal) db.session.commit() def update_challenges(*args, **kwargs): raise NotImplementedError
#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.config import config from downstream_node.models import Challenges from heartbeat import Heartbeat from downstream_node.startup import db __all__ = ['create_token', 'delete_token', 'add_file', 'remove_file', 'gen_challenges', 'update_challenges'] def create_token(*args, **kwargs): raise NotImplementedError def delete_token(*args, **kwargs): raise NotImplementedError def add_file(*args, **kwargs): raise NotImplementedError def remove_file(*args, **kwargs): raise NotImplementedError def gen_challenges(filepath, root_seed): secret = getattr(config, 'HEARTBEAT_SECRET') hb = Heartbeat(filepath, secret=secret) hb.generate_challenges(1000, root_seed) for challenge in hb.challenges: chal = Challenges( filepath=filepath, root_seed=root_seed, block=challenge.block, seed=challenge.seed, response=challenge.response, ) db.session.add(chal) db.session.commit() def update_challenges(*args, **kwargs): raise NotImplementedError
Add constant for Character Schema file path
"""This module loads character data from XML files and stores them in CharacterData objects that can be read by the game engine. Attributes: CHARACTER_LIST_PATH (String): The filepath for the text file which lists the paths to all of the characters' XML files. Each path is separated by a new-line. FILEPATH_PREFIX (String): The file path of the root directory where all character data files are kept. """ import os CHARACTER_LIST_PATH = 'characters/character_list.txt' CHARACTER_SCHEMA_PATH = os.path.join(os.path.dirname(os.path.realpath( __file__)), 'character.xsd') FILEPATH_PREFIX = 'characters/' def get_character_paths(): """Return a list of all of the filepaths to the XML files for playable characters. """ with open(CHARACTER_LIST_PATH) as f: character_path_list = [line.rstrip('\n') for line in f] return character_path_list
"""This module loads character data from XML files and stores them in CharacterData objects that can be read by the game engine. Attributes: CHARACTER_LIST_PATH (String): The filepath for the text file which lists the paths to all of the characters' XML files. Each path is separated by a new-line. FILEPATH_PREFIX (String): The file path of the root directory where all character data files are kept. """ CHARACTER_LIST_PATH = 'characters/character_list.txt' FILEPATH_PREFIX = 'characters/' def get_character_paths(): """Return a list of all of the filepaths to the XML files for playable characters. """ with open(CHARACTER_LIST_PATH) as f: character_path_list = [line.rstrip('\n') for line in f] return character_path_list
Fix for webpack es6 example loader
var path = require('path'); var webpackSettings = require('../../webpack-helper'); module.exports = webpackSettings({ entry: './js/app', output: { filename: './js/app.min.js', path: path.resolve('./js') }, resolve: { alias: { // Tungsten.js doesn't need jQuery, but backbone needs a subset of jQuery APIs. Backbone.native // implements tha minimum subset of required functionality 'jquery': 'backbone.native', // Aliases for the current version of tungstenjs above the ./examples directory. If // examples dir is run outside of main tungstenjs repo, remove these aliases // and use via normal modules directories (e.g., via NPM) 'tungstenjs/adaptors/backbone': path.join(__dirname, '../../adaptors/backbone'), 'tungstenjs/src/template/template': path.join(__dirname, '../../src/template/template'), 'tungstenjs': '../../src' } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), modulesDirectories: ['node_modules', path.join(__dirname, '../../node_modules/')] }, devtool: '#source-map', module: { loaders: [{test: /\.js$/, loader: 'babel?stage=0', exclude: /node_modules/}] } });
var path = require('path'); var webpackSettings = require('../../webpack-helper'); module.exports = webpackSettings({ entry: './js/app', output: { filename: './js/app.min.js', path: path.resolve('./js') }, resolve: { alias: { // Tungsten.js doesn't need jQuery, but backbone needs a subset of jQuery APIs. Backbone.native // implements tha minimum subset of required functionality 'jquery': 'backbone.native', // Aliases for the current version of tungstenjs above the ./examples directory. If // examples dir is run outside of main tungstenjs repo, remove these aliases // and use via normal modules directories (e.g., via NPM) 'tungstenjs/adaptors/backbone': path.join(__dirname, '../../adaptors/backbone'), 'tungstenjs/src/template/template': path.join(__dirname, '../../src/template/template'), 'tungstenjs': '../../src' } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), modulesDirectories: ['node_modules', path.join(__dirname, '../../node_modules/')] }, devtool: '#source-map', loaders: [{test: /\.js$/, loader: 'babel?stage=0', exclude: /node_modules/}] });
Fix bug in runtime.Caller() introduced by release.2010-03-30
// Copyright © 2009-2010 Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package gospec import ( "fmt" filepath "path" "runtime" ) type Location struct { File string Line int } func currentLocation() *Location { return newLocation(1) } func callerLocation() *Location { return newLocation(2) } func newLocation(n int) *Location { if _, file, line, ok := runtime.Caller(n + 2); ok { // TODO: is the change from n+1 to n+2 a bug in runtime.Caller or not? return &Location{filename(file), line} } return nil } func filename(path string) string { _, file := filepath.Split(path) return file } func (this *Location) equals(that *Location) bool { return this.File == that.File && this.Line == that.Line } func (this *Location) String() string { if this == nil { return "Unknown File" } return fmt.Sprintf("%v:%v", this.File, this.Line) }
// Copyright © 2009-2010 Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package gospec import ( "fmt" filepath "path" "runtime" ) type Location struct { File string Line int } func currentLocation() *Location { return newLocation(1) } func callerLocation() *Location { return newLocation(2) } func newLocation(n int) *Location { if _, file, line, ok := runtime.Caller(n + 1); ok { return &Location{filename(file), line} } return nil } func filename(path string) string { _, file := filepath.Split(path) return file } func (this *Location) equals(that *Location) bool { return this.File == that.File && this.Line == that.Line } func (this *Location) String() string { if this == nil { return "Unknown File" } return fmt.Sprintf("%v:%v", this.File, this.Line) }
Make sure to type hint to Configuration Allowing ConfigInterface will just make the code fail when initiating a Driver. The Driver needs a Configuration
<?php /* * This file is part of the GraphAware Bolt package. * * (c) Graph Aware Limited <http://graphaware.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GraphAware\Bolt; use GraphAware\Common\Driver\ConfigInterface; use GraphAware\Common\GraphDatabaseInterface; class GraphDatabase implements GraphDatabaseInterface { /** * @param string $uri * @param Configuration|null $config * * @return Driver */ public static function driver($uri, ConfigInterface $config = null) { return new Driver(self::formatUri($uri), $config); } /** * @param string $uri * * @return string */ private static function formatUri($uri) { return str_replace('bolt://', '', $uri); } }
<?php /* * This file is part of the GraphAware Bolt package. * * (c) Graph Aware Limited <http://graphaware.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GraphAware\Bolt; use GraphAware\Common\Driver\ConfigInterface; use GraphAware\Common\GraphDatabaseInterface; class GraphDatabase implements GraphDatabaseInterface { /** * @param string $uri * @param ConfigInterface|null $config * * @return Driver */ public static function driver($uri, ConfigInterface $config = null) { return new Driver(self::formatUri($uri), $config); } /** * @param string $uri * * @return string */ private static function formatUri($uri) { return str_replace('bolt://', '', $uri); } }
Make all right with the world
import Ember from 'ember'; var dateCreated = new Date(); var meta = { title: 'The Linux Command Line', authors: 'Zach Janicki', dateCreated: dateCreated, abstract: "This is a sample usage of the MFR on the preprint server. This document will teach you everything you would ever want to know about the linux command line. Enjoy!" + " From here on out this is just filler text to give a better sense of what the page layout may look like with a more real to life abstract length. Hopefully the scientists" + " who write these abstracts have more to day about their own topics than I do about the linux command line...", publisher: "Linus Torvalds", project: "http://localhost:5000/re58y/", supplementalMaterials: "NONE", figures: "NONE", License: "Mit License", link: "https://test-mfr.osf.io/render?url=https://test.osf.io/yr6ch/?action=download%26mode=render", }; export default Ember.Route.extend({ model() { console.log(this.store.findAll('preprint')); //return this.store.findRecord('preprint', 1); return meta; } }); // // 'https://test-mfr.osf.io/export?url=https://test.osf.io/2r4cz/?action=download%26direct%26mode=render&initialWidth=755&childId=mfrIframe&format=pdf' // // 'https://test-mfr.osf.io/export?url=https://test.osf.io/2r4cz/?action=download%26direct%26mode=render&initialWidth=755&childId=mfrIframe&format=pdf'
import Ember from 'ember'; var dateCreated = new Date(); var meta = { title: 'The Linux Command Line', authors: 'Zach Janicki', dateCreated: dateCreated, abstract: "This is a sample usage of the MFR on the preprint server. This document will teach you everything you would ever want to know about the linux command line. Enjoy!" + " From here on out this is just filler text to give a better sense of what the page layout may look like with a more real to life abstract length. Hopefully the scientists" + " who write these abstracts have more to day about their own topics than I do about the linux command line...", publisher: "Linus Torvalds", project: "http://localhost:5000/re58y/", supplementalMaterials: "NONE", figures: "NONE", License: "Mit License", link: 'http://localhost:7778/render?url=http://localhost:5000/sqdwh/?action=download%26mode=render', }; export default Ember.Route.extend({ model() { console.log(this.store.findAll('preprint')); //return this.store.findRecord('preprint', 1); return meta; } });
Include is_odata_config in brief exports Apparently the old version of the dbaccessors weren't actually respecting include_docs=False - they returned the full, wrapped instances.
function(doc) { if (doc.doc_type === "FormExportInstance" || doc.doc_type === "CaseExportInstance") { emit([doc.domain, doc.doc_type, doc.is_deidentified], { _id: doc._id, domain: doc.domain, doc_type: doc.doc_type, is_deidentified: doc.is_deidentified, is_daily_saved_export: doc.is_daily_saved_export, is_odata_config: doc.is_odata_config, export_format: doc.export_format, name: doc.name, owner_id: doc.owner_id, sharing: doc.sharing, }); } }
function(doc) { if (doc.doc_type === "FormExportInstance" || doc.doc_type === "CaseExportInstance") { emit([doc.domain, doc.doc_type, doc.is_deidentified], { _id: doc._id, domain: doc.domain, doc_type: doc.doc_type, is_deidentified: doc.is_deidentified, is_daily_saved_export: doc.is_daily_saved_export, export_format: doc.export_format, name: doc.name, owner_id: doc.owner_id, sharing: doc.sharing, }); } }
Disable comment stripping within cssnano Stylus already strips non-important comments, so we can now keep the copyright information.
var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var stylus = require('gulp-stylus'); var rename = require('gulp-rename'); var nib = require('nib'); var cssnano = require('gulp-cssnano'); var mainStyl = './styl/main.styl'; gulp.task('build:dev', function() { gulp.src(mainStyl) .pipe(sourcemaps.init()) .pipe(stylus({ use: nib() })) .pipe(sourcemaps.write()) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/development')); }); gulp.task('build:prod', function() { gulp.src(mainStyl) .pipe(stylus({ use: nib() })) .pipe(cssnano({ discardComments: false })) .pipe(rename('baremetal.min.css')) .pipe(gulp.dest('./build/production')); gulp.src(mainStyl) .pipe(stylus({ use: nib() })) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/production')); }); gulp.task('stylus:watch', function() { gulp.watch('./styl/**/*.styl', ['build:dev']); }); gulp.task('watch', ['build:dev', 'stylus:watch']); gulp.task('default', ['build:dev', 'build:prod']);
var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var stylus = require('gulp-stylus'); var rename = require('gulp-rename'); var nib = require('nib'); var cssnano = require('gulp-cssnano'); var mainStyl = './styl/main.styl'; gulp.task('build:dev', function() { gulp.src(mainStyl) .pipe(sourcemaps.init()) .pipe(stylus({ use: nib() })) .pipe(sourcemaps.write()) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/development')); }); gulp.task('build:prod', function() { gulp.src(mainStyl) .pipe(stylus({ use: nib() })) .pipe(cssnano()) .pipe(rename('baremetal.min.css')) .pipe(gulp.dest('./build/production')); gulp.src(mainStyl) .pipe(stylus({ use: nib() })) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/production')); }); gulp.task('stylus:watch', function() { gulp.watch('./styl/**/*.styl', ['build:dev']); }); gulp.task('watch', ['build:dev', 'stylus:watch']); gulp.task('default', ['build:dev', 'build:prod']);
Use the correct user ID to show the user from the profiles view. Fixes %61.
from signbank.registration.models import * from django.contrib import admin from django.core.urlresolvers import reverse class UserProfileAdmin(admin.ModelAdmin): list_display = ['user', 'permissions', 'best_describes_you', 'australian', 'auslan_user', 'deaf', 'researcher_credentials'] readonly_fields = ['user', 'australian', 'auslan_user', 'deaf', 'yob', 'postcode', 'best_describes_you', 'researcher_credentials', 'learned', 'schooltype', 'school', 'teachercomm'] list_filter = ['australian', 'auslan_user', 'deaf'] def permissions(self, obj): url = reverse('admin:auth_user_change', args=(obj.user.id,)) return '<a href="%s">View user</a>' % (url) permissions.allow_tags = True admin.site.register(UserProfile, UserProfileAdmin)
from signbank.registration.models import * from django.contrib import admin from django.core.urlresolvers import reverse class UserProfileAdmin(admin.ModelAdmin): list_display = ['user', 'permissions', 'best_describes_you', 'australian', 'auslan_user', 'deaf', 'researcher_credentials'] readonly_fields = ['user', 'australian', 'auslan_user', 'deaf', 'yob', 'postcode', 'best_describes_you', 'researcher_credentials', 'learned', 'schooltype', 'school', 'teachercomm'] list_filter = ['australian', 'auslan_user', 'deaf'] def permissions(self, obj): url = reverse('admin:auth_user_change', args=(obj.pk,)) return '<a href="%s">View user</a>' % (url) permissions.allow_tags = True admin.site.register(UserProfile, UserProfileAdmin)
Revert "remove not null constraint" This reverts commit 32f5c29a23341c4f1dd6c1241a751201ce286430.
package com.bazaarvoice.dropwizard.assets; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotNull; import java.util.Map; public class AssetsConfiguration { @NotNull @JsonProperty private String cacheSpec = ConfiguredAssetsBundle.DEFAULT_CACHE_SPEC.toParsableString(); @NotNull @JsonProperty private Map<String, String> overrides = Maps.newHashMap(); @NotNull @JsonProperty private Map<String, String> mimeTypes = Maps.newHashMap(); /** The caching specification for how to memoize assets. */ public String getCacheSpec() { return cacheSpec; } public Iterable<Map.Entry<String, String>> getOverrides() { return Iterables.unmodifiableIterable(overrides.entrySet()); } public Iterable<Map.Entry<String, String>> getMimeTypes() { return Iterables.unmodifiableIterable(mimeTypes.entrySet()); } }
package com.bazaarvoice.dropwizard.assets; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotNull; import java.util.Map; public class AssetsConfiguration { @NotNull @JsonProperty private String cacheSpec = ConfiguredAssetsBundle.DEFAULT_CACHE_SPEC.toParsableString(); @NotNull @JsonProperty private Map<String, String> overrides = Maps.newHashMap(); @JsonProperty private Map<String, String> mimeTypes = Maps.newHashMap(); /** The caching specification for how to memoize assets. */ public String getCacheSpec() { return cacheSpec; } public Iterable<Map.Entry<String, String>> getOverrides() { return Iterables.unmodifiableIterable(overrides.entrySet()); } public Iterable<Map.Entry<String, String>> getMimeTypes() { return Iterables.unmodifiableIterable(mimeTypes.entrySet()); } }
uninstall: Remove extraneous warns when removing a symlink Don't warn about not acting on a module in a symlink when the module's parent is being removed anyway
'use strict' var path = require('path') var validate = require('aproba') var log = require('npmlog') var getPackageId = require('./get-package-id.js') module.exports = function (top, differences, next) { validate('SAF', arguments) var action var keep = [] differences.forEach(function (action) { var cmd = action[0] var pkg = action[1] if (cmd === 'remove') { pkg.removing = true } }) /*eslint no-cond-assign:0*/ while (action = differences.shift()) { var cmd = action[0] var pkg = action[1] if (pkg.isInLink || pkg.parent.target || pkg.parent.isLink) { // we want to skip warning if this is a child of another module that we're removing if (!pkg.parent.removing) { log.warn('skippingAction', 'Module is inside a symlinked module: not running ' + cmd + ' ' + getPackageId(pkg) + ' ' + path.relative(top, pkg.path)) } } else { keep.push(action) } } differences.push.apply(differences, keep) next() }
'use strict' var path = require('path') var validate = require('aproba') var log = require('npmlog') var getPackageId = require('./get-package-id.js') module.exports = function (top, differences, next) { validate('SAF', arguments) var action var keep = [] /*eslint no-cond-assign:0*/ while (action = differences.shift()) { var cmd = action[0] var pkg = action[1] if (pkg.isInLink || pkg.parent.target) { log.warn('skippingAction', 'Module is inside a symlinked module: not running ' + cmd + ' ' + getPackageId(pkg) + ' ' + path.relative(top, pkg.path)) } else { keep.push(action) } } differences.push.apply(differences, keep) next() }
Fix URL for fetch CJSON
import requests import json from subprocess import Popen, PIPE import tempfile import os import sys config = {} with open ('../config/conversion.json') as fp: config = json.load(fp) def to_cml(inchi): request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi) request = requests.get(request_url) if request.status_code == 200: cjson = request.json(); else: print >> sys.stderr, "Unable to access REST API at %s: %s" % (request_url, request.status_code) return None # Call convertion routine p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(json.dumps(cjson['results'][0])) fd, path = tempfile.mkstemp(suffix='.cml') with open(path, 'w') as fp: fp.write(str(stdout)) os.close(fd) return path
import requests import json from subprocess import Popen, PIPE import tempfile import os import sys config = {} with open ('../config/conversion.json') as fp: config = json.load(fp) def to_cml(inchi): request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi)) if request.status_code == 200: cjson = request.json(); else: print >> sys.stderr, "Unable to access REST API: %s" % request.status_code return None # Call convertion routine p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(json.dumps(cjson['results'][0])) fd, path = tempfile.mkstemp(suffix='.cml') with open(path, 'w') as fp: fp.write(str(stdout)) os.close(fd) return path
Remove the plottable typings todo as it is currently a good solution Change: 130777731
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 gulp = require('gulp'); var ts = require('gulp-typescript'); var typescript = require('typescript'); var gutil = require('gulp-util'); var filter = require('gulp-filter'); var merge = require('merge2'); var tsProject = ts.createProject('./tsconfig.json', { typescript: typescript, noExternalResolve: true, // opt-in for faster compilation! }); module.exports = function() { var isComponent = filter([ 'components/tf-*/**/*.ts', 'components/vz-*/**/*.ts', 'typings/**/*.ts', 'components/plottable/plottable.d.ts' ]); return tsProject.src() .pipe(isComponent) .pipe(ts(tsProject)) .js .pipe(gulp.dest('.')); }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 gulp = require('gulp'); var ts = require('gulp-typescript'); var typescript = require('typescript'); var gutil = require('gulp-util'); var filter = require('gulp-filter'); var merge = require('merge2'); var tsProject = ts.createProject('./tsconfig.json', { typescript: typescript, noExternalResolve: true, // opt-in for faster compilation! }); module.exports = function() { var isComponent = filter([ 'components/tf-*/**/*.ts', 'components/vz-*/**/*.ts', 'typings/**/*.ts', // TODO(danmane): add plottable to the typings registry after updating it // and remove this. 'components/plottable/plottable.d.ts' ]); return tsProject.src() .pipe(isComponent) .pipe(ts(tsProject)) .js .pipe(gulp.dest('.')); }
Update spec to no longer expect label text on intervention plot bands
describe("InterventionPlotBand", function() { describe(".toHighChartsDate", function() { describe("good input", function() { it("returns a correct JavaScript UTC date for HighCharts", function() { var input = { year: 2015, month: 8, day: 14 }; var high_charts_date = InterventionPlotBand.toHighChartsDate(input); expect(high_charts_date).toEqual(1439510400000); expect(new Date(high_charts_date).toGMTString()).toEqual('Fri, 14 Aug 2015 00:00:00 GMT'); }); }); }); describe("#toHighCharts", function() { describe("good input", function() { it("returns a correct HighCharts configuration", function() { var attributes = { name: "Extra math help", start_date: { year: 2015, month: 8, day: 14 }, end_date: { year: 2015, month: 8, day: 15 } }; var intervention_plot_band = new InterventionPlotBand(attributes); var to_highcharts = intervention_plot_band.toHighCharts(); expect(to_highcharts.from).toEqual(1439510400000); expect(to_highcharts.to).toEqual(1439596800000); }); }); }); });
describe("InterventionPlotBand", function() { describe(".toHighChartsDate", function() { describe("good input", function() { it("returns a correct JavaScript UTC date for HighCharts", function() { var input = { year: 2015, month: 8, day: 14 }; var high_charts_date = InterventionPlotBand.toHighChartsDate(input); expect(high_charts_date).toEqual(1439510400000); expect(new Date(high_charts_date).toGMTString()).toEqual('Fri, 14 Aug 2015 00:00:00 GMT'); }); }); }); describe("#toHighCharts", function() { describe("good input", function() { it("returns a correct HighCharts configuration", function() { var attributes = { name: "Extra math help", start_date: { year: 2015, month: 8, day: 14 }, end_date: { year: 2015, month: 8, day: 15 } }; var intervention_plot_band = new InterventionPlotBand(attributes); var to_highcharts = intervention_plot_band.toHighCharts(); expect(to_highcharts.label.text).toEqual('Extra math help'); expect(to_highcharts.from).toEqual(1439510400000); expect(to_highcharts.to).toEqual(1439596800000); }); }); }); });
Add method to check for the SN in the HDF5 file
import tables as tb hdf5_filename = 'hdf5/sn_data.h5' class SN(object): """A supernova is the explosion that ends the life of a star The SN needs to be conatained within the HDF5 database before it is used by SNoBoL. Once there, simply create a supernova by calling the constructor with the name of the SN as a string of the form "sn[YEAR][Letter(s)]" For example: sn1987A = SN('sn1987a') sn1999em = SN('sn1999em') Attributes ---------- name : Name of the supernova, "SN" followed by the year of first observation along with a letter designating the order of observation in that year. "SN1987A" was the first SN observed in 1987. "SN2000cb" was the eightieth SN observed in 2000. """ def __init__(self, name): """Initializes the SN with supplied value for [name]""" self.name = name # Load SN data from HDF5 file self.read_hdf5() def read_hdf5(self): h5file = tb.open_file(hdf5_filename) # Get the desired node from the HDF5 file sn_node = h5file.get_node('/sn', self.name)
import tables as tb hdf5_filename = 'hdf5/sn_data.h5' class SN(object): """A supernova is the explosion that ends the life of a star The SN needs to be conatained within the HDF5 database before it is used by SNoBoL. Once there, simply create a supernova by calling the constructor with the name of the SN as a string of the form "sn[YEAR][Letter(s)]" For example: sn1987A = SN('sn1987a') sn1999em = SN('sn1999em') Attributes ---------- name : Name of the supernova, "SN" followed by the year of first observation along with a letter designating the order of observation in that year. "SN1987A" was the first SN observed in 1987. "SN2000cb" was the eightieth SN observed in 2000. """ def __init__(self, name): """Initializes the SN with supplied value for [name]""" self.name = name # Load SN data from HDF5 file self.read_hdf5() def read_hdf5(self): h5file = tb.open_file(hdf5_filename) # Check that the desired SN is in the HDF5 file if self.name in h5file.list_nodes('/sn')._v_name: print "Yay!" else: print "Boo!"
Use a standard database location
// leveldb-driver-test.js // // Testing the leveldb driver // // Copyright 2012, StatusNet Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var assert = require('assert'), vows = require('vows'), databank = require('databank'), Databank = databank.Databank, LevelDBDatabank = require('../lib/leveldb'); Databank.register('leveldb', LevelDBDatabank); var suite = databank.DriverTest('leveldb', {file: '/tmp/leveldb-driver-test'}); suite['export'](module);
// leveldb-driver-test.js // // Testing the leveldb driver // // Copyright 2012, StatusNet Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var assert = require('assert'), vows = require('vows'), databank = require('databank'), Databank = databank.Databank, LevelDBDatabank = require('../lib/leveldb'); Databank.register('leveldb', LevelDBDatabank); var suite = databank.DriverTest('leveldb', {mktmp: true}); suite['export'](module);
Fix observed element for Dynamics 365 The button was losing the active status right after the timer was started.
'use strict'; togglbutton.render( '[data-id="ticketnumber.fieldControl-text-box-text"]:not(.toggl)', { observe: true }, function (elem) { const header = $('#headerContainer'); const getDescription = function () { // entity: incident const ticketnumber = $( 'input[data-id="ticketnumber.fieldControl-text-box-text"]' ); const ticketname = $('input[data-id="title.fieldControl-text-box-text"]'); if (ticketnumber || ticketname) { return ( (ticketnumber ? ticketnumber.title + ' ' : '') + (ticketname ? ticketname.title : '') ); } else { // other entities if (!header) { return ''; } const title = $('h1', header); if (!title) { return ''; } return title ? title.textContent : ''; } }; const link = togglbutton.createTimerLink({ className: 'dynamics365', description: getDescription }); header.appendChild(link); } );
'use strict'; togglbutton.render('#headerContainer:not(.toggl)', { observe: true }, function (elem) { const getDescription = function () { // entity: incident const ticketnumber = $('input[data-id="ticketnumber.fieldControl-text-box-text"]'); const ticketname = $('input[data-id="title.fieldControl-text-box-text"]'); if ((ticketnumber) || (ticketname)) { return (ticketnumber ? ticketnumber.title + ' ' : '') + (ticketname ? ticketname.title : ''); } else { // other entities const header = $('#headerContainer'); if (!header) { return ''; } const title = $('h1', header); if (!title) { return ''; } return (title ? title.textContent : ''); } }; const link = togglbutton.createTimerLink({ className: 'dynamics365', description: getDescription }); elem.appendChild(link); });
Fix URL that was killing serving static files.
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'geojsonlint.views.home', name='home'), url(r'^validate$', 'geojsonlint.views.validate', name='validate'), # url(r'^geojsonlint/', include('geojsonlint.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), ) if settings.DEBUG: urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'geojsonlint.views.home', name='home'), url(r'^validate$', 'geojsonlint.views.validate', name='validate'), # url(r'^geojsonlint/', include('geojsonlint.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT, }), )
Enforce shape of store property This produce better Error messages, when store property is not being provided. In our case we migrated to redux-1.0.x and got the waring: "Warning: Failed Context Types: Required child context `store` was not specified in `Provider`" because previously the property holding the flux instance was named redux. With the propTypes specified you would get the following warning: "Warning: Failed propType: Required prop `store` was not specified in `Provider`" which makes it pretty clear how and where to fix the issue.
import createStoreShape from '../utils/createStoreShape'; export default function createProvider(React) { const { Component, PropTypes } = React; const storeShape = createStoreShape(PropTypes); return class Provider extends Component { static childContextTypes = { store: storeShape.isRequired }; static propTypes = { children: PropTypes.func.isRequired, store: storeShape.isRequired }; getChildContext() { return { store: this.state.store }; } constructor(props, context) { super(props, context); this.state = { store: props.store }; } componentWillReceiveProps(nextProps) { const { store } = this.state; const { store: nextStore } = nextProps; if (store !== nextStore) { const nextReducer = nextStore.getReducer(); store.replaceReducer(nextReducer); } } render() { const { children } = this.props; return children(); } }; }
import createStoreShape from '../utils/createStoreShape'; export default function createProvider(React) { const { Component, PropTypes } = React; const storeShape = createStoreShape(PropTypes); return class Provider extends Component { static childContextTypes = { store: storeShape.isRequired }; static propTypes = { children: PropTypes.func.isRequired }; getChildContext() { return { store: this.state.store }; } constructor(props, context) { super(props, context); this.state = { store: props.store }; } componentWillReceiveProps(nextProps) { const { store } = this.state; const { store: nextStore } = nextProps; if (store !== nextStore) { const nextReducer = nextStore.getReducer(); store.replaceReducer(nextReducer); } } render() { const { children } = this.props; return children(); } }; }
Update reference to babel documentation Babel changed it's link to their documents.
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value, currency=None): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return u"" # Using Babel's currency formatting # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency kwargs = { 'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY, 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None), 'locale': to_locale(get_language() or settings.LANGUAGE_CODE), } return format_currency(value, **kwargs)
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value, currency=None): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return u"" # Using Babel's currency formatting # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency kwargs = { 'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY, 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None), 'locale': to_locale(get_language() or settings.LANGUAGE_CODE), } return format_currency(value, **kwargs)
Install scripts properly rather than as datafiles - also fix whitespace
#!/usr/bin/env python from distutils.core import setup setup(name="sysops-api", version="1.0", description="LinkedIn Redis / Cfengine API", author="Mike Svoboda", author_email="msvoboda@linkedin.com", py_modules=['CacheExtractor', 'RedisFinder'], scripts=['scripts/extract_sysops_cache.py', 'scripts/extract_sysops_api_to_disk.py', 'scripts/extract_sysctl_live_vs_persistant_entries.py', 'scripts/extract_user_account_access.py', 'scripts/extract_user_sudo_privileges.py'], package_dir={'': 'src'}, packages=['seco'], )
#!/usr/bin/env python from distutils.core import setup setup(name="sysops-api", version="1.0", description="LinkedIn Redis / Cfengine API", author = "Mike Svoboda", author_email = "msvoboda@linkedin.com", py_modules=['CacheExtractor', 'RedisFinder'], data_files=[('/usr/local/bin', ['./scripts/extract_sysops_cache.py']), ('/usr/local/bin', ['./scripts/extract_sysops_api_to_disk.py']), ('/usr/local/bin', ['./scripts/extract_sysctl_live_vs_persistant_entries.py']), ('/usr/local/bin', ['./scripts/extract_user_account_access.py']), ('/usr/local/bin', ['./scripts/extract_user_sudo_privileges.py'])], package_dir={'': 'src'}, packages = ['seco'], )
Set up saml's autoloader before yii's (for tests, too).
<?php // Define a constant to indicate that this is a testing environment. define('APPLICATION_ENV', 'testing'); require_once __DIR__.'/../utils/Utils.php'; // simpleSAMLphp autoloading if (file_exists(__DIR__ . '/../../simplesamlphp/lib/_autoload.php')) { $loader = include_once __DIR__ . '/../../simplesamlphp/lib/_autoload.php'; } else { die('Unable to find simpleSAMLphp autoloader file.'); } // Composer autoloading if (file_exists(__DIR__ . '/../../vendor/autoload.php')) { $loader = include_once __DIR__ . '/../../vendor/autoload.php'; } else { die('Unable to find Composer autoloader file.'); } // Bring in the Yii framework. $yiit = dirname(__FILE__) . '/../../vendor/yiisoft/yii/framework/yiit.php'; require_once($yiit); // Assemble the path to the appropriate config data. $config = dirname(__FILE__) . '/../config/test.php'; require_once(dirname(__FILE__) . '/WebTestCase.php'); // Configure Phake. \Phake::setClient(Phake::CLIENT_PHPUNIT); // Run the application. Yii::createWebApplication($config);
<?php // Define a constant to indicate that this is a testing environment. define('APPLICATION_ENV', 'testing'); require_once __DIR__.'/../utils/Utils.php'; // Bring in the Yii framework. $yiit = dirname(__FILE__).'/../../vendor/yiisoft/yii/framework/yiit.php'; require_once($yiit); // simpleSAMLphp autoloading if (file_exists(__DIR__ . '/../../simplesamlphp/lib/_autoload.php')) { $loader = include_once __DIR__ . '/../../simplesamlphp/lib/_autoload.php'; } else { die('Unable to find simpleSAMLphp autoloader file.'); } // Composer autoloading if (file_exists(__DIR__ . '/../../vendor/autoload.php')) { $loader = include_once __DIR__ . '/../../vendor/autoload.php'; } else { die('Unable to find Composer autoloader file.'); } // Assemble the path to the appropriate config data. $config = dirname(__FILE__) . '/../config/test.php'; require_once(dirname(__FILE__) . '/WebTestCase.php'); // Configure Phake. \Phake::setClient(Phake::CLIENT_PHPUNIT); // Run the application. Yii::createWebApplication($config);
Add dependency for python bcrypt
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='porick', version='0.1', description='', author='', author_email='', url='', install_requires=[ "Pylons>=1.0.1rc1", "SQLAlchemy==0.7.7", "py-bcrypt" ], setup_requires=["PasteScript>=1.6.3"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'porick': ['i18n/*/LC_MESSAGES/*.mo']}, #message_extractors={'porick': [ # ('**.py', 'python', None), # ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}), # ('public/**', 'ignore', None)]}, zip_safe=False, paster_plugins=['PasteScript', 'Pylons'], entry_points=""" [paste.app_factory] main = porick.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller """, )
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='porick', version='0.1', description='', author='', author_email='', url='', install_requires=[ "Pylons>=1.0.1rc1", "SQLAlchemy==0.7.7", ], setup_requires=["PasteScript>=1.6.3"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'porick': ['i18n/*/LC_MESSAGES/*.mo']}, #message_extractors={'porick': [ # ('**.py', 'python', None), # ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}), # ('public/**', 'ignore', None)]}, zip_safe=False, paster_plugins=['PasteScript', 'Pylons'], entry_points=""" [paste.app_factory] main = porick.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller """, )
Simplify pass through of CHECK_SYNTACTIC_ERRORS
var ts = require('typescript'); var process = require('process'); var IncrementalChecker = require('./IncrementalChecker'); var CancellationToken = require('./CancellationToken'); var checker = new IncrementalChecker( process.env.TSCONFIG, process.env.TSLINT === '' ? false : process.env.TSLINT, process.env.WATCH === '' ? [] : process.env.WATCH.split('|'), parseInt(process.env.WORK_NUMBER, 10), parseInt(process.env.WORK_DIVISION, 10), process.env.CHECK_SYNTACTIC_ERRORS ); function run (cancellationToken) { var diagnostics = []; var lints = []; checker.nextIteration(); try { diagnostics = checker.getDiagnostics(cancellationToken); if (checker.hasLinter()) { lints = checker.getLints(cancellationToken); } } catch (error) { if (error instanceof ts.OperationCanceledException) { return; } throw error; } if (!cancellationToken.isCancellationRequested()) { try { process.send({ diagnostics: diagnostics, lints: lints }); } catch (e) { // channel closed... process.exit(); } } } process.on('message', function (message) { run(CancellationToken.createFromJSON(message)); }); process.on('SIGINT', function () { process.exit(); });
var ts = require('typescript'); var process = require('process'); var IncrementalChecker = require('./IncrementalChecker'); var CancellationToken = require('./CancellationToken'); var checker = new IncrementalChecker( process.env.TSCONFIG, process.env.TSLINT === '' ? false : process.env.TSLINT, process.env.WATCH === '' ? [] : process.env.WATCH.split('|'), parseInt(process.env.WORK_NUMBER, 10), parseInt(process.env.WORK_DIVISION, 10), process.env.CHECK_SYNTACTIC_ERRORS === '' ? false : process.env.CHECK_SYNTACTIC_ERRORS ); function run (cancellationToken) { var diagnostics = []; var lints = []; checker.nextIteration(); try { diagnostics = checker.getDiagnostics(cancellationToken); if (checker.hasLinter()) { lints = checker.getLints(cancellationToken); } } catch (error) { if (error instanceof ts.OperationCanceledException) { return; } throw error; } if (!cancellationToken.isCancellationRequested()) { try { process.send({ diagnostics: diagnostics, lints: lints }); } catch (e) { // channel closed... process.exit(); } } } process.on('message', function (message) { run(CancellationToken.createFromJSON(message)); }); process.on('SIGINT', function () { process.exit(); });
Mark docker-manifest command as experimental (cli) Signed-off-by: Vincent Demeester <87e1f221a672a14a323e57bb65eaea19d3ed3804@sbr.pm>
package manifest import ( "fmt" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" ) // NewManifestCommand returns a cobra command for `manifest` subcommands func NewManifestCommand(dockerCli command.Cli) *cobra.Command { // use dockerCli as command.Cli cmd := &cobra.Command{ Use: "manifest COMMAND", Short: "Manage Docker image manifests and manifest lists", Long: manifestDescription, Args: cli.NoArgs, Run: func(cmd *cobra.Command, args []string) { fmt.Fprintf(dockerCli.Err(), "\n"+cmd.UsageString()) }, Annotations: map[string]string{"experimentalCLI": ""}, } cmd.AddCommand( newCreateListCommand(dockerCli), newInspectCommand(dockerCli), newAnnotateCommand(dockerCli), newPushListCommand(dockerCli), ) return cmd } var manifestDescription = ` The **docker manifest** command has subcommands for managing image manifests and manifest lists. A manifest list allows you to use one name to refer to the same image built for multiple architectures. To see help for a subcommand, use: docker manifest CMD --help For full details on using docker manifest lists, see the registry v2 specification. `
package manifest import ( "fmt" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" ) // NewManifestCommand returns a cobra command for `manifest` subcommands func NewManifestCommand(dockerCli command.Cli) *cobra.Command { // use dockerCli as command.Cli cmd := &cobra.Command{ Use: "manifest COMMAND", Short: "Manage Docker image manifests and manifest lists", Long: manifestDescription, Args: cli.NoArgs, Run: func(cmd *cobra.Command, args []string) { fmt.Fprintf(dockerCli.Err(), "\n"+cmd.UsageString()) }, } cmd.AddCommand( newCreateListCommand(dockerCli), newInspectCommand(dockerCli), newAnnotateCommand(dockerCli), newPushListCommand(dockerCli), ) return cmd } var manifestDescription = ` The **docker manifest** command has subcommands for managing image manifests and manifest lists. A manifest list allows you to use one name to refer to the same image built for multiple architectures. To see help for a subcommand, use: docker manifest CMD --help For full details on using docker manifest lists, see the registry v2 specification. `
Set MidgardConnection in setUp method
# coding=utf-8 import sys import struct import unittest from test_000_config import TestConfig from test_001_connection import TestConnection from gi.repository import Midgard from gi.repository import GObject class TestQuerySelect(unittest.TestCase): def setUp(self): self.mgd = TestConnection.openConnection() def tearDown(self): return def testSelectAdminPerson(self): st = Midgard.QueryStorage(dbclass = "midgard_person") qs = Midgard.QuerySelect(connection = self.mgd, storage = st) qs.execute() objects = qs.list_objects() # Expect one person only self.assertEqual(len(objects), 1); def testSelectInvalidType(self): st = Midgard.QueryStorage(dbclass = "NotExists") qs = Midgard.QuerySelect(connection = self.mgd, storage = st) # Check if we have GError self.assertRaises(GObject.GError, qs.execute) # Check if we have correct domain try: qs.execute() except GObject.GError as e: self.assertEqual(e.domain, "midgard-validation-error-quark") self.assertEqual(e.code, Midgard.ValidationError.TYPE_INVALID) def testOrder(self): self.assertEqual("ok", "NOT IMPLEMENTED") def testInheritance(self): qs = Midgard.QuerySelect(connection = self.mgd) self.assertIsInstance(qs, Midgard.QueryExecutor) if __name__ == "__main__": unittest.main()
# coding=utf-8 import sys import struct import unittest from test_000_config import TestConfig from test_001_connection import TestConnection from gi.repository import Midgard from gi.repository import GObject class TestQuerySelect(unittest.TestCase): def testSelectAdminPerson(self): mgd = TestConnection.openConnection() st = Midgard.QueryStorage(dbclass = "midgard_person") qs = Midgard.QuerySelect(connection = mgd, storage = st) qs.execute() objects = qs.list_objects() # Expect one person only self.assertEqual(len(objects), 1); def testSelectInvalidType(self): mgd = TestConnection.openConnection() st = Midgard.QueryStorage(dbclass = "NotExists") qs = Midgard.QuerySelect(connection = mgd, storage = st) # Check if we have GError self.assertRaises(GObject.GError, qs.execute) # Check if we have correct domain try: qs.execute() except GObject.GError as e: self.assertEqual(e.domain, "midgard-validation-error-quark") self.assertEqual(e.code, Midgard.ValidationError.TYPE_INVALID) def testOrder(self): mgd = TestConnection.openConnection() self.assertEqual("ok", "NOT IMPLEMENTED") def testInheritance(self): mgd = TestConnection.openConnection() qs = Midgard.QuerySelect(connection = mgd) self.assertIsInstance(qs, Midgard.QueryExecutor) if __name__ == "__main__": unittest.main()
Add test for detailed view
from django.test import TestCase from ansible.models import Playbook from django.core.urlresolvers import reverse class PlaybookListViewTest(TestCase): @classmethod def setUpTestData(cls): Playbook.query_set.create(username='lozadaomr',repository='ansi-dst', inventory='hosts',user='ubuntu') def test_view_url_exists_at_desired_location(self): resp = self.client.get('/playbooks/') self.assertEqual(resp.status_code, 200) def test_view_playbook_list_url_accessible_by_name(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) def test_view_playbook_detail_url_accessible_by_name(self): resp = self.client.get(reverse( 'ansible:playbook-detail', kwargs={'pk':1})) self.assertEqual(resp.status_code, 200) def test_view_uses_correct_template(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'ansible/playbook_list.html')
from django.test import TestCase from ansible.models import Playbook from django.core.urlresolvers import reverse class PlaybookListViewTest(TestCase): @classmethod def setUpTestData(cls): Playbook.query_set.create(username='lozadaomr',repository='ansi-dst', inventory='hosts',user='ubuntu') def test_view_url_exists_at_desired_location(self): resp = self.client.get('/playbooks/') self.assertEqual(resp.status_code, 200) def test_view_url_accessible_by_name(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) def test_view_uses_correct_template(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'ansible/playbook_list.html')
@noref: Fix email obfuscate when they contain a subject
<?php namespace Exolnet\Html; /** * Copyright © 2014 eXolnet Inc. All rights reserved. (http://www.exolnet.com) * * This file contains copyrighted code that is the sole property of eXolnet Inc. * You may not use this file except with a written agreement. * * This code is distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESS OR IMPLIED, AND EXOLNET INC. HEREBY DISCLAIMS ALL SUCH * WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * * @package Exolnet * @subpackage Html * @author eXolnet Inc. <info@exolnet.com> */ use \Illuminate\Html\HtmlBuilder as LaravelHtmlBuilder; class HtmlHelper { /** * Obfuscate all mailto in the HTML source provided. * * @param $value * @return mixed */ public static function obfuscateEmails($html) { return preg_replace_callback('#(mailto:)?[a-z0-9_.+-]+@[a-z0-9-]+\.[a-z0-9-.]+#i', function($match) { return \HTML::email($match[0]); }, $html); } }
<?php namespace Exolnet\Html; /** * Copyright © 2014 eXolnet Inc. All rights reserved. (http://www.exolnet.com) * * This file contains copyrighted code that is the sole property of eXolnet Inc. * You may not use this file except with a written agreement. * * This code is distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESS OR IMPLIED, AND EXOLNET INC. HEREBY DISCLAIMS ALL SUCH * WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * * @package Exolnet * @subpackage Html * @author eXolnet Inc. <info@exolnet.com> */ use \Illuminate\Html\HtmlBuilder as LaravelHtmlBuilder; class HtmlHelper { /** * Obfuscate all mailto in the HTML source provided. * * @param $value * @return mixed */ public static function obfuscateMailtos($html) { return preg_replace_callback('#("|\')(mailto:.+?)(\1)#', function($match) { //dd($match); return $match[1]. \HTML::obfuscate($match[2]).$match[3]; }, $html); } }
Include all package data and add django dependency
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = "django-webmaster-verification", version = "0.1.3", author = "Nicolas Kuttler", author_email = "pypi@nicolaskuttler.com", description = "Webmaster tools verification for Django", long_description = open("README.rst").read(), license = "BSD", url = "http://github.com/nkuttler/django-webmaster-verification", packages = ['webmaster_verification'], include_package_data = True, classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ], install_requires = [ "Django >= 1.3", ], zip_safe = True, )
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = "django-webmaster-verification", version = "0.1.1", author = "Nicolas Kuttler", author_email = "pypi@nicolaskuttler.com", description = "Webmaster tools verification for Django", long_description = open("README.rst").read(), license = "BSD", url = "http://github.com/nkuttler/django-webmaster-verification", packages = ['webmaster_verification'], package_data = { 'webmaster_verification': ['templates/webmaster_verification/*', ], }, classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ], zip_safe = True, )
Fix test break for windows: better error handling
// +build windows package buf import ( "syscall" ) func checkReadVConstraint(conn syscall.RawConn) (bool, error) { var isSocketReady = false var reason error /* In Windows, WSARecv system call only support socket connection. It it required to check if the given fd is of a socket type Fix https://github.com/v2ray/v2ray-core/issues/1666 Additional Information: https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-wsarecv https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-getsockopt https://docs.microsoft.com/en-us/windows/desktop/WinSock/sol-socket-socket-options */ err := conn.Control(func(fd uintptr) { var val [4]byte var le = int32(len(val)) err := syscall.Getsockopt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_RCVBUF, &val[0], &le) if err != nil { isSocketReady = false } else { isSocketReady = true } reason = err }) if err != nil { return false, err } return isSocketReady, reason }
// +build windows package buf import ( "syscall" ) func checkReadVConstraint(conn syscall.RawConn) (bool, error) { var isSocketReady = false var reason error /* In Windows, WSARecv system call only support socket connection. It it required to check if the given fd is of a socket type Fix https://github.com/v2ray/v2ray-core/issues/1666 Additional Information: https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-wsarecv https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-getsockopt https://docs.microsoft.com/en-us/windows/desktop/WinSock/sol-socket-socket-options */ err := conn.Control(func(fd uintptr) { var val [4]byte var le = int32(len(val)) err := syscall.Getsockopt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_RCVBUF, &val[0], &le) if err != nil { isSocketReady = false } else { isSocketReady = true } reason = err }) return isSocketReady, err }
Update the toolkit to use indexedDB Wrapper and the generic implementation of service-framework
import SandboxBrowser from '../sandboxes/SandboxBrowser'; import AppSandboxBrowser from '../sandboxes/AppSandboxBrowser'; import Request from '../browser/Request'; import {RuntimeCatalogue} from 'service-framework/dist/RuntimeCatalogue'; import PersistenceManager from 'service-framework/dist/PersistenceManager'; import StorageManager from 'service-framework/dist/StorageManager'; // import StorageManagerFake from './StorageManagerFake'; import Dexie from 'dexie'; const runtimeFactory = Object.create({ createSandbox() { return new SandboxBrowser(); }, createAppSandbox() { return new AppSandboxBrowser(); }, createHttpRequest() { let request = new Request(); return request; }, atob(b64) { return atob(b64); }, storageManager() { // Using the implementation of Service Framework // Dexie is the IndexDB Wrapper const db = new Dexie('cache'); const storeName = 'objects'; return new StorageManager(db, storeName); // return new StorageManagerFake('a', 'b'); }, persistenceManager() { let localStorage = window.localStorage; return new PersistenceManager(localStorage); }, createRuntimeCatalogue(development) { if (!this.catalogue) this.catalogue = new RuntimeCatalogue(this); return this.catalogue; } }); export default runtimeFactory;
import SandboxBrowser from '../sandboxes/SandboxBrowser'; import AppSandboxBrowser from '../sandboxes/AppSandboxBrowser'; import Request from '../browser/Request'; import {RuntimeCatalogue} from 'service-framework/dist/RuntimeCatalogue'; import PersistenceManager from 'service-framework/dist/PersistenceManager'; import StorageManagerFake from './StorageManagerFake'; // import Dexie from 'dexie'; const runtimeFactory = Object.create({ createSandbox() { return new SandboxBrowser(); }, createAppSandbox() { return new AppSandboxBrowser(); }, createHttpRequest() { let request = new Request(); return request; }, atob(b64) { return atob(b64); }, storageManager() { // const db = new Dexie('cache'); // const storeName = 'objects'; return new StorageManagerFake('a', 'b'); }, persistenceManager() { let localStorage = window.localStorage; return new PersistenceManager(localStorage); }, createRuntimeCatalogue(development) { if (!this.catalogue) this.catalogue = new RuntimeCatalogue(this); return this.catalogue; } }); export default runtimeFactory;
Use toString instead of toHexString
var events = require('events'); var util = require('util'); module.exports = Job; function Job(collection, data) { this.collection = collection; if(data){ data.__proto__ = JobData.prototype; //Convert plain object to JobData type this.data = data; } else { this.data = new JobData(); } } util.inherits(Job, events.EventEmitter); Job.prototype.save = function(callback) { var self = this; this.collection.save(this.data, function(err, doc) { if (err) return callback(err); if (doc && self.data._id === undefined) self.data._id = doc._id; callback(null, self); }); }; Job.prototype.complete = function(result, callback) { this.data.status = 'complete'; this.data.ended = new Date(); this.data.result = result; this.save(callback); }; Job.prototype.fail = function(error, callback) { this.data.status = 'failed'; this.data.ended = new Date(); this.data.error = error.message; this.save(callback); }; function JobData() {} Object.defineProperty(JobData.prototype, 'id', { get: function(){ return this._id && this._id.toString && this._id.toString(); } });
var events = require('events'); var util = require('util'); module.exports = Job; function Job(collection, data) { this.collection = collection; if(data){ data.__proto__ = JobData.prototype; //Convert plain object to JobData type this.data = data; } else { this.data = new JobData(); } } util.inherits(Job, events.EventEmitter); Job.prototype.save = function(callback) { var self = this; this.collection.save(this.data, function(err, doc) { if (err) return callback(err); if (doc && self.data._id === undefined) self.data._id = doc._id; callback(null, self); }); }; Job.prototype.complete = function(result, callback) { this.data.status = 'complete'; this.data.ended = new Date(); this.data.result = result; this.save(callback); }; Job.prototype.fail = function(error, callback) { this.data.status = 'failed'; this.data.ended = new Date(); this.data.error = error.message; this.save(callback); }; function JobData() {} Object.defineProperty(JobData.prototype, 'id', { get: function(){ return this._id && this._id.toHexString && this._id.toHexString(); } });
Remove membership internal ID and change person to name
from rest_framework import serializers from popolo import models as popolo_models from parties.serializers import MinimalPartySerializer class MinimalPostSerializer(serializers.ModelSerializer): class Meta: model = popolo_models.Post fields = ("id", "label", "slug") id = serializers.ReadOnlyField(source="slug") label = serializers.ReadOnlyField() class NominationAndResultSerializer(serializers.HyperlinkedModelSerializer): """ A representation of a Membership with only the information on the ballot paper, and results if we have them. """ class Meta: model = popolo_models.Membership fields = ("id", "elected", "party_list_position", "name", "party") elected = serializers.ReadOnlyField() party_list_position = serializers.ReadOnlyField() name = serializers.ReadOnlyField(source="person.name") party = MinimalPartySerializer(read_only=True)
from rest_framework import serializers from popolo import models as popolo_models from parties.serializers import MinimalPartySerializer class MinimalPostSerializer(serializers.ModelSerializer): class Meta: model = popolo_models.Post fields = ("id", "label", "slug") id = serializers.ReadOnlyField(source="slug") label = serializers.ReadOnlyField() class NominationAndResultSerializer(serializers.HyperlinkedModelSerializer): """ A representation of a Membership with only the information on the ballot paper, and results if we have them. """ class Meta: model = popolo_models.Membership fields = ("elected", "party_list_position", "person", "party") elected = serializers.ReadOnlyField() party_list_position = serializers.ReadOnlyField() person = serializers.ReadOnlyField(source="person.name") party = MinimalPartySerializer(read_only=True)
Define default value for `$processors` This makes it possible to initialize a `ConfigProcessor` that has no processors. Solves this error: Typed property Overblog\GraphQLBundle\Definition\ConfigProcessor::$processors must not be accessed before initialization.
<?php declare(strict_types=1); namespace Overblog\GraphQLBundle\Definition; use Overblog\GraphQLBundle\Definition\ConfigProcessor\ConfigProcessorInterface; final class ConfigProcessor { /** * @var ConfigProcessorInterface[] */ private array $processors = []; public function __construct(iterable $processors) { foreach ($processors as $processor) { $this->register($processor); } } public function getProcessors(): array { return $this->processors; } public function register(ConfigProcessorInterface $configProcessor): void { $this->processors[] = $configProcessor; } /** * @phpstan-template T of array * @phpstan-param T $config * @phpstan-return T */ public function process(array $config): array { foreach ($this->processors as $processor) { $config = $processor->process($config); } return $config; } }
<?php declare(strict_types=1); namespace Overblog\GraphQLBundle\Definition; use Overblog\GraphQLBundle\Definition\ConfigProcessor\ConfigProcessorInterface; final class ConfigProcessor { /** * @var ConfigProcessorInterface[] */ private array $processors; public function __construct(iterable $processors) { foreach ($processors as $processor) { $this->register($processor); } } public function getProcessors(): array { return $this->processors; } public function register(ConfigProcessorInterface $configProcessor): void { $this->processors[] = $configProcessor; } /** * @phpstan-template T of array * @phpstan-param T $config * @phpstan-return T */ public function process(array $config): array { foreach ($this->processors as $processor) { $config = $processor->process($config); } return $config; } }
Fix after throwing chain to catch the right exception
package com.bnorm.auto.weave.internal.chain; import com.bnorm.auto.weave.AfterThrowingJoinPoint; import com.bnorm.auto.weave.internal.Pointcut; public abstract class AfterThrowingChain extends WrapChain { public AfterThrowingChain(Chain wrapped, Pointcut pointcut) { super(wrapped, pointcut); } @Override public final Object call() { try { return super.call(); } catch (MethodException error) { AfterThrowingJoinPoint afterThrowingJoinPoint = new AfterThrowingJoinPoint(pointcut, error.getCause()); afterThrowing(afterThrowingJoinPoint); throw error; } } protected abstract void afterThrowing(AfterThrowingJoinPoint afterJoinPoint); }
package com.bnorm.auto.weave.internal.chain; import com.bnorm.auto.weave.AfterThrowingJoinPoint; import com.bnorm.auto.weave.internal.Pointcut; public abstract class AfterThrowingChain extends WrapChain { public AfterThrowingChain(Chain wrapped, Pointcut pointcut) { super(wrapped, pointcut); } @Override public final Object call() { try { return super.call(); } catch (Throwable error) { AfterThrowingJoinPoint afterThrowingJoinPoint = new AfterThrowingJoinPoint(pointcut, error); afterThrowing(afterThrowingJoinPoint); throw error; } } protected abstract void afterThrowing(AfterThrowingJoinPoint afterJoinPoint); }
Configure webpack to use root folder for static path
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: '', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: '', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
Use StringIO object from 'io' module instead of deprecated 'StringIO' module
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from io import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from StringIO import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
Change url to point to github
import os from setuptools import setup def read(name): return open(os.path.join(os.path.dirname(__file__), name), 'r').read() setup( name="kitsu.http", version="0.0.7", description="Low-level HTTP library for Python", long_description=read('README'), author="Alexey Borzenkov", author_email="snaury@gmail.com", url="https://github.com/snaury/kitsu.http", license="MIT License", platforms=['any'], namespace_packages=['kitsu', 'kitsu.http'], packages=['kitsu', 'kitsu.http'], test_suite='tests.test_suite', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Operating System :: OS Independent', 'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
import os from setuptools import setup def read(name): return open(os.path.join(os.path.dirname(__file__), name), 'r').read() setup( name="kitsu.http", version="0.0.7", description="Low-level HTTP library for Python", long_description=read('README'), author="Alexey Borzenkov", author_email="snaury@gmail.com", url="http://git.kitsu.ru/mine/kitsu-http.git", license="MIT License", platforms=['any'], namespace_packages=['kitsu', 'kitsu.http'], packages=['kitsu', 'kitsu.http'], test_suite='tests.test_suite', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Operating System :: OS Independent', 'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Update client to account for change in signature. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@583 c7a0535c-eda6-11de-83d8-6d5adf01d787
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.unittesting.assertionbenchmarks; import java.math.BigDecimal; import org.mutabilitydetector.cli.CommandLineOptions; import org.mutabilitydetector.cli.NamesFromClassResources; import org.mutabilitydetector.cli.RunMutabilityDetector; import org.mutabilitydetector.repackaged.com.google.classpath.ClassPath; import org.mutabilitydetector.repackaged.com.google.classpath.ClassPathFactory; public class CheckSomeClass { public static void main(String[] args) { //checkClass(TestIllegalFieldValueException.class); // checkClass(DurationField.class); checkClass(BigDecimal.class); } private static void checkClass(Class<?> toAnalyse) { ClassPath cp = new ClassPathFactory().createFromJVM(); String match = toAnalyse.getName().replace("$", "\\$"); CommandLineOptions options = new CommandLineOptions(System.out, "-v", "-match", match); new RunMutabilityDetector(cp, options, new NamesFromClassResources(options.match())).run(); } }
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.unittesting.assertionbenchmarks; import java.math.BigDecimal; import org.mutabilitydetector.cli.CommandLineOptions; import org.mutabilitydetector.cli.RunMutabilityDetector; import org.mutabilitydetector.repackaged.com.google.classpath.ClassPath; import org.mutabilitydetector.repackaged.com.google.classpath.ClassPathFactory; public class CheckSomeClass { public static void main(String[] args) { //checkClass(TestIllegalFieldValueException.class); // checkClass(DurationField.class); checkClass(BigDecimal.class); } private static void checkClass(Class<?> toAnalyse) { ClassPath cp = new ClassPathFactory().createFromJVM(); String match = toAnalyse.getName().replace("$", "\\$"); CommandLineOptions options = new CommandLineOptions(System.out, "-v", "-match", match); new RunMutabilityDetector(cp, options).run(); } }
[fix] HTTP: Handle null request bodies properly
export function request(method, url, body, params = {}) { method = method.toUpperCase(); if (body) { if (typeof body === "object") { let formstring = ""; for (let entry of body) { if (formstring !== "") { formstring += "&"; } formstring += entry[0] + "=" + encodeURIComponent(entry[1]); } body = formstring; } if (method === "GET" || method === "HEAD") { url += (url.includes("?") ? "&" : "?") + body; body = ""; } } return __jsapi__.HTTPRequest(method, url, body, params); }; export function get(url, body, params) { return request("GET", url, body, params); }; export function post(url, body, params) { return request("POST", url, body, params); }; export function put(url, body, params) { return request("PUT", url, body, params); }; export function del(url, body, params) { return request("DELETE", url, body, params); }; export function patch(url, body, params) { return request("PATCH", url, body, params); }; export default { request: request, get: get, post: post, put: put, del: del, patch: patch, };
export function request(method, url, body, params = {}) { method = method.toUpperCase(); if (typeof body === "object") { let formstring = ""; for (let entry of body) { if (formstring !== "") { formstring += "&"; } formstring += entry[0] + "=" + encodeURIComponent(entry[1]); } } if (method === "GET" || method === "HEAD") { if (body) { url += (url.includes("?") ? "&" : "?") + body; } body = ""; } return __jsapi__.HTTPRequest(method, url, body, params); }; export function get(url, body, params) { return request("GET", url, body, params); }; export function post(url, body, params) { return request("POST", url, body, params); }; export function put(url, body, params) { return request("PUT", url, body, params); }; export function del(url, body, params) { return request("DELETE", url, body, params); }; export function patch(url, body, params) { return request("PATCH", url, body, params); }; export default { request: request, get: get, post: post, put: put, del: del, patch: patch, };
Use runghc instead of executables
import subprocess import unittest import glob def runTestcase(self, input_file, result_file): spillProg = subprocess.Popen(['runghc', '-i../../src', 'Main.hs', input_file],stdout=subprocess.PIPE) idProg = subprocess.Popen(['runghc', '-i../../src', 'Id.hs', result_file],stdout=subprocess.PIPE) with open(result_file) as results: self.assertEqual(spillProg.stdout.read(), idProg.stdout.read()) class Tests(unittest.TestCase): def testValidateAll(self): all_inputs = sorted(glob.glob('../../322-interps/tests/mhuesch/spill-test/*.L2f')) all_results = sorted(glob.glob('../../322-interps/tests/mhuesch/spill-test/*.sres')) for i,r in zip(all_inputs, all_results): print i runTestcase(self, i, r) if __name__ == '__main__': unittest.main()
import subprocess import unittest import glob def runTestcase(self, input_file, result_file): spillProg = subprocess.Popen(['./spill', input_file],stdout=subprocess.PIPE) idProg = subprocess.Popen(['./id', result_file],stdout=subprocess.PIPE) with open(result_file) as results: self.assertEqual(spillProg.stdout.read(), idProg.stdout.read()) class Tests(unittest.TestCase): def testValidateAll(self): all_inputs = sorted(glob.glob('../../322-interps/tests/mhuesch/spill-test/*.L2f')) all_results = sorted(glob.glob('../../322-interps/tests/mhuesch/spill-test/*.sres')) for i,r in zip(all_inputs, all_results): print i runTestcase(self, i, r) if __name__ == '__main__': unittest.main()
Create version 0.9.11 before integrating file upload functionality
package org.beanmaker; /** * This class gives information about the VERSION of this library. */ public class Version { private static final String PREFIX = ""; private static final int MAJOR = 0; private static final int MINOR = 9; private static final int PATCH = 11; private static final String POSTFIX = "-beta"; private static final String VERSION = PREFIX + MAJOR + "." + MINOR + "." + PATCH + POSTFIX; /** * @return the version number of this library */ public static String get() { return VERSION; } /** * To be used in build scripts. */ public static void main (String[] args) { System.out.println(get()); } }
package org.beanmaker; /** * This class gives information about the VERSION of this library. */ public class Version { private static final String PREFIX = ""; private static final int MAJOR = 0; private static final int MINOR = 9; private static final int PATCH = 10; private static final String POSTFIX = "-beta"; private static final String VERSION = PREFIX + MAJOR + "." + MINOR + "." + PATCH + POSTFIX; /** * @return the version number of this library */ public static String get() { return VERSION; } /** * To be used in build scripts. */ public static void main (String[] args) { System.out.println(get()); } }
Change to preferred encoding style. UTF-8 -> utf-8
""" Serializer plugin interface. This module is useful for those wanting to write a serializer that can plugin to rdflib. If you are wanting to invoke a serializer you likely want to do so through the Graph class serialize method. TODO: info for how to write a serializer that can plugin to rdflib. See also rdflib.plugin """ from typing import IO, TYPE_CHECKING, Optional from rdflib.term import URIRef if TYPE_CHECKING: from rdflib.graph import Graph __all__ = ["Serializer"] class Serializer: def __init__(self, store: "Graph"): self.store: "Graph" = store self.encoding: str = "utf-8" self.base: Optional[str] = None def serialize( self, stream: IO[bytes], base: Optional[str] = None, encoding: Optional[str] = None, **args ) -> None: """Abstract method""" def relativize(self, uri: str): base = self.base if base is not None and uri.startswith(base): uri = URIRef(uri.replace(base, "", 1)) return uri
""" Serializer plugin interface. This module is useful for those wanting to write a serializer that can plugin to rdflib. If you are wanting to invoke a serializer you likely want to do so through the Graph class serialize method. TODO: info for how to write a serializer that can plugin to rdflib. See also rdflib.plugin """ from typing import IO, TYPE_CHECKING, Optional from rdflib.term import URIRef if TYPE_CHECKING: from rdflib.graph import Graph __all__ = ["Serializer"] class Serializer: def __init__(self, store: "Graph"): self.store: "Graph" = store self.encoding: str = "UTF-8" self.base: Optional[str] = None def serialize( self, stream: IO[bytes], base: Optional[str] = None, encoding: Optional[str] = None, **args ) -> None: """Abstract method""" def relativize(self, uri: str): base = self.base if base is not None and uri.startswith(base): uri = URIRef(uri.replace(base, "", 1)) return uri
Add media manager open JS method
( function( window, Backbone, $, _, Scrivener, undefined ) { "use strict"; var document = window.document; Scrivener.Views.Sidebar = Backbone.View.extend( { className : 'scrivener-customizer-sidebar', events : { 'click .button.close' : 'onCloseCustomizerClick', 'click #set-post-thumbnail' : 'openMediaManager', 'click #remove-post-thumbnail' : 'removePostThumbnail', }, initialize : function( attributes ) { this.render( attributes.ajaxData ); }, render : function( ajaxData ) { this.$el.html( '<div class="content">' + ajaxData.sidebarHTML + '</div>' ); }, onCloseCustomizerClick : function( event ) { this.model.closeCustomizer(); }, close : function() { this.remove(); }, openMediaManager: function( event ) { event.stopPropagation(); event.preventDefault(); wp.media.featuredImage.frame().open(); }, removePostThumbnail: function( event ) { //wp.media.view.settings.post.featuredImageId = -1; } } ); } )( window, Backbone, jQuery, _, Scrivener );
( function( window, Backbone, $, _, Scrivener, undefined ) { "use strict"; var document = window.document; Scrivener.Views.Sidebar = Backbone.View.extend( { className : 'scrivener-customizer-sidebar', events : { 'click .button.close' : 'onCloseCustomizerClick' }, initialize : function( attributes ) { this.render( attributes.ajaxData ); }, render : function( ajaxData ) { this.$el.html( '<div class="content">' + ajaxData.sidebarHTML + '</div>' ); }, onCloseCustomizerClick : function( event ) { this.model.closeCustomizer(); }, close : function() { this.remove(); } } ); } )( window, Backbone, jQuery, _, Scrivener );
Add a comment about the route.
<?php namespace Illuminate\Auth\Console; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; class RemindersControllerCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'auth:reminders-controller'; /** * The console command description. * * @var string */ protected $description = 'Create a stub password reminder controller'; /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * Create a new reminder table command instance. * * @param \Illuminate\Filesystem\Filesystem $files * @return void */ public function __construct(Filesystem $files) { parent::__construct(); $this->files = $files; } /** * Execute the console command. * * @return void */ public function fire() { $destination = $this->laravel['path'].'/controllers/RemindersController.php'; if ( ! $this->files->exists($destination)) { $this->files->copy(__DIR__.'/stubs/controller.stub', $destination); $this->info('Password reminders controller created successfully!'); $this->comment("Route: Route::controller('password', 'RemindersController')"); } else { $this->error('Password reminders controller already exists!'); } } }
<?php namespace Illuminate\Auth\Console; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; class RemindersControllerCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'auth:reminders-controller'; /** * The console command description. * * @var string */ protected $description = 'Create a stub password reminder controller'; /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * Create a new reminder table command instance. * * @param \Illuminate\Filesystem\Filesystem $files * @return void */ public function __construct(Filesystem $files) { parent::__construct(); $this->files = $files; } /** * Execute the console command. * * @return void */ public function fire() { $destination = $this->laravel['path'].'/controllers/RemindersController.php'; if ( ! $this->files->exists($destination)) { $this->files->copy(__DIR__.'/stubs/controller.stub', $destination); $this->info('Password reminders controller created successfully!'); } else { $this->error('Password reminders controller already exists!'); } } }
Remove call to run management commands that we didn't use during migration
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-10-26 18:43 from __future__ import unicode_literals from django.db import migrations, models from osf.management.commands.add_notification_subscription import add_reviews_notification_setting from osf.management.commands.populate_registration_provider_notification_subscriptions import populate_registration_provider_notification_subscriptions def revert(apps, schema_editor): NotificationSubscription = apps.get_model('osf', 'NotificationSubscription') # The revert of this migration deletes all NotificationSubscription instances NotificationSubscription.objects.filter(provider__isnull=False, provider__type='osf.registrationprovider').delete() def populate_subscriptions(*args, **kwargs): add_reviews_notification_setting('global_reviews') populate_registration_provider_notification_subscriptions() class Migration(migrations.Migration): dependencies = [ ('osf', '0223_auto_20201026_1843'), ] operations = [ migrations.AlterField( model_name='notificationsubscription', name='event_name', field=models.CharField(max_length=100), ) ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-10-26 18:43 from __future__ import unicode_literals from django.db import migrations, models from osf.management.commands.add_notification_subscription import add_reviews_notification_setting from osf.management.commands.populate_registration_provider_notification_subscriptions import populate_registration_provider_notification_subscriptions def revert(apps, schema_editor): NotificationSubscription = apps.get_model('osf', 'NotificationSubscription') # The revert of this migration deletes all NotificationSubscription instances NotificationSubscription.objects.filter(provider__isnull=False, provider__type='osf.registrationprovider').delete() def populate_subscriptions(*args, **kwargs): add_reviews_notification_setting('global_reviews') populate_registration_provider_notification_subscriptions() class Migration(migrations.Migration): dependencies = [ ('osf', '0223_auto_20201026_1843'), ] operations = [ migrations.AlterField( model_name='notificationsubscription', name='event_name', field=models.CharField(max_length=100), ), migrations.RunPython(populate_subscriptions, revert) ]
Use slice of *Conn instead of a map These is very very devices at had. SO no need for a map
package device import ( "sync" "github.com/tarm/serial" ) type Manager struct { devices map[string]serial.Config conn []*Conn mu sync.RWMutex } func (m *Manager) AddDevice(name string) error { cfg := serial.Config{Name: name} m.mu.Lock() m.devices[name] = cfg m.mu.Unlock() return nil } func (m *Manager) RemoveDevice(name string) error { m.mu.RLock() delete(m.devices, name) m.mu.RUnlock() return nil } type Conn struct { device serial.Config port *serial.Port isOpen bool } func (c *Conn) Open() error { p, err := serial.OpenPort(&c.device) if err != nil { return nil } c.port = p c.isOpen = true return nil } // Close closes the port helt by *Conn. func (c *Conn) Close() error { if c.isOpen { return c.port.Close() } return nil }
package device import ( "sync" "github.com/tarm/serial" ) type Manager struct { devices map[string]serial.Config mu sync.RWMutex } func (m *Manager) AddDevice(name string) error { cfg := serial.Config{Name: name} m.mu.Lock() m.devices[name] = cfg m.mu.Unlock() return nil } func (m *Manager) RemoveDevice(name string) error { m.mu.RLock() delete(m.devices, name) m.mu.RUnlock() return nil } type Conn struct { device serial.Config port *serial.Port isOpen bool } func (c *Conn) Open() error { p, err := serial.OpenPort(&c.device) if err != nil { return nil } c.port = p c.isOpen = true return nil } // Close closes the port helt by *Conn. func (c *Conn) Close() error { if c.isOpen { return c.port.Close() } return nil }
Update drag context usage to avoid error about refs
import React from 'react'; import PropTypes from 'prop-types'; import { withProps } from 'recompose'; import BandwidthThemeProvider from '../BandwidthThemeProvider'; import DefaultStyleRoot from './styles/StyleRoot'; import withDragDropContext from './withDragDropContext'; import DefaultDragLayer from '../DragLayer'; import './styles/global'; // injects a global stylesheet class Provider extends React.PureComponent { static propTypes = { StyleRoot: PropTypes.func, ThemeProvider: PropTypes.func, DragLayer: PropTypes.func, children: PropTypes.node.isRequired, }; static defaultProps = { StyleRoot: DefaultStyleRoot, ThemeProvider: BandwidthThemeProvider, DragLayer: DefaultDragLayer, }; render() { const { StyleRoot, ThemeProvider, DragLayer, children } = this.props; return ( <ThemeProvider> <StyleRoot> {children} <DragLayer /> </StyleRoot> </ThemeProvider> ); } } export default withDragDropContext(Provider);
import React from 'react'; import PropTypes from 'prop-types'; import { withProps } from 'recompose'; import BandwidthThemeProvider from '../BandwidthThemeProvider'; import DefaultStyleRoot from './styles/StyleRoot'; import withDragDropContext from './withDragDropContext'; import DefaultDragLayer from '../DragLayer'; import './styles/global'; // injects a global stylesheet const Provider = ({ StyleRoot, ThemeProvider, DragLayer, children }) => ( <ThemeProvider> <StyleRoot> {children} <DragLayer /> </StyleRoot> </ThemeProvider> ); Provider.propTypes = { StyleRoot: PropTypes.func, ThemeProvider: PropTypes.func, DragLayer: PropTypes.func, children: PropTypes.node.isRequired, }; Provider.defaultProps = { StyleRoot: DefaultStyleRoot, ThemeProvider: BandwidthThemeProvider, DragLayer: DefaultDragLayer, }; export default withDragDropContext(Provider);
Update to use autopilot instead of understand
// Download the helper library https://www.twilio.com/docs/libraries/node#install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.autopilot.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
// Download the helper library https://www.twilio.com/docs/libraries/node#install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.preview.understand.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
Add new concrete MultiValuedMap implementation. git-svn-id: 53f0c1087cb9b05f99ff63ab1f4d1687a227fef1@1633229 13f79535-47bb-0310-9956-ffa450edef68
/* * 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. */ /** * This package contains implementations of the {@link org.apache.commons.collections4.MultiValuedMap} interfaces. * A MultiValuedMap holds a collection of values against each key. * <p> * The following implementations are provided in the package: * <ul> * <li>MultiValuedHashMap - implementation that uses a HashMap to store the data * <li>MultiValuedLinkedHashMap - implementation that uses a LinkedHashMap as backing map * </ul> * <p> * The following decorators are provided in the package: * <ul> * <li>Transformed - transforms elements added to the MultiValuedMap * <li>Unmodifiable - ensures the collection cannot be altered * </ul> * * @version $Id$ */ package org.apache.commons.collections4.multimap;
/* * 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. */ /** * This package contains implementations of the {@link org.apache.commons.collections4.MultiValuedMap} interfaces. * A MultiValuedMap holds a collection of values against each key. * <p> * The following implementations are provided in the package: * <ul> * <li>MultiValuedHashMap - implementation that uses a HashMap to store the data * </ul> * <p> * The following decorators are provided in the package: * <ul> * <li>Transformed - transforms elements added to the MultiValuedMap * <li>Unmodifiable - ensures the collection cannot be altered * </ul> * * @version $Id$ */ package org.apache.commons.collections4.multimap;
Upgrade to v0.1.2 and properly add dictobj as an installation requirement.
from setuptools import setup import os def read(filename): fin = None data = None try: fin = open(filename) data = fin.read() finally: if fin is not None: fin.close() return data setup( name='jstree', version='0.1.2', author='William Grim', author_email='william@grimapps.com', url='https://github.com/grimwm/py-jstree', classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], description='A package that helps generate JSON data for jQuery jsTree.', long_description=read('README.txt') if os.path.exists('README.txt') else '', install_requires=['dictobj'], py_modules=['jstree'], test_suite='jstree_test', )
from setuptools import setup import os def read(filename): fin = None data = None try: fin = open(filename) data = fin.read() finally: if fin is not None: fin.close() return data setup( name='jstree', version='0.1.1', author='William Grim', author_email='william@grimapps.com', url='https://github.com/grimwm/py-jstree', classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], description='A package that helps generate JSON data for jQuery jsTree.', long_description=read('README.txt') if os.path.exists('README.txt') else '', requires=['dictobj'], py_modules=['jstree'], test_suite='jstree_test', )
Fix bug in isToday method
export default class Utils { static paddingZero(num) { return `0${num}`.slice(-2); } static toFormatDate(date) { const y = date.getFullYear(); const m = this.paddingZero(date.getMonth() + 1); const d = this.paddingZero(date.getDate()); return `${y}-${m}-${d}`; } static toDate(formatedDate) { const ary = formatedDate.split('-').map(s => parseInt(s, 10)); return new Date(ary[0], ary[1] - 1, ary[2], 0, 0, 0); } static getToday() { return this.toFormatDate(new Date()); } static getRelativeDate(formatedBaseDate, diff) { const bd = this.toDate(formatedBaseDate); const rd = new Date(bd.getFullYear(), bd.getMonth(), bd.getDate() + diff); return this.toFormatDate(rd); } static isToday(date) { const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0); return today.getTime() === this.toDate(date).getTime(); } }
export default class Utils { static paddingZero(num) { return `0${num}`.slice(-2); } static toFormatDate(date) { const y = date.getFullYear(); const m = this.paddingZero(date.getMonth() + 1); const d = this.paddingZero(date.getDate()); return `${y}-${m}-${d}`; } static toDate(formatedDate) { const ary = formatedDate.split('-').map(s => parseInt(s, 10)); return new Date(ary[0], ary[1] - 1, ary[2], 0, 0, 0); } static getToday() { return this.toFormatDate(new Date()); } static getRelativeDate(formatedBaseDate, diff) { const bd = this.toDate(formatedBaseDate); const rd = new Date(bd.getFullYear(), bd.getMonth(), bd.getDate() + diff); return this.toFormatDate(rd); } static isToday(date) { const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate(), 0, 0, 0); return today.getTime() === this.toDate(date).getTime(); } }
Fix the version to correct one
from setuptools import setup REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox' setup( author='Serenata de Amor', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'boto3', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL), name='serenata-toolbox', packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'], url=REPO_URL, version='9.1.0' )
from setuptools import setup REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox' setup( author='Serenata de Amor', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'boto3', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL), name='serenata-toolbox', packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'], url=REPO_URL, version='9.0.4' )
Fix wrong class name in CardSupportingText
import m from 'mithril'; import attributes from './attributes'; export let Card = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {shadow} = args; attr.class.push('mdl-card'); if(shadow) attr.class.push(`mdl-shadow--${shadow}dp`); return <div {...attr}>{children}</div>; } }; export let CardTitle = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {expand, size} = args; attr.class.push('mdl-card__title'); if(expand) attr.class.push('mdl-card--expand'); size = size || 2; return <div {...attr}><h2 class="mdl-card__title-text">{children}</h2></div>; } }; export let CardSupportingText = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {border, expand} = attr; attr.class.push('mdl-card__title-text'); if(border) attr.class.push('mdl-card--border'); if(expand) attr.class.push('mdl-card--expand'); return <div {...attr}>{children}</div>; } };
import m from 'mithril'; import attributes from './attributes'; export let Card = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {shadow} = args; attr.class.push('mdl-card'); if(shadow) attr.class.push(`mdl-shadow--${shadow}dp`); return <div {...attr}>{children}</div>; } }; export let CardTitle = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {expand, size} = args; attr.class.push('mdl-card__title'); if(expand) attr.class.push('mdl-card--expand'); size = size || 2; return <div {...attr}><h2 class="mdl-card__title-text">{children}</h2></div>; } }; export let CardSupportingText = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {border, expand} = attr; attr.class.push('mdl-card__title-text'); if(border) attr.class.push('mdl-shadow--border'); if(expand) attr.class.push('mdl-card--expand'); return <div {...attr}>{children}</div>; } };
WUI: Allow regex check on radio buttons on registration forms - There was a missing check on existing regex for radio buttons. There seems to be check only on input fields and text area like widgets.
package cz.metacentrum.perun.wui.registrar.widgets.items.validators; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; import cz.metacentrum.perun.wui.registrar.widgets.items.Radiobox; import org.gwtbootstrap3.client.ui.constants.ValidationState; /** * @author Ondrej Velisek <ondrejvelisek@gmail.com> */ public class RadioboxValidator extends PerunFormItemValidatorImpl<Radiobox> { @Override public boolean validateLocal(Radiobox radiobox) { if (radiobox.isRequired() && isNullOrEmpty(radiobox.getValue())) { setResult(Result.EMPTY); radiobox.setStatus(getTransl().cantBeEmpty(), ValidationState.ERROR); return false; } String regex = radiobox.getItemData().getFormItem().getRegex(); if (regex != null && !regex.equals("")) { RegExp regExp = RegExp.compile(regex); MatchResult matcher = regExp.exec(radiobox.getValue()); boolean matchFound = (matcher != null); // equivalent to regExp.test(inputStr); if(!matchFound){ setResult(Result.INVALID_FORMAT); radiobox.setStatus(getErrorMsgOrDefault(radiobox), ValidationState.ERROR); return false; } } radiobox.setStatus(ValidationState.SUCCESS); return true; } }
package cz.metacentrum.perun.wui.registrar.widgets.items.validators; import cz.metacentrum.perun.wui.registrar.widgets.items.Radiobox; import org.gwtbootstrap3.client.ui.constants.ValidationState; /** * @author Ondrej Velisek <ondrejvelisek@gmail.com> */ public class RadioboxValidator extends PerunFormItemValidatorImpl<Radiobox> { @Override public boolean validateLocal(Radiobox radiobox) { if (radiobox.isRequired() && isNullOrEmpty(radiobox.getValue())) { setResult(Result.EMPTY); radiobox.setStatus(getTransl().cantBeEmpty(), ValidationState.ERROR); return false; } radiobox.setStatus(ValidationState.SUCCESS); return true; } }
Refactor to avoid hardcoding model name
var modella = require('modella'); var test = require('tape'); var render = require('./'); var modelName = 'MyModel'; test('Model with no attributes', function(t) { var model = modella(modelName); t.equal(render(model), modelName); t.end(); }); test('Model with attributes', function(t) { var attributes = ['a', 'b', 'c']; var model = modella(modelName); attributes.forEach(function(attr) { model.attr(attr); }); t.equal( render(model), modelName + ':\n- a\n- b\n- c\n'); t.end(); }); test('Model with ID key', function(t) { var model = modella(modelName); model.attr('id'); t.equal( render(model), modelName + ':\n- id (primaryKey)\n'); t.end(); });
var modella = require('modella'); var test = require('tape'); var render = require('./'); var modelName = 'MyModel'; test('Model with no attributes', function(t) { var model = modella(modelName); t.equal(render(model), modelName); t.end(); }); test('Model with attributes', function(t) { var attributes = ['a', 'b', 'c']; var model = modella(modelName); attributes.forEach(function(attr) { model.attr(attr); }); t.equal( render(model), 'MyModel:\n- a\n- b\n- c\n'); t.end(); }); test('Model with ID key', function(t) { var model = modella(modelName); model.attr('id'); t.equal( render(model), 'MyModel:\n- id (primaryKey)\n'); t.end(); });
Add mode to fix error
var sys = require('sys'); var fs = require('fs'); var cache = {} function now() { return (new Date).getTime(); } exports.put = function(key, value, time) { fs.stat('cache', function (err, stats) { if (err) { fs.mkdirSync('cache', 0777) } fs.writeFile('cache/' + key, value, function (err) { if (err) { console.log('Error on set:' + err); } else { cache[key] = {expire: time + now()} } }); }); } exports.del = function(key) { fs.unlink('cache/' + key, function (err) { delete cache[key]; }); } exports.get = function(key) { var data = cache[key]; if (typeof data != "undefined") { if (isNaN(data.expire) || data.expire >= now()) { fs.readFile('cache/' + key, function (err, filedata) { if (err) { console.log('Error on get:' + err); return null; } else { return filedata; } }); } else { exports.del(key); } } return null; }
var sys = require('sys'); var fs = require('fs'); var cache = {} function now() { return (new Date).getTime(); } exports.put = function(key, value, time) { fs.stat('cache', function (err, stats) { if (err) { fs.mkdirSync('cache') } fs.writeFile('cache/' + key, value, function (err) { if (err) { console.log('Error on set:' + err); } else { cache[key] = {expire: time + now()} } }); }); } exports.del = function(key) { fs.unlink('cache/' + key, function (err) { delete cache[key]; }); } exports.get = function(key) { var data = cache[key]; if (typeof data != "undefined") { if (isNaN(data.expire) || data.expire >= now()) { fs.readFile('cache/' + key, function (err, filedata) { if (err) { console.log('Error on get:' + err); return null; } else { return filedata; } }); } else { exports.del(key); } } return null; }
Fix missing generator on Windows - Since compiler is not listed on settings, CMake is not able to detect a valid generator, using MingGW by default - Add topics to be used as tags for searching Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake class PEGTLConan(ConanFile): name = "pegtl" description = "C++ header-only parser combinator library for creating PEG parsers" homepage = "https://github.com/taocpp/PEGTL" topics = ("conan", "taocpp", "pegtl", "peg", "grammar", "parsing") url = homepage license = "MIT" author = "taocpp@icemx.net" exports = "LICENSE" exports_sources = "include/*", "CMakeLists.txt" settings = "compiler" generators = "cmake" no_copy_source = True def build(self): pass def package(self): cmake = CMake(self) cmake.definitions["PEGTL_BUILD_TESTS"] = "OFF" cmake.definitions["PEGTL_BUILD_EXAMPLES"] = "OFF" cmake.definitions["PEGTL_INSTALL_DOC_DIR"] = "licenses" cmake.configure() cmake.install() def package_id(self): self.info.header_only()
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake class PEGTLConan(ConanFile): name = "pegtl" description = "C++ header-only parser combinator library for creating PEG parsers" homepage = "https://github.com/taocpp/PEGTL" url = homepage license = "MIT" author = "taocpp@icemx.net" exports = "LICENSE" exports_sources = "include/*", "CMakeLists.txt" generators = "cmake" no_copy_source = True def build(self): pass def package(self): cmake = CMake(self) cmake.definitions["PEGTL_BUILD_TESTS"] = "OFF" cmake.definitions["PEGTL_BUILD_EXAMPLES"] = "OFF" cmake.definitions["PEGTL_INSTALL_DOC_DIR"] = "licenses" cmake.configure() cmake.install() def package_id(self): self.info.header_only()
fix(SvgIconWidget): Support old and new svg-loader
import React from 'react'; import PropTypes from 'prop-types'; import defaultIcon from '../../../../svg/kitware.svg'; export default function SvgIconWidget(props) { const { id, viewBox } = props.icon || {}; let xlink = id || props.icon; if (xlink[0] !== '#') { xlink = `#${xlink}`; } const style = Object.assign({}, props.style, { width: props.width, height: props.height, }); return ( <svg viewBox={viewBox || props.viewBox} style={style} className={props.className} onClick={props.onClick} > <use xlinkHref={xlink} /> </svg> ); } SvgIconWidget.propTypes = { className: PropTypes.string, height: PropTypes.string, icon: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), width: PropTypes.string, style: PropTypes.object, onClick: PropTypes.func, viewBox: PropTypes.string, }; SvgIconWidget.defaultProps = { className: '', icon: defaultIcon, style: {}, height: undefined, width: undefined, onClick: undefined, viewBox: '0 0 20 20', };
import React from 'react'; import PropTypes from 'prop-types'; import defaultIcon from '../../../../svg/kitware.svg'; export default function SvgIconWidget(props) { const style = Object.assign({}, props.style, { width: props.width, height: props.height, }); return ( <svg style={style} className={props.className} onClick={props.onClick}> <use xlinkHref={props.icon} /> </svg> ); } SvgIconWidget.propTypes = { className: PropTypes.string, height: PropTypes.string, icon: PropTypes.string, width: PropTypes.string, style: PropTypes.object, onClick: PropTypes.func, }; SvgIconWidget.defaultProps = { className: '', icon: defaultIcon, style: {}, height: undefined, width: undefined, onClick: undefined, };