text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Make sure that follow-file decodes utf-8 from its input Signed-off-by: Jason Bernardino Alonso <f71c42a1353bbcdbe07e24c2a1c893f8ea1d05ee@hackorp.com>
""" Utility functions for dhcp2nest """ from queue import Queue from subprocess import Popen, PIPE from threading import Thread def follow_file(fn, max_lines=100): """ Return a Queue that is fed lines (up to max_lines) from the given file (fn) continuously The implementation given here was inspired by http://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python """ fq = Queue(maxsize=max_lines) # Declare the helper routine def _follow_file_thread(fn, fq): # Use system tail with name-based following and retry p = Popen(["tail", "-F", fn], stdout=PIPE) # Loop forever on pulling data from tail line = True while line: line = p.stdout.readline().decode('utf-8') fq.put(line) # Spawn a thread to read data from tail Thread(target=_follow_file_thread, args=(fn, fq)).start() # Return the queue return fq
""" Utility functions for dhcp2nest """ from queue import Queue from subprocess import Popen, PIPE from threading import Thread def follow_file(fn, max_lines=100): """ Return a Queue that is fed lines (up to max_lines) from the given file (fn) continuously The implementation given here was inspired by http://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python """ fq = Queue(maxsize=max_lines) # Declare the helper routine def _follow_file_thread(fn, fq): # Use system tail with name-based following and retry p = Popen(["tail", "-F", fn], stdout=PIPE) # Loop forever on pulling data from tail line = True while line: line = p.stdout.readline() fq.put(line) # Spawn a thread to read data from tail Thread(target=_follow_file_thread, args=(fn, fq)).start() # Return the queue return fq
Update download links for CelebA files
from fuel.downloaders.base import default_downloader def fill_subparser(subparser): """Sets up a subparser to download the CelebA dataset file. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `celeba` command. """ urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1', 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1'] filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip'] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader
from fuel.downloaders.base import default_downloader def fill_subparser(subparser): """Sets up a subparser to download the CelebA dataset file. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `celeba` command. """ urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1', 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1'] filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip'] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader
Check in @ Fri Apr 29 10:34:20 IST 2016
var ServiceModel = require('../core/service-model'); module.exports = ServiceModel.create("Story", { url: '/story', userSpace: { field: "_user" }, timestamps: true, schema: { id: { type: Number, required: true, min: 1, autoIncrement: true, idField: true }, title: { type: String, required: true }, description: String, status: { type: String, required: true, default: 'new', enum: ['new', 'progress', 'done', 'hold'] }, createdDate: { type: Date, required: true, default: Date.now } }, // permissions: function() { // return { // item: { // read: ['None'], // write: ['None'], // delete: ['None'] // }, // bulk: { // read: ['None'], // write: ['None'], // delete: ['None'] // } // }; // }, configure: function() { // this.model.path('name').set(function(v) { // return capitalize(v); // }); } });
var ServiceModel = require('../core/service-model'); module.exports = ServiceModel.create("Story", { url: '/story', userSpace: { field: "_user" }, timestamps: true, schema: { id: { type: Number, required: true, min: 1, autoIncrement: true, idField: true }, title: { type: String, required: true }, description: String, status: { type: String, required: true, default: 'new', enum: ['new', 'progress', 'done', 'hold'] }, createdDate: { type: Date, required: true, default: Date.now } }, permissions: function() { return { item: { read: ['None'], write: ['None'], delete: ['None'] }, bulk: { read: ['None'], write: ['None'], delete: ['None'] } }; }, configure: function() { console.log('configure'); // this.model.path('name').set(function(v) { // return capitalize(v); // }); } });
Fix Markdown bug and correct license information
import pelican_bibtex from distutils.core import setup CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Science/Research Intended Audience :: Developers License :: Public Domain Programming Language :: Python Programming Language :: Python :: 3 Topic :: Software Development Operating System :: POSIX Operating System :: Unix """ LONG_DESCRIPTION = """\ Requirements ============ pelican\_bibtex requires pybtex. This plugin reads a user-specified BibTeX file and populates the context with a list of publications, ready to be used in your Jinja2 template. If the file is present and readable, you will be able to find the 'publications' variable in all templates. It is a list of tuples with the following fields: (key, text, bibtex, pdf, slides, poster) 1. key is the BibTeX key (identifier) of the entry. 2. text is the HTML formatted entry, generated by pybtex. 3. bibtex is a string containing BibTeX code for the entry, useful to make it available to people who want to cite your work. 4. pdf, slides, poster: in your BibTeX file, you can add these special fields """ setup( name='pelican_bibtex', description='Organize your scientific publications with BibTeX in Pelican', long_description=LONG_DESCRIPTION, version=pelican_bibtex.__version__, author='Vlad Niculae', author_email='vlad@vene.ro', url='https://pypi.python.org/pypi/pelican_bibtex', py_modules=['pelican_bibtex'], classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f] )
import pelican_bibtex from distutils.core import setup CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Science/Research Intended Audience :: Developers License :: OSI Approved Programming Language :: Python Programming Language :: Python :: 3 Topic :: Software Development Operating System :: POSIX Operating System :: Unix """ setup( name='pelican_bibtex', description='Manage your academic publications page with Pelican and BibTeX', long_description=open('Readme.md').read(), version=pelican_bibtex.__version__, author='Vlad Niculae', author_email='vlad@vene.ro', url='https://pypi.python.org/pypi/pelican_bibtex', py_modules=['pelican_bibtex'], classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], license='Public Domain' )
Add copyright header to migration
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jost@reciprocitylabs.com # Maintained By: jost@reciprocitylabs.com """Change conclusion dropdowns options in control assessment Revision ID: 29dca3ce0556 Revises: 2d8a46b1e4a4 Create Date: 2015-09-11 13:18:18.269109 """ # revision identifiers, used by Alembic. revision = '29dca3ce0556' down_revision = '2d8a46b1e4a4' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): sql = """ UPDATE control_assessments SET design = 'Ineffective' WHERE design = 'Material weakness' OR design = 'Significant deficiency' """ op.execute(sql) sql = """ UPDATE control_assessments SET operationally = 'Ineffective' WHERE operationally = 'Material weakness' OR operationally = 'Significant deficiency' """ op.execute(sql) def downgrade(): sql = """ UPDATE control_assessments SET design = 'Significant deficiency' WHERE design = 'Ineffective' """ op.execute(sql) sql = """ UPDATE control_assessments SET operationally = 'Significant deficiency' WHERE operationally = 'Ineffective' """ op.execute(sql)
"""Change conclusion dropdowns options in control assessment Revision ID: 29dca3ce0556 Revises: 2d8a46b1e4a4 Create Date: 2015-09-11 13:18:18.269109 """ # revision identifiers, used by Alembic. revision = '29dca3ce0556' down_revision = '2d8a46b1e4a4' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): sql = """ UPDATE control_assessments SET design = 'Ineffective' WHERE design = 'Material weakness' OR design = 'Significant deficiency' """ op.execute(sql) sql = """ UPDATE control_assessments SET operationally = 'Ineffective' WHERE operationally = 'Material weakness' OR operationally = 'Significant deficiency' """ op.execute(sql) def downgrade(): sql = """ UPDATE control_assessments SET design = 'Significant deficiency' WHERE design = 'Ineffective' """ op.execute(sql) sql = """ UPDATE control_assessments SET operationally = 'Significant deficiency' WHERE operationally = 'Ineffective' """ op.execute(sql)
Use the correct variable for the test
# -*- coding: utf-8 -*- def test_bar_fixture(testdir): """Make sure that pytest accepts our fixture.""" # create a temporary pytest test module testdir.makepyfile(""" def test_sth(bar): assert bar == "europython2015" """) # run pytest with the following cmd args result = testdir.runpytest( '--foo=something', '-v' ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ '*::test_a PASSED', ]) # make sure that that we get a '0' exit code for the testsuite assert result.ret == 0 def test_help_message(testdir): result = testdir.runpytest( '--help', ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ '{{cookiecutter.plugin_name}}:', '*--foo=DEST_FOO*Set the value for the fixture "bar".', ])
# -*- coding: utf-8 -*- def test_bar_fixture(testdir): """Make sure that pytest accepts our fixture.""" # create a temporary pytest test module testdir.makepyfile(""" def test_sth(bar): assert bar == "europython2015" """) # run pytest with the following cmd args result = testdir.runpytest( '--foo=something', '-v' ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ '*::test_a PASSED', ]) # make sure that that we get a '0' exit code for the testsuite assert result.ret == 0 def test_help_message(testdir): result = testdir.runpytest( '--help', ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ 'cat:', '*--foo=DEST_FOO*Set the value for the fixture "bar".', ])
Remove duplication and extra knowledge I guess we can trust when.isPromise here. Maybe we should consider using buster.assertions.add('isPromise')
(function(buster, fn, when) { var assert = buster.assert; function assertIsPromise(something) { var message = 'Object is not a promise'; buster.assert(when.isPromise(something), message); } function f(x, y) { return x + y; } buster.testCase('when/function', { 'apply': { 'should return a promise': function() { var result = fn.apply(f, [1, 2]); assertIsPromise(result); }, 'should accept values for arguments': function() { var result = fn.apply(f, [1, 2]); return when(result, function(result) { assert.equals(result, 3); }); }, }, 'call': { 'should return a promise': function() { var result = fn.call(f, 1, 2); assertIsPromise(result); }, 'should accept values for arguments': function() { var result = fn.call(f, 1, 2); return when(result, function(result) { assert.equals(result, 3); }); }, }, 'bind': { 'should return a function': function() { assert.isFunction(fn.bind(f, null)); } } }); })( this.buster || require('buster'), this.when_fn || require('../function'), this.when || require('../when') );
(function(buster, fn, when) { var assert = buster.assert; function f(x, y) { return x + y; } buster.testCase('when/function', { 'apply': { 'should return a promise': function() { var result = fn.apply(f, [1, 2]); assert(result && typeof result.then === 'function'); }, 'should accept values for arguments': function() { var result = fn.apply(f, [1, 2]); return when(result, function(result) { assert.equals(result, 3); }); }, }, 'call': { 'should return a promise': function() { var result = fn.call(f, 1, 2); assert(result && typeof result.then === 'function'); }, 'should accept values for arguments': function() { var result = fn.call(f, 1, 2); return when(result, function(result) { assert.equals(result, 3); }); }, }, 'bind': { 'should return a function': function() { assert.isFunction(fn.bind(f, null)); } } }); })( this.buster || require('buster'), this.when_fn || require('../function'), this.when || require('../when') );
Handle responce if no access
var https = require('https'); var inspect = require('eyes').inspector({ stream: null }); var querystring = require('querystring'); var xml2js = require('xml2js'); module.exports.access = function(data, callback){ var parser = new xml2js.Parser(); var stringData = querystring.stringify(data); var noAccess = new RegExp(/Access denied/); var options = { host: 'www.pivotaltracker.com', port: 443, path: '/services/v3/tokens/active', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': stringData.length } }; var req = https.request(options, function(res) { res.on('data', function(d) { if(noAccess.test(d.toString())){ return callback.call(this, null, {message: d.toString()}); } parser.parseString(d, function (err, result) { return callback.call(this, err, result); }); }); }); req.write(stringData); req.end(); req.on('error', function(e) { return callback.call(this, e); }); };
var https = require('https'); var inspect = require('eyes').inspector({ stream: null }); var querystring = require('querystring'); var xml2js = require('xml2js'); module.export.access = function(data, callback){ var parser = new xml2js.Parser(); var stringData = querystring.stringify(data); var options = { host: 'www.pivotaltracker.com', port: 443, path: '/services/v3/tokens/active', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': stringData.length } }; var req = https.request(options, function(res) { res.on('data', function(d) { parser.parseString(d, function (err, result) { return callback.call(this, err, result); }); }); }); req.write(stringData); req.end(); req.on('error', function(e) { return callback.call(this, e); }); };
Add callback for homepage javascript light POST request.
"use strict"; $(document).ready(function(){ var $btnLight = $("#btnLight"); var lightText = $btnLight.text(); var lightOn = (lightText == "Light Off"); function toggleGarageDoor() { $.post("/toggle"); } function turnLightOn() { $.post("/light?state=on", parseLightState); } function turnLightOff() { $.post("/light?state=off", parseLightState); } function parseLightState(data) { data = $.parseJSON(data); lightOn = data.LightOn; if (lightOn) { $btnLight.text("Light Off"); } else { $btnLight.text("Light On"); } if (!data.StateKnown) { $btnLight.prop('disabled', true); } } $("#btnDoorToggle").on("click", function( event ) { toggleGarageDoor(); }); $btnLight.on("click", function( event ) { if (lightOn) { turnLightOff(); } else { turnLightOn(); } }); });
"use strict"; $(document).ready(function(){ var $btnLight = $("#btnLight"); var lightText = $btnLight.text(); var lightOn; if (lightText = "Light On") { lightOn = true; } else { lightOn = false; } function toggleGarageDoor() { $.post("/toggle"); } function turnLightOn() { $.post("/light?state=on"); } function turnLightOff() { $.post("/light?state=off"); } $("#btnDoorToggle").on("click", function( event ) { toggleGarageDoor(); }); $btnLight.on("click", function( event ) { if (lightOn) { turnLightOff(); lightOn = false; $btnLight.text("Light On") } else { turnLightOn(); lightOn = true; $btnLight.text("Light Off") } }); });
Add scheduler entry for ldap sync
<?php namespace Myjob\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ \Myjob\Console\Commands\Inspire::class, \Myjob\Console\Commands\SendNotificationMails::class, \Myjob\Console\Commands\SyncLDAPStudents::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // Synchronise student list with the LDAP $schedule->command('syncstudents') ->weeklyOn(5, '4:00'); // Send notification mails $schedule->command('sendnotificationmails --subscribed=instantly') ->everyThirtyMinutes(); $schedule->command('sendnotificationmails --subscribed=daily') ->dailyAt('4:00'); $schedule->command('sendnotificationmails --subscribed=weekly') ->weeklyOn(6, '4:00'); } }
<?php namespace Myjob\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ \Myjob\Console\Commands\Inspire::class, \Myjob\Console\Commands\SendNotificationMails::class, \Myjob\Console\Commands\SyncLDAPStudents::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('sendnotificationmails --subscribed=instantly') ->everyThirtyMinutes(); $schedule->command('sendnotificationmails --subscribed=daily') ->dailyAt('4:00'); $schedule->command('sendnotificationmails --subscribed=weekly') ->weeklyOn(6, '4:00'); } }
[Misc] Work around bad design so that our component checker doesn't fail the build
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.wikimodel.xhtml.impl; import org.xwiki.component.annotation.Component; /** * @version $Id$ * @since 4.0M1 * @deprecated use org.xwiki.xml.internal.LocalEntityResolver instead */ @Deprecated // TODO: Work around the fact that LocalEntityResolver is a Component while org.xwiki.xml.internal.LocalEntityResolver // is not supposed to be one. This is a bad design since a non-component should not extend a component (it's dangerous // - @Inject-ed component will not be injected, and the extending class will inherit the @Component annotation, which // is bad - imagine for example that in the future we auto-generate components.txt based on the @Component annotation). @Component(staticRegistration = false) public class LocalEntityResolver extends org.xwiki.xml.internal.LocalEntityResolver { }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.wikimodel.xhtml.impl; /** * @version $Id$ * @since 4.0M1 * @deprecated use org.xwiki.xml.internal.LocalEntityResolver instead */ @Deprecated public class LocalEntityResolver extends org.xwiki.xml.internal.LocalEntityResolver { }
Use generic names for SMTP env variables
module.exports = { "allow_create_new_accounts" : true, "send_emails" : false, "application_sender_email" : process.env.SENDER_EMAIL || "email@test.com", // transports email via SMTP "email_smtp_transporter" : { "host" : process.env.SMTP_SERVER || "localhost", "port" : process.env.SMTP_PORT || 25, "auth" : { "user" : process.env.SMTP_LOGIN || "user", "pass" : process.env.SMTP_PASSWORD || "pass" } }, // transports emails via Mailgun REST API (which is 3x faster than SMTP) // precedes email_smtp_transporter if api_key and domain are set "email_mailgun_transporter" : { auth: { api_key: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN } }, "crypto_secret" : process.env.CRYPTO_SECRET || "!2~`HswpPPLa22+=±§sdq qwe,appp qwwokDF_", "application_domain" : process.env.APPLICATION_DOMAIN || "http://app.timeoff.management", "promotion_website_domain" : process.env.PROMOTION_WEBSITE_DOMAIN || "http://timeoff.management" }
module.exports = { "allow_create_new_accounts" : true, "send_emails" : false, "application_sender_email" : process.env.SENDER_EMAIL || "email@test.com", // transports email via SMTP "email_smtp_transporter" : { "host" : process.env.MAILGUN_SMTP_SERVER || "localhost", "port" : process.env.MAILGUN_SMTP_PORT || 25, "auth" : { "user" : process.env.MAILGUN_SMTP_LOGIN || "user", "pass" : process.env.MAILGUN_SMTP_PASSWORD || "pass" } }, // transports emails via Mailgun REST API (which is 3x faster than SMTP) // precedes email_smtp_transporter if api_key and domain are set "email_mailgun_transporter" : { auth: { api_key: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN } }, "crypto_secret" : process.env.CRYPTO_SECRET || "!2~`HswpPPLa22+=±§sdq qwe,appp qwwokDF_", "application_domain" : process.env.APPLICATION_DOMAIN || "http://app.timeoff.management", "promotion_website_domain" : process.env.PROMOTION_WEBSITE_DOMAIN || "http://timeoff.management" }
Fix infinite recursion. Compare addresses properly.
package main import ( "github.com/dimfeld/glog" "net" ) const ( WhiteList = iota BlackList ) type ListenFilter struct { net.Listener // BlackList or WhiteList. Behavior int FilterAddr map[string]bool } func (f *ListenFilter) Accept() (c net.Conn, err error) { for { c, err = f.Listener.Accept() if err != nil { return } addr := c.RemoteAddr().String() addr, _, err = net.SplitHostPort(addr) configured := f.FilterAddr[addr] if (configured && f.Behavior == WhiteList) || (!configured && f.Behavior == BlackList) { return } c.Close() glog.Infoln("Denied connection from", addr) } } func NewListenFilter(l net.Listener, behavior int) *ListenFilter { return &ListenFilter{ Listener: l, Behavior: behavior, FilterAddr: make(map[string]bool), } }
package main import ( "github.com/dimfeld/glog" "net" ) const ( WhiteList = iota BlackList ) type ListenFilter struct { net.Listener // BlackList or WhiteList. Behavior int FilterAddr map[string]bool } func (f *ListenFilter) Accept() (c net.Conn, err error) { for { c, err = f.Accept() if err != nil { return } addr := c.RemoteAddr().String() configured := f.FilterAddr[addr] if (configured && f.Behavior == WhiteList) || (!configured && f.Behavior == BlackList) { return } c.Close() glog.Infoln("Denied connection from", addr) } } func NewListenFilter(l net.Listener, behavior int) *ListenFilter { return &ListenFilter{ Listener: l, Behavior: behavior, FilterAddr: make(map[string]bool), } }
Reset movement speed after going through a teleporter
package com.mcjty.rftools.blocks.teleporter; import net.minecraft.entity.Entity; import net.minecraft.world.Teleporter; import net.minecraft.world.WorldServer; public class RfToolsTeleporter extends Teleporter { private final WorldServer worldServerInstance; private double x; private double y; private double z; public RfToolsTeleporter(WorldServer world, double x, double y, double z) { super(world); this.worldServerInstance = world; this.x = x; this.y = y; this.z = z; } @Override public void placeInPortal(Entity pEntity, double p2, double p3, double p4, float p5) { this.worldServerInstance.getBlock((int) this.x, (int) this.y, (int) this.z); //dummy load to maybe gen chunk pEntity.setPosition(this.x, this.y, this.z); pEntity.motionX = 0.0f; pEntity.motionY = 0.0f; pEntity.motionZ = 0.0f; } }
package com.mcjty.rftools.blocks.teleporter; import net.minecraft.entity.Entity; import net.minecraft.world.Teleporter; import net.minecraft.world.WorldServer; public class RfToolsTeleporter extends Teleporter { private final WorldServer worldServerInstance; private double x; private double y; private double z; public RfToolsTeleporter(WorldServer world, double x, double y, double z) { super(world); this.worldServerInstance = world; this.x = x; this.y = y; this.z = z; } @Override public void placeInPortal(Entity pEntity, double p2, double p3, double p4, float p5) { this.worldServerInstance.getBlock((int) this.x, (int) this.y, (int) this.z); //dummy load to maybe gen chunk pEntity.setPosition(this.x, this.y, this.z); // pEntity.setVelocity(); } }
Convert class to final with a private constructor vs abstracst +review REVIEW-6431
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.tasks.scala; public final class ZincScalaCompilerUtil { private ZincScalaCompilerUtil() { } public static final String ZINC_CACHE_HOME_DIR_SYSTEM_PROPERTY = "org.gradle.zinc.home.dir"; public static final String ZINC_DIR_SYSTEM_PROPERTY = "zinc.dir"; public static final String ZINC_DIR_IGNORED_MESSAGE = "In order to guarantee parallel safe Scala compilation, Gradle does not support the '" + ZINC_DIR_SYSTEM_PROPERTY + "' system property and ignores any value provided."; }
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.tasks.scala; public abstract class ZincScalaCompilerUtil { public static final String ZINC_CACHE_HOME_DIR_SYSTEM_PROPERTY = "org.gradle.zinc.home.dir"; public static final String ZINC_DIR_SYSTEM_PROPERTY = "zinc.dir"; public static final String ZINC_DIR_IGNORED_MESSAGE = "In order to guarantee parallel safe Scala compilation, Gradle does not support the '" + ZINC_DIR_SYSTEM_PROPERTY + "' system property and ignores any value provided."; }
FIX don loose context when creating from story form view
# -*- coding: utf-8 -*- from openerp import models, fields, api, _ class task(models.Model): _inherit = 'project.task' user_story = fields.Boolean( 'Is User Story?', default=False) @api.multi def action_open_task(self): print 'context', self._context return { 'name': _('User Story'), 'view_type': 'form', 'view_mode': 'form', # 'view_id': [res_id], 'res_model': 'project.task', 'context': self._context, 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'current', 'res_id': self.id, } class project(models.Model): _inherit = 'project.project' user_story_ids = fields.One2many( 'project.task', 'project_id', domain=[('user_story', '=', True)], context={'default_user_story': True}, string='User Stories', )
# -*- coding: utf-8 -*- from openerp import models, fields, api, _ class task(models.Model): _inherit = 'project.task' user_story = fields.Boolean( 'Is User Story?', default=False) @api.multi def action_open_task(self): return { 'name': _('User Story'), 'view_type': 'form', 'view_mode': 'form', # 'view_id': [res_id], 'res_model': 'project.task', # 'context': "{'type':'out_invoice'}", 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'current', 'res_id': self.id, } class project(models.Model): _inherit = 'project.project' user_story_ids = fields.One2many( 'project.task', 'project_id', domain=[('user_story', '=', True)], context={'default_user_story': True}, string='User Stories', )
Add python_requires to help pip
#!/usr/bin/env python import sys from setuptools import setup requires = ['six'] tests_require = ['mock', 'nose'] if sys.version_info[0] == 2: requires += ['python-dateutil>=1.0, != 2.0'] else: # Py3k requires += ['python-dateutil>=2.0'] with open('README.rst') as f: readme = f.read() setup( name='freezegun', version='0.3.10', description='Let your Python tests travel through time', long_desciption=readme, author='Steve Pulec', author_email='spulec@gmail.com', url='https://github.com/spulec/freezegun', packages=['freezegun'], install_requires=requires, tests_require=tests_require, include_package_data=True, license='Apache 2.0', python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
#!/usr/bin/env python import sys from setuptools import setup requires = ['six'] tests_require = ['mock', 'nose'] if sys.version_info[0] == 2: requires += ['python-dateutil>=1.0, != 2.0'] else: # Py3k requires += ['python-dateutil>=2.0'] with open('README.rst') as f: readme = f.read() setup( name='freezegun', version='0.3.10', description='Let your Python tests travel through time', long_desciption=readme, author='Steve Pulec', author_email='spulec@gmail.com', url='https://github.com/spulec/freezegun', packages=['freezegun'], install_requires=requires, tests_require=tests_require, include_package_data=True, license='Apache 2.0', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
Check for git prior to calling shell.exec
'use strict'; var shell = require('shelljs'); var nameCache = {}; var emailCache = {}; /** * @mixin * @alias actions/user */ var user = module.exports; /** * Git related properties * * The value will come from the global scope or the project scope (it'll take * what git will use in the current context) * @prop name {String|undefined} - Current git name * @prop email {String|undefined} - Current git email */ user.git = { get name() { var name = nameCache[process.cwd()]; if (name) { return name; } if (shell.which('git')) { name = shell.exec('git config --get user.name', { silent: true }).output.trim(); nameCache[process.cwd()] = name; } return name; }, get email() { var email = emailCache[process.cwd()]; if (email) { return email; } if (shell.which('git')) { email = shell.exec('git config --get user.email', { silent: true }).output.trim(); emailCache[process.cwd()] = email; } return email; } };
'use strict'; var shell = require('shelljs'); var nameCache = {}; var emailCache = {}; /** * @mixin * @alias actions/user */ var user = module.exports; /** * Git related properties * * The value will come from the global scope or the project scope (it'll take * what git will use in the current context) * @prop name {String|undefined} - Current git name * @prop email {String|undefined} - Current git email */ user.git = { get name() { var name = nameCache[process.cwd()]; if (name) { return name; } name = shell.exec('git config --get user.name', { silent: true }).output.trim(); nameCache[process.cwd()] = name; return name; }, get email() { var email = emailCache[process.cwd()]; if (email) { return email; } email = shell.exec('git config --get user.email', { silent: true }).output.trim(); emailCache[process.cwd()] = email; return email; } };
Add corrected key for pageinfocolumns
import React from 'react'; import PropTypes from 'prop-types'; import { FlexColumn } from '../FlexColumn'; import { PageInfoRow } from './PageInfoRow'; export const PageInfoColumn = ({ columnData, isEditingDisabled, titleColor, infoColor, numberOfLines, titleTextAlign, }) => ( <FlexColumn flex={1}> {columnData.map(({ onPress, editableType, title, info }, idx) => ( <PageInfoRow titleTextAlign={titleTextAlign} numberOfLines={numberOfLines} // eslint-disable-next-line react/no-array-index-key key={`${title}${info}${idx}`} isEditingDisabled={isEditingDisabled} titleColor={titleColor} infoColor={infoColor} onPress={onPress} editableType={editableType} info={info} title={title} /> ))} </FlexColumn> ); PageInfoColumn.defaultProps = { isEditingDisabled: false, numberOfLines: 1, titleTextAlign: 'left', }; PageInfoColumn.propTypes = { // eslint-disable-next-line react/forbid-prop-types columnData: PropTypes.array.isRequired, isEditingDisabled: PropTypes.bool, titleColor: PropTypes.string.isRequired, infoColor: PropTypes.string.isRequired, numberOfLines: PropTypes.number, titleTextAlign: PropTypes.string, };
import React from 'react'; import PropTypes from 'prop-types'; import { FlexColumn } from '../FlexColumn'; import { PageInfoRow } from './PageInfoRow'; export const PageInfoColumn = ({ columnData, isEditingDisabled, titleColor, infoColor, numberOfLines, titleTextAlign, }) => ( <FlexColumn flex={1}> {columnData.map(({ onPress, editableType, title, info }) => ( <PageInfoRow titleTextAlign={titleTextAlign} numberOfLines={numberOfLines} key={`${title}${info}`} isEditingDisabled={isEditingDisabled} titleColor={titleColor} infoColor={infoColor} onPress={onPress} editableType={editableType} info={info} title={title} /> ))} </FlexColumn> ); PageInfoColumn.defaultProps = { isEditingDisabled: false, numberOfLines: 1, titleTextAlign: 'left', }; PageInfoColumn.propTypes = { // eslint-disable-next-line react/forbid-prop-types columnData: PropTypes.array.isRequired, isEditingDisabled: PropTypes.bool, titleColor: PropTypes.string.isRequired, infoColor: PropTypes.string.isRequired, numberOfLines: PropTypes.number, titleTextAlign: PropTypes.string, };
Add time sorting from db
<?php class db_dcs_log extends CI_Model{ function get_all(){ $this->db->order_by('time', 'desc'); $q = $this->db->get('dcs_log'); return $q->result(); } function get_date(){ $this->db->distinct(); $this->db->select('date(time) as date'); $this->db->order_by('time', 'desc'); $q = $this->db->get('dcs_log'); return $q->result(); } function get_date_detail($param){ $this->db->where('date(time)', date('Y-m-d', strtotime($param))); $this->db->order_by('time', 'desc'); $q = $this->db->get('dcs_log'); return $q->result(); } function get_today(){ $this->db->where('date(time)', date('Y-m-d')); $this->db->order_by('time', 'desc'); $q = $this->db->get('dcs_log'); return $q->result(); } function insert($data){ $this->db->insert('dcs_log', $data); } }
<?php class db_dcs_log extends CI_Model{ function get_all(){ $q = $this->db->get('dcs_log'); return $q->result(); } function get_date(){ $this->db->distinct(); $this->db->select('date(time) as date'); $this->db->order_by('time', 'desc'); $q = $this->db->get('dcs_log'); return $q->result(); } function get_date_detail($param){ $this->db->where('date(time)', date('Y-m-d', strtotime($param))); $this->db->order_by('time', 'desc'); $q = $this->db->get('dcs_log'); return $q->result(); } function get_today(){ $this->db->where('date(time)', date('Y-m-d')); $this->db->order_by('time', 'desc'); $q = $this->db->get('dcs_log'); return $q->result(); } function insert($data){ $this->db->insert('dcs_log', $data); } }
Format the message string after translating, not before This makes sure we use the right translated string. Contributes to Ultimaker/Cura#57
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from UM.Job import Job from UM.Application import Application from UM.Message import Message import os.path from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") ## A Job subclass that performs mesh loading. # # The result of this Job is a MeshData object. class ReadMeshJob(Job): def __init__(self, filename): super().__init__() self._filename = filename self._handler = Application.getInstance().getMeshFileHandler() self._device = Application.getInstance().getStorageDevice("LocalFileStorage") def getFileName(self): return self._filename def run(self): loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}").format(self._filename), lifetime = 0, dismissable = False) loading_message.setProgress(-1) loading_message.show() self.setResult(self._handler.read(self._filename, self._device)) loading_message.hide() result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}").format(self._filename)) result_message.show()
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from UM.Job import Job from UM.Application import Application from UM.Message import Message import os.path from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") ## A Job subclass that performs mesh loading. # # The result of this Job is a MeshData object. class ReadMeshJob(Job): def __init__(self, filename): super().__init__() self._filename = filename self._handler = Application.getInstance().getMeshFileHandler() self._device = Application.getInstance().getStorageDevice("LocalFileStorage") def getFileName(self): return self._filename def run(self): loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}".format(self._filename)), lifetime = 0, dismissable = False) loading_message.setProgress(-1) loading_message.show() self.setResult(self._handler.read(self._filename, self._device)) loading_message.hide() result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}".format(self._filename))) result_message.show()
Make llama command spit out random llamas
package ml.duncte123.skybot.commands.animals; import ml.duncte123.skybot.Command; import ml.duncte123.skybot.utils.AirUtils; import ml.duncte123.skybot.utils.URLConnectionReader; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import org.json.JSONArray; import org.json.JSONObject; public class LlamaCommand extends Command { @Override public boolean called(String[] args, GuildMessageReceivedEvent event) { return true; } @Override public void action(String[] args, GuildMessageReceivedEvent event) { try { String jsonString = URLConnectionReader.getText("https://lucoa.systemexit.co.uk/animals/api/llama/random"); JSONObject jsonObject = new JSONObject(jsonString); event.getChannel().sendMessage(AirUtils.embedImage(jsonObject.getString("file"))).queue(); } catch (Exception e) { e.printStackTrace(); event.getChannel().sendMessage(AirUtils.embedMessage("ERROR: " + e.getMessage())).queue(); } } @Override public String help() { return "Here is a llama"; } }
package ml.duncte123.skybot.commands.animals; import ml.duncte123.skybot.Command; import ml.duncte123.skybot.utils.AirUtils; import ml.duncte123.skybot.utils.URLConnectionReader; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import org.json.JSONArray; import org.json.JSONObject; public class LlamaCommand extends Command { @Override public boolean called(String[] args, GuildMessageReceivedEvent event) { return true; } @Override public void action(String[] args, GuildMessageReceivedEvent event) { try { String jsonString = URLConnectionReader.getText("https://lucoa.systemexit.co.uk/animals/api/llama"); JSONArray jsonArray = new JSONArray(jsonString); JSONObject jsonObject = new JSONObject(String.valueOf(jsonArray.get(0))); event.getChannel().sendMessage(AirUtils.embedImage(jsonObject.getString("file"))).queue(); } catch (Exception e) { e.printStackTrace(); event.getChannel().sendMessage(AirUtils.embedMessage("ERROR: " + e.getMessage())).queue(); } } @Override public String help() { return "Here is a llama"; } }
Make sure heroku is in accepted hosts
from logtacts.settings import * import dj_database_url DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL')) SECRET_KEY = get_env_variable("LOGTACTS_SECRET_KEY") ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', '.pebble.ink', '.logtacts.com', '.contactotter.com', '.herokuapp.com', ] SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_FRAME_DENY = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True STATIC_URL = '//logtacts.s3.amazonaws.com/assets/' INSTALLED_APPS += ( 'gunicorn', 'opbeat.contrib.django', ) MIDDLEWARE_CLASSES = ( 'opbeat.contrib.django.middleware.OpbeatAPMMiddleware', ) + MIDDLEWARE_CLASSES OPBEAT = { 'ORGANIZATION_ID': get_env_variable("OPBEAT_ORG_ID"), 'APP_ID': get_env_variable("OPBEAT_APP_ID"), 'SECRET_TOKEN': get_env_variable("OPBEAT_SECRET_KEY"), }
from logtacts.settings import * import dj_database_url DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL')) SECRET_KEY = get_env_variable("LOGTACTS_SECRET_KEY") ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', '.pebble.ink', '.logtacts.com', '.contactotter.com', ] SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_FRAME_DENY = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True STATIC_URL = '//logtacts.s3.amazonaws.com/assets/' INSTALLED_APPS += ( 'gunicorn', 'opbeat.contrib.django', ) MIDDLEWARE_CLASSES = ( 'opbeat.contrib.django.middleware.OpbeatAPMMiddleware', ) + MIDDLEWARE_CLASSES OPBEAT = { 'ORGANIZATION_ID': get_env_variable("OPBEAT_ORG_ID"), 'APP_ID': get_env_variable("OPBEAT_APP_ID"), 'SECRET_TOKEN': get_env_variable("OPBEAT_SECRET_KEY"), }
Make abstract test case class abstract
<?php /* * This file is part of Laravel GitLab. * * (c) Vincent Klaiber <hello@vinkla.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vinkla\Tests\GitLab; use GrahamCampbell\TestBench\AbstractPackageTestCase; /** * This is the abstract test case class. * * @author Vincent Klaiber <hello@vinkla.com> */ abstract class AbstractTestCase extends AbstractPackageTestCase { /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return 'Vinkla\GitLab\GitLabServiceProvider'; } }
<?php /* * This file is part of Laravel GitLab. * * (c) Vincent Klaiber <hello@vinkla.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vinkla\Tests\GitLab; use GrahamCampbell\TestBench\AbstractPackageTestCase; /** * This is the abstract test case class. * * @author Vincent Klaiber <hello@vinkla.com> */ class AbstractTestCase extends AbstractPackageTestCase { /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return 'Vinkla\GitLab\GitLabServiceProvider'; } }
Replace `\` with `/` in resolved path This fixes url rebasing on windows. We probably should use something other than the `path` module for resolving, but that can come at a later time – this'll do for now.
import postcss from 'postcss' import { readFileSync as slurp } from 'fs' import { resolve, isAbsolute } from 'path' import { parse as parseUrl } from 'url' import { default as rebaseUrl } from 'postcss-url' export default function rebase(pkg, opts, filename) { return postcss([ rebaseUrl({ url: (url, decl, from, dirname, to, options, result) => { let parsed = parseUrl(url, true, true) if (parsed.host || isAbsolute(parsed.path)) { return url } else { let resolved = pkg.relative(resolve(pkg.root, opts.lib, parsed.path)) return resolved.replace(/\\/g, '/') } } }) ]).process(slurp(filename, 'utf8')) }
import postcss from 'postcss' import { readFileSync as slurp } from 'fs' import { resolve, isAbsolute } from 'path' import { parse as parseUrl } from 'url' import { default as rebaseUrl } from 'postcss-url' export default function rebase(pkg, opts, filename) { return postcss([ rebaseUrl({ url: (url, decl, from, dirname, to, options, result) => { let parsed = parseUrl(url, true, true) if (parsed.host || isAbsolute(parsed.path)) { return url } else { let resolved = pkg.relative(resolve(pkg.root, opts.lib, parsed.path)) return resolved } } }) ]).process(slurp(filename, 'utf8')) }
Update current parse, add alt parse frame
#!/bin/env python3 from sys import argv def main(): parseArgs() print("Nope.") print(argv) # go through via characters def parseArgsChar(): pass() # while this works, it only works when _h_m_s format # might want to not do that def parseArgs(): if len(argv) > 1: time = argv[1].split('h') if 'm' not in time[0] and 'n' not in time[0]: hours = time[0] else: hours = 0 print(time) print(hours) time = time[1].split('m') if 's' not in time[0]: minutes = time[0] else: minutes = 0 print(time) print(minutes) time = time[1].split('s') if time: seconds = time[0] else: seconds = 0 print(time) print(seconds) else: print("commands go here") if __name__ == "__main__": main()
#!/bin/env python3 from sys import argv def main(): parseArgs() print("Nope.") print(argv) def parseArgs(): if len(argv) > 1: time = argv[1].split('h') print(time) if 'm' not in time[0] and 'n' not in time[0]: hours = time[0] else: house = 0 time = time[0].split('m') print(time) if 's' not in time[0]: minutes = time[0] else: minutes = 0 time = time[0].split('s') if time: seconds = time[0] else: print("commands go here") if __name__ == "__main__": main()
Connect popover to redux store
import React from 'react'; import * as styles from './PopOver.scss'; const PopOver = ({ order, text, xPos, yPos, totalLength, tutorialActive, currentlyDisplayedTutorial, viewNext, viewPrevious, closeTutorial }) => { const first = order === 1; const last = order === totalLength; const active = tutorialActive && currentlyDisplayedTutorial === order; const buttonText = last ? 'End' : 'Next'; const nextAction = last ? closeTutorial : viewNext; if (!active) { return null; } return ( <div className={styles.modal} style={{ top: yPos, left: xPos }}> <div className={styles.text}> {text} </div> <div className={styles.footer}> {first ? (<div />) : (<button onClick={viewPrevious}>Prev</button>)} <button onClick={nextAction}>{buttonText}</button> </div> </div> ); }; export default PopOver;
import React from 'react'; import * as styles from './PopOver.scss'; const PopOver = ({ next, active, first, last, previous, xPos, yPos, children }) => { if (!active) { return null; } const text = last ? 'End' : 'Next'; return ( <div className={styles.modal} style={{ top: yPos, left: xPos }}> <div className={styles.text}> {children} </div> <div className={styles.footer}> {first ? <div /> : <button onClick={previous}>Prev</button> } <button onClick={next}>{text}</button> </div> </div> ); }; export default PopOver;
Add share() method to view factory contract.
<?php namespace Illuminate\Contracts\View; interface Factory { /** * Determine if a given view exists. * * @param string $view * @return bool */ public function exists($view); /** * Get the evaluated view contents for the given view. * * @param string $view * @param array $data * @param array $mergeData * @return \Illuminate\Contracts\View\View */ public function make($view, $data = array(), $mergeData = array()); /** * Add a piece of shared data to the environment. * * @param string $key * @param mixed $value * @return void */ public function share($key, $value = null) /** * Register a view composer event. * * @param array|string $views * @param \Closure|string $callback * @param int|null $priority * @return array */ public function composer($views, $callback, $priority = null); /** * Register a view creator event. * * @param array|string $views * @param \Closure|string $callback * @return array */ public function creator($views, $callback); /** * Add a new namespace to the loader. * * @param string $namespace * @param string|array $hints * @return void */ public function addNamespace($namespace, $hints); }
<?php namespace Illuminate\Contracts\View; interface Factory { /** * Determine if a given view exists. * * @param string $view * @return bool */ public function exists($view); /** * Get the evaluated view contents for the given view. * * @param string $view * @param array $data * @param array $mergeData * @return \Illuminate\Contracts\View\View */ public function make($view, $data = array(), $mergeData = array()); /** * Register a view composer event. * * @param array|string $views * @param \Closure|string $callback * @param int|null $priority * @return array */ public function composer($views, $callback, $priority = null); /** * Register a view creator event. * * @param array|string $views * @param \Closure|string $callback * @return array */ public function creator($views, $callback); /** * Add a new namespace to the loader. * * @param string $namespace * @param string|array $hints * @return void */ public function addNamespace($namespace, $hints); }
Send first_name and last_name in JSON.
from rest_framework import serializers from roledb.models import User class UserSerializer(serializers.ModelSerializer): roles = serializers.SerializerMethodField('role_data') attributes = serializers.SerializerMethodField('attribute_data') class Meta: model = User fields = ('username','first_name','last_name','roles','attributes') def role_data(self, obj): data = [] for a in obj.attendances.all(): d = {} d['school'] = a.school.school_id d['group'] = a.group d['role'] = a.role.name data.append(d) return data def attribute_data(self, obj): data = [] for a in obj.attributes.all(): d = {} d['name'] = a.attribute.name d['value'] = a.value data.append(d) return data
from rest_framework import serializers from roledb.models import User class UserSerializer(serializers.ModelSerializer): roles = serializers.SerializerMethodField('role_data') attributes = serializers.SerializerMethodField('attribute_data') class Meta: model = User fields = ('username', 'roles', 'attributes') def role_data(self, obj): data = [] for a in obj.attendances.all(): d = {} d['school'] = a.school.school_id d['group'] = a.group d['role'] = a.role.name data.append(d) return data def attribute_data(self, obj): data = [] for a in obj.attributes.all(): d = {} d['name'] = a.attribute.name d['value'] = a.value data.append(d) return data
Tag an image based on detected visual content which mean running a CNN on top of it
<?php /* * PixLab PHP Client which is just a single class PHP file without any dependency that you can get from Github * https://github.com/symisc/pixlab-php */ require_once "pixlab.php"; # Tag an image based on detected visual content which mean running a CNN on top of it. # https://pixlab.io/#/cmd?id=tagimg for more info. # Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info. $img = 'https://s-media-cache-ak0.pinimg.com/originals/35/d0/f6/35d0f6ee0e40306c41cfd714c625f78e.jpg'; # Your PixLab key $key = 'My_Pixlab_Key'; /* Process */ $pix = new Pixlab($key); if( !$pix->get('tagimg',array( 'img' => $img, 'key' => $key )) ){ echo $pix->get_error_message(); die; } /* Grab the total number of tags */ $tags = $pix->json->tags; echo "Total number of tags: ".count($tags)."\n"; foreach($tags as $tag){ echo "Tag = ".$tag->name.", Confidence: ".$tag->confidence."\n"; }
<?php /* * PixLab PHP Client which is just a single class PHP file without any dependency that you can get from Github * https://github.com/symisc/pixlab-php */ require_once "pixlab.php"; # Tag an image based on detected visual content which mean running a CNN on top of it. # https://pixlab.io/#/cmd?id=tagimg for more info. # Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info. $img = 'https://s-media-cache-ak0.pinimg.com/originals/35/d0/f6/35d0f6ee0e40306c41cfd714c625f78e.jpg'; # Your PixLab key $key = 'My_Pixlab_Key'; /* Process */ $pix = new Pixlab($key); if( !$pix->get('tagimg',array( 'img' => $img, 'key' => $key )) ){ echo $pix->get_error_message(); die; } /* Grab the total number of tags */ $tags = $pix->json->tags; echo "Total number of detected tags: ".count($tags)."\n"; foreach($tags as $tag){ echo "Tag = ".$tag->name.", Confidence: ".$tag->confidence."\n"; }
Migrate to Spring Boot 1.4.0
/* Copyright (c) 2016 Sebastian Schmidt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.swm.nis.logicaldecoding.application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import de.swm.nis.logicaldecoding.RefreshCacheApplication; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = RefreshCacheApplication.class) public class RefreshCacheApplicationTests { @Test public void contextLoads() { } }
/* Copyright (c) 2016 Sebastian Schmidt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.swm.nis.logicaldecoding.application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import de.swm.nis.logicaldecoding.RefreshCacheApplication; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = RefreshCacheApplication.class) public class RefreshCacheApplicationTests { @Test public void contextLoads() { } }
Remove unnecessary visibility modifiers in interface
package im.delight.android.ddp.db; /* * Copyright (c) delight.im <info@delight.im> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import im.delight.android.ddp.Fields; /** Storage for data that exposes write access */ public interface DataStore { void onDataAdded(String collectionName, String documentID, Fields newValues); void onDataChanged(String collectionName, String documentID, Fields updatedValues, Fields removedValues); void onDataRemoved(String collectionName, String documentID); }
package im.delight.android.ddp.db; /* * Copyright (c) delight.im <info@delight.im> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import im.delight.android.ddp.Fields; /** Storage for data that exposes write access */ public interface DataStore { public void onDataAdded(String collectionName, String documentID, Fields newValues); public void onDataChanged(String collectionName, String documentID, Fields updatedValues, Fields removedValues); public void onDataRemoved(String collectionName, String documentID); }
Set root option on history.start.
/* global BackboneWizard, Backbone, $ */ window.BackboneWizard = { Models: {}, Collections: {}, Views: {}, Controllers: {}, Routers: {}, init: function () { 'use strict'; var self = this; self.itemList = new BackboneWizard.Collections.ItemList(); self.transaction = new BackboneWizard.Models.Transaction(); self.state = new BackboneWizard.Models.State({ 'current': 'index' }); $.get('./appData.json').done(function (data) { self.transaction.set(data); }); $.get('./itemData.json').done(function (data) { self.itemList.add(data, { merge: true }); }); self.wizardRouter = new BackboneWizard.Routers.WizardRouter(); Backbone.history.start({ root: '/backbone/' }); } }; $(document).ready(function () { 'use strict'; BackboneWizard.init(); });
/* global BackboneWizard, Backbone, $ */ window.BackboneWizard = { Models: {}, Collections: {}, Views: {}, Controllers: {}, Routers: {}, init: function () { 'use strict'; var self = this; self.itemList = new BackboneWizard.Collections.ItemList(); self.transaction = new BackboneWizard.Models.Transaction(); self.state = new BackboneWizard.Models.State({ 'current': 'index' }); $.get('./appData.json').done(function (data) { self.transaction.set(data); }); $.get('./itemData.json').done(function (data) { self.itemList.add(data, { merge: true }); }); self.wizardRouter = new BackboneWizard.Routers.WizardRouter(); Backbone.history.start(); } }; $(document).ready(function () { 'use strict'; BackboneWizard.init(); });
Move disparate functions into groups of functions to call.
/* global SW:true */ var getUnassigned = function (assignmentCount) { var ticketTotal = 0; for (var property in assignmentCount) { ticketTotal += assignmentCount[property]; } var unassignedTickets = data.tickets.length - ticketTotal; console.log('unassignedTickets'); return unassignedTickets; } var countAssignments = function(ticket){ if (assignmentCount[ticket.assignee.id]){ assignmentCount[ticket.assignee.id] += 1; } else { assignmentCount[ticket.assignee.id] = 1; } }; $(document).ready(function(){ 'use strict'; console.log( 'Doing SW things!' ); var card = new SW.Card(); var helpdesk = card.services('helpdesk'); var assignmentCount = {}; helpdesk.request('tickets') .then( function(data){ $.each(data.tickets, function(index, ticket){ countAssignments(ticket); }); console.log( assignmentCount + 'final' ); getUnassigned(assignmentCount); }); });
/* global SW:true */ $(document).ready(function(){ 'use strict'; console.log( 'Doing SW things!' ); var card = new SW.Card(); var helpdesk = card.services('helpdesk'); var assignmentCount = {}; helpdesk .request('tickets') .then( function(data){ console.log( 'got data!' ); $.each(data.tickets, function(index, ticket){ console.log( ticket.assignee.id ); if (assignmentCount[ticket.assignee.id]){ assignmentCount[ticket.assignee.id] += 1; } else { assignmentCount[ticket.assignee.id] = 1; } console.log( 'assignmentCount object' ); console.log( assignmentCount ); }); console.log( assignmentCount + 'final' ); var ticketTotal = 0; for (var property in assignmentCount) { ticketTotal += assignmentCount[property]; } var unassignedTickets = data.tickets.length - ticketTotal; console.log('unassignedTickets'); console.log(unassignedTickets); }); });
Enable reindexing with v2 reindexer
from django.core.management import BaseCommand, CommandError from corehq.pillows.case import get_couch_case_reindexer, get_sql_case_reindexer from corehq.pillows.case_search import get_couch_case_search_reindexer from corehq.pillows.xform import get_couch_form_reindexer, get_sql_form_reindexer class Command(BaseCommand): args = 'index' help = 'Reindex a pillowtop index' def handle(self, index, *args, **options): reindex_fns = { 'case': get_couch_case_reindexer, 'form': get_couch_form_reindexer, 'sql-case': get_sql_case_reindexer, 'sql-form': get_sql_form_reindexer, 'case-search': get_couch_case_search_reindexer } if index not in reindex_fns: raise CommandError('Supported indices to reindex are: {}'.format(','.join(reindex_fns.keys()))) reindexer = reindex_fns[index]() reindexer.reindex()
from django.core.management import BaseCommand, CommandError from corehq.pillows.case import get_couch_case_reindexer, get_sql_case_reindexer from corehq.pillows.xform import get_couch_form_reindexer, get_sql_form_reindexer class Command(BaseCommand): args = 'index' help = 'Reindex a pillowtop index' def handle(self, index, *args, **options): reindex_fns = { 'case': get_couch_case_reindexer, 'form': get_couch_form_reindexer, 'sql-case': get_sql_case_reindexer, 'sql-form': get_sql_form_reindexer, } if index not in reindex_fns: raise CommandError('Supported indices to reindex are: {}'.format(','.join(reindex_fns.keys()))) reindexer = reindex_fns[index]() reindexer.reindex()
Change title to Base maps
package mil.nga.mapcache.preferences; import android.os.Bundle; import android.view.MenuItem; import androidx.appcompat.app.AppCompatActivity; import mil.nga.mapcache.R; public class BasemapSettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preferences); getSupportActionBar().setTitle("Base maps"); // Adds back arrow button to action bar getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new TileUrlFragment()).commit(); } /** * Add back arrow button listener * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } }
package mil.nga.mapcache.preferences; import android.os.Bundle; import android.view.MenuItem; import androidx.appcompat.app.AppCompatActivity; import mil.nga.mapcache.R; public class BasemapSettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preferences); getSupportActionBar().setTitle("Saved Tile URLs"); // Adds back arrow button to action bar getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new TileUrlFragment()).commit(); } /** * Add back arrow button listener * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } }
Remove After - logically redundant
package org.gluster.test; import java.io.File; import junit.framework.Assert; import org.apache.hadoop.fs.glusterfs.GlusterFUSEInputStream; import org.apache.hadoop.fs.glusterfs.GlusterFUSEOutputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestGlusterFuseInputStream{ String infile ; @Before public void create() throws Exception{ //setup: no need for gluster specific path, since its just reading from local path infile=File.createTempFile("TestGlusterFuseInputStream"+System.currentTimeMillis(),"txt").getAbsolutePath(); new File(infile).deleteOnExit(); final GlusterFUSEOutputStream stream = new GlusterFUSEOutputStream(infile,true); stream.write("hello there, certainly, there is some data in this stream".getBytes()); stream.close(); } @Test public void testDoubleClose() throws Exception{ //test GlusterFUSEInputStream gfi= new GlusterFUSEInputStream (new File(infile), null, "localhost") ; //assert that Position is updated (necessary for hbase to function properly) gfi.seek(2); Assert.assertEquals(2,gfi.getPos()); gfi.close(); //cleanup new File(infile).delete(); } }
package org.gluster.test; import java.io.File; import junit.framework.Assert; import org.apache.hadoop.fs.glusterfs.GlusterFUSEInputStream; import org.apache.hadoop.fs.glusterfs.GlusterFUSEOutputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestGlusterFuseInputStream{ String infile ; @Before public void create() throws Exception{ //setup: no need for gluster specific path, since its just reading from local path infile=File.createTempFile("TestGlusterFuseInputStream"+System.currentTimeMillis(),"txt").getAbsolutePath(); new File(infile).deleteOnExit(); final GlusterFUSEOutputStream stream = new GlusterFUSEOutputStream(infile,true); stream.write("hello there, certainly, there is some data in this stream".getBytes()); stream.close(); } @After public void cleanUp() throws Exception{ new File(infile).delete(); } @Test public void testDoubleClose() throws Exception{ //test GlusterFUSEInputStream gfi= new GlusterFUSEInputStream (new File(infile), null, "localhost") ; //assert that Position is updated (necessary for hbase to function properly) gfi.seek(2); Assert.assertEquals(2,gfi.getPos()); gfi.close(); //cleanup new File(infile).delete(); } }
Use local variables to make methods parse easier. * Stash local variables, and use them inline (seems to be easier to read to me). * Do not require function prototype extensions (`Function.prototype.on` was used before).
import Ember from 'ember'; var observer = Ember.observer; var on = Ember.on; var computed = Ember.computed; export default Ember.Component.extend({ tagName: 'span', theme: 'default', off: 'Off', on: 'On', toggled: false, inputClasses: on('init', observer('themeClass', 'inputCheckbox', function () { var themeClass = this.get('themeClass'); var input = this.get('inputCheckbox'); if (input) { var inputClasses = input.get('classNames') || []; input.set('classNames', inputClasses.concat(['x-toggle', themeClass])); } }), themeClass: computed('theme', function () { var theme = this.get('theme') || 'default'; return 'x-toggle-' + theme; }), generatedId: computed(function () { return this.get('elementId') + '-x-toggle'; }), wasToggled: on('init', observer('toggled', function () { var toggled = this.get('toggled'); this.sendAction('toggle', toggled); }) });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'span', theme: 'default', off: 'Off', on: 'On', toggled: false, inputClasses: Ember.observer('themeClass', 'inputCheckbox', function () { var themeClass = this.get('themeClass'); var input = this.get('inputCheckbox'); if (input) { var inputClasses = input.get('classNames') || []; input.set('classNames', inputClasses.concat(['x-toggle', themeClass])); } }).on('init'), themeClass: Ember.computed('theme', function () { var theme = this.get('theme') || 'default'; return 'x-toggle-' + theme; }), generatedId: Ember.computed(function () { return this.get('elementId') + '-x-toggle'; }), wasToggled: Ember.observer('toggled', function () { var toggled = this.get('toggled'); this.sendAction('toggle', toggled); }).on('init') });
Fix gofmt relaxed problem with common
package common import ( "encoding/json" ) type TaskData struct { FullyQualifiedNodeName string RexFullyQualifiedNodeName string Zookeepers []string ClusterName string NodeID string } func (s *TaskData) Serialize() ([]byte, error) { b, err := json.Marshal(s) return b, err } func DeserializeTaskData(data []byte) (TaskData, error) { t := TaskData{} err := json.Unmarshal(data, &t) return t, err } type CoordinatedData struct { NodeName string DisterlPort int PBPort int HTTPPort int Hostname string } func (s *CoordinatedData) Serialize() ([]byte, error) { b, err := json.Marshal(s) return b, err } func DeserializeCoordinatedData(data []byte) (CoordinatedData, error) { t := CoordinatedData{} err := json.Unmarshal(data, &t) return t, err } type DisterlData struct { NodeName string DisterlPort int } func (s *DisterlData) Serialize() ([]byte, error) { b, err := json.Marshal(s) return b, err } func DeserializeDisterlData(data []byte) (DisterlData, error) { t := DisterlData{} err := json.Unmarshal(data, &t) return t, err }
package common import ( "encoding/json" ) type TaskData struct { FullyQualifiedNodeName string RexFullyQualifiedNodeName string Zookeepers []string ClusterName string NodeID string } func (s *TaskData) Serialize() ([]byte, error) { b, err := json.Marshal(s) return b, err } func DeserializeTaskData(data []byte) (TaskData, error) { t := TaskData{} err := json.Unmarshal(data, &t) return t, err } type CoordinatedData struct { NodeName string DisterlPort int PBPort int HTTPPort int Hostname string } func (s *CoordinatedData) Serialize() ([]byte, error) { b, err := json.Marshal(s) return b, err } func DeserializeCoordinatedData(data []byte) (CoordinatedData, error) { t := CoordinatedData{} err := json.Unmarshal(data, &t) return t, err } type DisterlData struct { NodeName string DisterlPort int } func (s *DisterlData) Serialize() ([]byte, error) { b, err := json.Marshal(s) return b, err } func DeserializeDisterlData(data []byte) (DisterlData, error) { t := DisterlData{} err := json.Unmarshal(data, &t) return t, err }
Add multi team output in markers Signed-off-by: Dominik Pataky <46f1a0bd5592a2f9244ca321b129902a06b53e03@netdecorator.org>
import json from flask import Blueprint, render_template import database as db from database.model import Team bp = Blueprint('public', __name__) @bp.route("/map") def map_page(): return render_template("public/map.html") @bp.route("/map_teams") def map_teams(): qry = db.session.query(Team).filter_by(confirmed=True).filter_by(deleted=False).filter_by(backup=False) data_dict = {} for item in qry: if item.location is not None: ident = "%s%s" % (item.location.lat, item.location.lon) if ident not in data_dict: data_dict[ident] = { "lat": item.location.lat, "lon": item.location.lon, "name": item.name } else: data_dict[ident]["name"] += "<br>" + item.name data = [entry for entry in data_dict.itervalues()] return json.dumps(data)
import json from flask import Blueprint, render_template import database as db from database.model import Team bp = Blueprint('public', __name__) @bp.route("/map") def map_page(): return render_template("public/map.html") @bp.route("/map_teams") def map_teams(): qry = db.session.query(Team).filter_by(confirmed=True).filter_by(deleted=False).filter_by(backup=False) data = [] for item in qry: if item.location is not None: data.append({"lat": item.location.lat, "lon": item.location.lon, "name": item.name}) return json.dumps(data)
Replace map with a list comprehension.
# -*- coding: utf-8 -*- """ traceview.formatters This module contains functions used to format TraceView API results. """ from collections import namedtuple def identity(results): return results def tuplify(results, class_name='Result'): if 'fields' in results and 'items' in results: return _tuplify_timeseries(results, class_name) return _tuplify_dict(results, class_name) def _tuplify_timeseries(results, class_name): tuple_name = '{name}Tuple'.format(name=class_name) nt = namedtuple(tuple_name, results['fields']) return [nt(*item) for item in results['items']] def _tuplify_dict(results, class_name): tuple_name = '{name}Tuple'.format(name=class_name) nt = namedtuple(tuple_name, results.keys()) return nt(**results)
# -*- coding: utf-8 -*- """ traceview.formatters This module contains functions used to format TraceView API results. """ from collections import namedtuple def identity(results): return results def tuplify(results, class_name='Result'): if 'fields' in results and 'items' in results: return _tuplify_timeseries(results, class_name) return _tuplify_dict(results, class_name) def _tuplify_timeseries(results, class_name): tuple_name = '{name}Tuple'.format(name=class_name) nt = namedtuple(tuple_name, results['fields']) return map(nt._make, results['items']) def _tuplify_dict(results, class_name): tuple_name = '{name}Tuple'.format(name=class_name) nt = namedtuple(tuple_name, results.keys()) return nt(**results)
Fix continuation whitespace and add extras_require
from setuptools import setup, find_packages import re with open("README.rst", mode='r') as readme_file: text=readme_file.read() #below version code pulled from requests module with open('__init__.py', 'r') as fd: version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version_number: raise RuntimeError('Cannot find version information') setup( name='pyautoupdate', version=version_number, packages=find_packages(), description='Interface to allow python programs to automatically update', long_description=text, url='https://github.com/rlee287/pyautoupdate', install_requires=['requests'], extras_require={ 'testing': ['pytest','coverage'] }, package_data={ 'testing':['*.rst']}, license="LGPL 2.1" )
from setuptools import setup, find_packages import re with open("README.rst", mode='r') as readme_file: text=readme_file.read() #below version code pulled from requests module with open('__init__.py', 'r') as fd: version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version_number: raise RuntimeError('Cannot find version information') setup( name='pyautoupdate', version=version_number, packages=find_packages(), description='Interface to allow python programs to automatically update', long_description=text, url='https://github.com/rlee287/pyautoupdate', install_requires=['requests>=2.6'], package_data={ 'testing':['*.rst']}, license="LGPL 2.1" )
Throw an exception if env vars not set.
"use strict"; var os = require("os"), path = require("path"), express = require("express"), routes = require("./routes"); var app = express(), hostname = os.hostname(), port = process.env.CONPA_PORT || 8080, documentRoot = path.join(__dirname, "../client"), liveUrl = process.env.CONPA_LIVE_URL, testingUrl = process.env.CONPA_TEST_URL; if (!liveUrl && !testingUrl) { throw new Error("CONPA_LIVE_URL and CONPA_TEST_URL not defined."); } process.on("uncaughtException", function (err) { console.log(err.stack); }); app.get("/status", function (req, res) { res.send("ConPA is running on " + hostname + " on " + process.version); }); app.use(express.static(documentRoot)); routes.configure(app, { crm: { liveDomain: hostname, // liveDomain: "foo.com", liveUrl: liveUrl, liveDb: "conpa", testingUrl: testingUrl, testingDb: "conpa-staging", design: "ConPA" } }); app.listen(port, function () { console.log("ConPA document root is " + documentRoot); console.log("ConPA listening on http://" + hostname + ":" + port); });
"use strict"; var os = require("os"), path = require("path"), express = require("express"), routes = require("./routes"); var app = express(), hostname = os.hostname(), port = process.env.CONPA_PORT || 8080, documentRoot = path.join(__dirname, "../client"); process.on("uncaughtException", function (err) { console.log(err.stack); }); app.get("/status", function (req, res) { res.send("ConPA is running on " + hostname + " on " + process.version); }); app.use(express.static(documentRoot)); routes.configure(app, { crm: { liveDomain: hostname, // liveDomain: "foo.com", liveUrl: process.env.CONPA_LIVE_URL, liveDb: "conpa", testingUrl: process.env.CONPA_TEST_URL, testingDb: "conpa-staging", design: "ConPA" } }); app.listen(port, function () { console.log("ConPA document root is " + documentRoot); console.log("ConPA listening on http://" + hostname + ":" + port); });
Add success notifcation for project creation
define(['react', 'collections/projects', 'models/project', 'rsvp', 'controllers/notifications'], function(React, Collection, Model, RSVP, Notifications) { var projects = new Collection(); var getProjects = function() { return new RSVP.Promise(function(resolve, reject) { projects.fetch({ success: resolve, error: reject }); }); }; var createProject = function(name, description) { console.log(name, description); return new RSVP.Promise(function(resolve, reject) { var model = new Model(); model.save({name: name, description: description}, { success: function(model) { Notifications.success('Success', 'Created new project "' + model.get('name') + '"'); resolve(model); }, error: function(model, response) { reject(response); } }); }); }; return { create: createProject, get: getProjects }; });
define(['react', 'collections/projects', 'models/project', 'rsvp'], function(React, Collection, Model, RSVP) { var projects = new Collection(); var getProjects = function() { return new RSVP.Promise(function(resolve, reject) { projects.fetch({ success: resolve, error: reject }); }); }; var createProject = function(name, description) { console.log(name, description); return new RSVP.Promise(function(resolve, reject) { var model = new Model(); model.save({name: name, description: description}, { success: function(model) { resolve(model); }, error: function(model, response) { reject(response); } }); }); }; return { create: createProject, get: getProjects }; });
[refactor] Make selector more specific To avoid conflicts with future examples.
import React, { Component } from 'react' import * as d3 from 'd3' class SelectionAndData extends Component { componentDidMount() { const rectWidth = 50 const height = 200 var data = [100, 250, 175, 200, 120] d3.selectAll('.rect-1') .data(data) .attr('x', (d, i) => i * rectWidth) .attr('y', d => height - d) .attr('width', rectWidth) .attr('height', d => d) .attr('fill', 'blue') .attr('stroke', '#fff') } render() { return ( <svg> <rect class='rect-1' /> <rect class='rect-1' /> <rect class='rect-1' /> <rect class='rect-1' /> <rect class='rect-1' /> </svg> ) } } export default SelectionAndData;
import React, { Component } from 'react' import * as d3 from 'd3' class SelectionAndData extends Component { componentDidMount() { const rectWidth = 50 const height = 200 var data = [100, 250, 175, 200, 120] d3.selectAll('rect') .data(data) .attr('x', (d, i) => i * rectWidth) .attr('y', d => height - d) .attr('width', rectWidth) .attr('height', d => d) .attr('fill', 'blue') .attr('stroke', '#fff') } render() { return ( <svg> <rect /> <rect /> <rect /> <rect /> <rect /> </svg> ) } } export default SelectionAndData;
Fix ES index script with updated param
from website.app import setup_django setup_django() from website import search from website.search.elastic_search import delete_doc from osf.models import Preprint, AbstractNode import progressbar # To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es def main(): """ Temporary script for updating elastic search after the node-preprint divorce - Removes nodes from the index that are categorized as preprints - Adds these nodes to the index, this time categorized as nodes - Adds preprints to the index, categorized as preprints """ preprints = Preprint.objects progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start() for i, p in enumerate(preprints.all(), 1): progress_bar.update(i) search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint if p.node: delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint search.search.update_node(p.node, bulk=False, async_update=False) # create new index for node (this time categorized as a node) progress_bar.finish() if __name__ == '__main__': main()
from website.app import setup_django setup_django() from website import search from website.search.elastic_search import delete_doc from osf.models import Preprint, AbstractNode import progressbar # To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es def main(): """ Temporary script for updating elastic search after the node-preprint divorce - Removes nodes from the index that are categorized as preprints - Adds these nodes to the index, this time categorized as nodes - Adds preprints to the index, categorized as preprints """ preprints = Preprint.objects progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start() for i, p in enumerate(preprints.all(), 1): progress_bar.update(i) search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint if p.node: delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint search.search.update_node(p.node, bulk=False, async=False) # create new index for node (this time categorized as a node) progress_bar.finish() if __name__ == '__main__': main()
Add a bit of documentation on what AsyncCommand is.
from collections import namedtuple from django.core.management.base import BaseCommand Progress = namedtuple('Progress', ['progress', 'overall']) class AsyncCommand(BaseCommand): """A management command with added convenience functions for displaying progress to the user. Rather than implementing handle() (as is for BaseCommand), subclasses, must implement handle_async(), which accepts the same arguments as handle(). If ran from the command line, AsynCommand displays a progress bar to the user. If ran asynchronously through kolibri.tasks.schedule_command(), AsyncCommand sends results through the Progress class to the main Django process. Anyone who knows the task id for the command instance can check the intermediate progress by looking at the task's AsyncResult.result variable. """ CELERY_PROGRESS_STATE_NAME = "PROGRESS" def _identity(*args, **kwargs): # heh, are we all just NoneTypes after all? pass def handle(self, *args, **options): self.update_state = options.pop("update_state", self._identity) self.handle_async(*args, **options) def set_progress(self, progress, overall=None, message=None): overall = overall or self.get_overall() progress = Progress(progress, overall) self.update_state(state=self.CELERY_PROGRESS_STATE_NAME, meta=progress) def get_overall(): pass def set_overall(): pass
from collections import namedtuple from django.core.management.base import BaseCommand Progress = namedtuple('Progress', ['progress', 'overall']) class AsyncCommand(BaseCommand): CELERY_PROGRESS_STATE_NAME = "PROGRESS" def handle(self, *args, **options): self.update_state = options.pop("update_state", id) self.handle_async(*args, **options) def set_progress(self, progress, overall=None, message=None): overall = overall or self.get_overall() progress = Progress(progress, overall) self.update_state(state=self.CELERY_PROGRESS_STATE_NAME, meta=progress) def get_overall(): pass def set_overall(): pass
Allow anonymous on loadpage service
<?php /** * Created by PhpStorm. * User: d.baudry * Date: 12/10/2017 * Time: 16:12 */ namespace GameScoreBundle\Service; use UserBundle\Entity\User; class LoadPageLogWriter { public function test(\DateTime $date, $user) { if ($user) { $userId = $user->getId(); $userName = $user->getUsername(); } else { $userId = 0; $userName = 'Anonymous'; } $logFilePath = '..\web\files\homepage_loads.txt'; $logData = $date->format('Y-m-d H:i:s') . ' : ' .'Home visited' . ' : ' . $userName . ' (id:' . $userId .')' . PHP_EOL; file_put_contents($logFilePath, $logData, FILE_APPEND | LOCK_EX); } }
<?php /** * Created by PhpStorm. * User: d.baudry * Date: 12/10/2017 * Time: 16:12 */ namespace GameScoreBundle\Service; use UserBundle\Entity\User; class LoadPageLogWriter { public function test(\DateTime $date, User $user) { $logFilePath = '..\web\files\homepage_loads.txt'; $logData = $date->format('Y-m-d H:i:s') . ' : ' .'Home visited' . ' : ' . $user->getUsername() . ' (id:' . $user->getId() .')' . PHP_EOL; file_put_contents($logFilePath, $logData, FILE_APPEND | LOCK_EX); } }
Revert "set opennms home for JMXDataCollectionConfigFactory" This reverts commit 201fab95419f57ce48ed00c7b77522d89034359f.
package org.opennms.netmgt.config; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class JMXDataCollectionConfigFactoryTest { @Test // Tests that the JmxDataCollectionConfigFactory also supports/implements the split config feature. public void shouldSupportSplitConfig() throws FileNotFoundException { File jmxCollectionConfig = new File("src/test/resources/etc/jmx-datacollection-split.xml"); Assert.assertTrue("JMX configuration file is not readable", jmxCollectionConfig.canRead()); FileInputStream configFileStream = new FileInputStream(jmxCollectionConfig); JMXDataCollectionConfigFactory factory = new JMXDataCollectionConfigFactory(configFileStream); Assert.assertNotNull(factory.getJmxCollection("jboss")); Assert.assertNotNull(factory.getJmxCollection("jsr160")); Assert.assertEquals(8, factory.getJmxCollection("jboss").getMbeanCount()); Assert.assertEquals(4, factory.getJmxCollection("jsr160").getMbeanCount()); } }
package org.opennms.netmgt.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /* @RunWith(OpenNMSJUnit4ClassRunner.class) @ContextConfiguration(locations={ "classpath:/emptyContext.xml" }) @TestExecutionListeners({ OpenNMSConfigurationExecutionListener.class }) */ public class JMXDataCollectionConfigFactoryTest { @Before public void setUp() { System.setProperty("opennms.home", new File("target/test-classes").getAbsolutePath()); } @Test // Tests that the JmxDataCollectionConfigFactory also supports/implements the split config feature. public void shouldSupportSplitConfig() throws FileNotFoundException { File jmxCollectionConfig = new File("src/test/resources/etc/jmx-datacollection-split.xml"); Assert.assertTrue("JMX configuration file is not readable", jmxCollectionConfig.canRead()); FileInputStream configFileStream = new FileInputStream(jmxCollectionConfig); JMXDataCollectionConfigFactory factory = new JMXDataCollectionConfigFactory(configFileStream); Assert.assertNotNull(factory.getJmxCollection("jboss")); Assert.assertNotNull(factory.getJmxCollection("jsr160")); Assert.assertEquals(8, factory.getJmxCollection("jboss").getMbeanCount()); Assert.assertEquals(4, factory.getJmxCollection("jsr160").getMbeanCount()); } }
Fix args err in wheel test
# coding: utf-8 # Import Salt Testing libs from __future__ import absolute_import import integration # Import Salt libs import salt.wheel class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn): def setUp(self): self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config'))) def test_list_all(self): ret = self.wheel.cmd('key.list_all', print_event=False) for host in ['minion', 'sub_minion']: self.assertIn(host, ret['minions']) def test_gen(self): ret = self.wheel.cmd('key.gen', kwarg={'id_': 'soundtechniciansrock'}, print_event=False) self.assertIn('pub', ret) self.assertIn('priv', ret) self.assertTrue( ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----')) self.assertTrue( ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----')) if __name__ == '__main__': from integration import run_tests run_tests(KeyWheelModuleTest, needs_daemon=True)
# coding: utf-8 # Import Salt Testing libs from __future__ import absolute_import import integration # Import Salt libs import salt.wheel class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn): def setUp(self): self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config'))) def test_list_all(self): ret = self.wheel.cmd('key.list_all', print_event=False) for host in ['minion', 'sub_minion']: self.assertIn(host, ret['minions']) def test_gen(self): ret = self.wheel.cmd('key.gen', id_='soundtechniciansrock', print_event=False) self.assertIn('pub', ret) self.assertIn('priv', ret) self.assertTrue( ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----')) self.assertTrue( ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----')) if __name__ == '__main__': from integration import run_tests run_tests(KeyWheelModuleTest, needs_daemon=True)
Revert "Handle second service UUID better." Realized I actually made the url parsing worse, this isn't what we wanted.
# Author: Braedy Kuzma from django.conf.urls import url from . import views urlpatterns = [ url(r'^posts/$', views.PostsView.as_view(), name='posts'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(), name='post'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$', views.CommentView.as_view(), name='comments'), url(r'^author/posts/$', views.PostsView.as_view(), name='authorpost'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(), name='author'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$', views.AuthorFriendsView.as_view(), name='friends'), url(r'^friendrequest/$', views.FriendRequestView.as_view(), name='friendrequest'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/' r'(?P<other>[\w\-\.]+(:\d{2,5})?(/\w+)*/)$', views.AuthorIsFriendsView.as_view(), name='isfriends') ]
# Author: Braedy Kuzma from django.conf.urls import url from . import views urlpatterns = [ url(r'^posts/$', views.PostsView.as_view(), name='posts'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(), name='post'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$', views.CommentView.as_view(), name='comments'), url(r'^author/posts/$', views.PostsView.as_view(), name='authorpost'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(), name='author'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$', views.AuthorFriendsView.as_view(), name='friends'), url(r'^friendrequest/$', views.FriendRequestView.as_view(), name='friendrequest'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/' r'(?P<other>[\w\-\.]+(:\d{2,5})?(/[0-9a-fA-F\-]+)*/)$', views.AuthorIsFriendsView.as_view(), name='isfriends') ]
Revert "removing protocol relative url"
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-g-map', included: function(app, parentAddon) { var target = (parentAddon || app); target.import('vendor/addons.css'); }, contentFor: function(type, config) { var content = ''; if (type === 'head') { var src = "//maps.googleapis.com/maps/api/js"; var gMapConfig = config['g-map'] || {}; var params = []; var key = gMapConfig.key; if (key) { params.push('key=' + encodeURIComponent(key)); } var libraries = gMapConfig.libraries; if (libraries && libraries.length) { params.push('libraries=' + encodeURIComponent(libraries.join(','))); } var protocol = gMapConfig.protocol; if (protocol) { src = protocol + ":" + src; } src += '?' + params.join('&'); content = '<script type="text/javascript" src="' + src + '"></script>'; } return content; } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-g-map', included: function(app, parentAddon) { var target = (parentAddon || app); target.import('vendor/addons.css'); }, contentFor: function(type, config) { var content = ''; if (type === 'head') { var src = "https://maps.googleapis.com/maps/api/js"; var gMapConfig = config['g-map'] || {}; var params = []; var key = gMapConfig.key; if (key) { params.push('key=' + encodeURIComponent(key)); } var libraries = gMapConfig.libraries; if (libraries && libraries.length) { params.push('libraries=' + encodeURIComponent(libraries.join(','))); } var protocol = gMapConfig.protocol; if (protocol) { src = protocol + ":" + src; } src += '?' + params.join('&'); content = '<script type="text/javascript" src="' + src + '"></script>'; } return content; } };
Add fast path for comparing to an identical (interned) keyword
// (c) 2012 B Smith-Mannschott -- Distributed under the Eclipse Public License package bpsm.edn.model; import bpsm.edn.parser.util.Interner; public final class Keyword implements Named, Comparable<Keyword> { private final Symbol sym; public final String getPrefix() { return sym.getPrefix(); } public final String getName() { return sym.getName(); } public static Keyword newKeyword(Symbol sym) { return INTERNER.intern(sym, new Keyword(sym)); } private Keyword(Symbol sym) { if (sym == null) { throw new NullPointerException(); } this.sym = sym; } public String toString() { return ":" + sym.toString(); } public int compareTo(Keyword o) { if (this==o) return 0; return sym.compareTo(o.sym); } private static final Interner<Symbol, Keyword> INTERNER = new Interner<Symbol, Keyword>(); }
// (c) 2012 B Smith-Mannschott -- Distributed under the Eclipse Public License package bpsm.edn.model; import bpsm.edn.parser.util.Interner; public final class Keyword implements Named, Comparable<Keyword> { private final Symbol sym; public final String getPrefix() { return sym.getPrefix(); } public final String getName() { return sym.getName(); } public static Keyword newKeyword(Symbol sym) { return INTERNER.intern(sym, new Keyword(sym)); } private Keyword(Symbol sym) { if (sym == null) { throw new NullPointerException(); } this.sym = sym; } public String toString() { return ":" + sym.toString(); } public int compareTo(Keyword o) { return sym.compareTo(o.sym); } private static final Interner<Symbol, Keyword> INTERNER = new Interner<Symbol, Keyword>(); }
Add model to controller to avoid inflection error
<?php /** * Este archivo contiene toda la logica de negocio asociada a los detalles de las vacaciones. * * PHP versions 5 * * @filesource * @copyright Copyright 2007-2009, Pragmatia * @link http://www.pragmatia.com * @package pragtico * @subpackage app.controllers * @since Pragtico v 1.0.0 * @version $Revision: 971 $ * @modifiedby $LastChangedBy: mradosta $ * @lastmodified $Date: 2009-09-16 11:51:11 -0300 (Wed, 16 Sep 2009) $ * @author Martin Radosta <mradosta@pragmatia.com> */ /** * La clase encapsula la logica de negocio asociada a los detalles de las vacaciones. * * @package pragtico * @subpackage app.controllers */ class VacacionesDetallesController extends AppController { var $uses = 'VacacionesDetalle'; } ?>
<?php /** * Este archivo contiene toda la logica de negocio asociada a los detalles de las vacaciones. * * PHP versions 5 * * @filesource * @copyright Copyright 2007-2009, Pragmatia * @link http://www.pragmatia.com * @package pragtico * @subpackage app.controllers * @since Pragtico v 1.0.0 * @version $Revision: 971 $ * @modifiedby $LastChangedBy: mradosta $ * @lastmodified $Date: 2009-09-16 11:51:11 -0300 (Wed, 16 Sep 2009) $ * @author Martin Radosta <mradosta@pragmatia.com> */ /** * La clase encapsula la logica de negocio asociada a los detalles de las vacaciones. * * @package pragtico * @subpackage app.controllers */ class VacacionesDetallesController extends AppController { } ?>
Update error handling and handled partials 1. Updated so as an error is logged rather than reported as an error as this will stop the watcher which could be annoying - although may be a preference option? 2. Added logic to ignore a partial (doesn't log) essentially a sass file prefixed with '_'
var es = require('event-stream') , clone = require('clone') , sass = require('node-sass') , path = require('path') , gutil = require('gulp-util') , ext = gutil.replaceExtension ; module.exports = function (options) { var opts = options ? clone(options) : {}; function nodeSass (file, cb) { // file is on object passed in by gulp // file.contents is always a Buffer if (path.basename(file.path).indexOf('_') === 0) { //gutil.log('[gulp-sass] Partial: ' + path.basename(file.path) + ' ignored'); return cb(); } if (file.isNull()) { gutil.log('[gulp-sass] Empty file: ' + path.basename(file.path) + ' ignored'); return cb(); } opts.data = file.contents.toString(); opts.success = function (css) { file.path = ext(file.path, '.css'); file.shortened = file.shortened && ext(file.shortened, '.css'); file.contents = new Buffer(css); cb(null, file); } opts.error = function (err) { //return cb(new gutil.PluginError('gulp-imagemin', err)); gutil.log('[gulp-sass] Error: ' + err); return cb(); } sass.render(opts); } return es.map(nodeSass); }
var es = require('event-stream') , clone = require('clone') , sass = require('node-sass') , ext = require('gulp-util').replaceExtension ; module.exports = function (options) { var opts = options ? clone(options) : {}; function nodeSass (file, cb) { if (file.isNull()) { return cb(null, file); } opts.data = file.contents.toString(); opts.success = function (css) { file.path = ext(file.path, '.css'); file.shortened = file.shortened && ext(file.shortened, '.css'); file.contents = new Buffer(css); cb(null, file); } opts.error = function (err) { cb(err); } sass.render(opts); } return es.map(nodeSass); }
Rename rank field to avoid column name clash
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('leaderboard_rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "leaderboard_rank")
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "rank")
[DDW-596] Improve electron process webpack plugin
const { exec } = require('child_process'); class ManageElectronProcessPlugin { apply(compiler) { if (compiler.options.watch) { let electronMainProcess = null; let isMainProcessBeingRestarted = false; compiler.hooks.done.tap( 'RestartElectronPlugin', () => { if (electronMainProcess === null) { electronMainProcess = exec("yarn electron ."); electronMainProcess.once('close', () => { electronMainProcess = null; if (isMainProcessBeingRestarted) { electronMainProcess = exec("yarn electron ."); isMainProcessBeingRestarted = false; } }); } else if (!isMainProcessBeingRestarted) { isMainProcessBeingRestarted = true; electronMainProcess.kill(); } } ); } } } module.exports = ManageElectronProcessPlugin;
const { exec } = require('child_process'); class ManageElectronProcessPlugin { apply(compiler) { if (compiler.options.watch) { let electron = null; compiler.hooks.done.tap( 'RestartElectronPlugin', () => { if (electron === null) { electron = exec("yarn electron ."); electron.once('close', () => { electron = null; }); } else { electron.kill(); electron = exec("yarn electron ."); } } ); } } } module.exports = ManageElectronProcessPlugin;
Test fix for errors caused by CWD being different when using a systemd initiated service as compared to npm start or node ./
/* Created by 'myth' on June 30. 2015 CognacTime is licenced under the MIT licence. */ var fs = require('fs') , express = require('express') , expresshbs = require('express-handlebars') , io = require('socket.io') , log = require('./logging') , pkg = require('../package.json') , config = require('../config.json') , routes = require('../routes/core') , path = require('path') // Initialize the express app ct = express() // Set logging middleware ct.use(require('morgan')('combined', {'stream': log.stream})) // Set static ct.use('/static', express.static('public')) // Set view engine ct.engine('hbs', expresshbs({ defaultLayout: 'main', extname: '.hbs' })) ct.set('views', path.join(__dirname, '../views')) ct.set('view engine', 'hbs') // Set core routes ct.use('/', routes) // Lets drink some Cognac and watch documentaries... server = ct.listen(config.port, config.host, function () { var host = server.address().address var port = server.address().port log.info("CognacTime v%s running at %s:%s", pkg.version, host, port) }) // Enable socket.io io = io(server) require('./socket')(io)
/* Created by 'myth' on June 30. 2015 CognacTime is licenced under the MIT licence. */ var fs = require('fs') , express = require('express') , expresshbs = require('express-handlebars') , io = require('socket.io') , log = require('./logging') , pkg = require('../package.json') , config = require('../config.json') , routes = require('../routes/core') // Initialize the express app ct = express() // Set logging middleware ct.use(require('morgan')('combined', {'stream': log.stream})) // Set static ct.use('/static', express.static('public')) // Set view engine ct.engine('hbs', expresshbs({ defaultLayout: 'main', extname: '.hbs' })) ct.set('views', './views') ct.set('view engine', 'hbs') // Set core routes ct.use('/', routes) // Lets drink some Cognac and watch documentaries... server = ct.listen(config.port, config.host, function () { var host = server.address().address var port = server.address().port log.info("CognacTime v%s running at %s:%s", pkg.version, host, port) }) // Enable socket.io io = io(server) require('./socket')(io)
Fix issues with the deprecated `chrome.app`
var formatLocale = require('./utils').formatLocale function getLocale(locale) { if (locale) return locale if (global.Intl && typeof global.Intl.DateTimeFormat === 'function') { return global.Intl.DateTimeFormat().resolvedOptions && global.Intl.DateTimeFormat().resolvedOptions().locale } if (global.chrome && global.chrome.app && typeof global.chrome.app.getDetails === 'function') { locale = global.chrome.app.getDetails() if (locale) { return locale.current_locale } } locale = (global.clientInformation || global.navigator || Object.create(null)).language || (global.navigator && (global.navigator.userLanguage || (global.navigator.languages && global.navigator.languages[0]) || (global.navigator.userAgent && global.navigator.userAgent.match(/;.(\w+\-\w+)/i)[1]))) if (!locale && ['LANG', 'LANGUAGE'].some(Object.hasOwnProperty, process.env)) { return (process.env.LANG || process.env.LANGUAGE || String()).replace(/[.:].*/, '') .replace('_', '-') } return locale } var locale2 = function(locale) { return formatLocale(getLocale(locale)) } exports.locale2 = locale2
var formatLocale = require('./utils').formatLocale function getLocale(locale) { if (locale) return locale if (global.Intl && typeof global.Intl.DateTimeFormat === 'function') { return global.Intl.DateTimeFormat().resolvedOptions && global.Intl.DateTimeFormat().resolvedOptions().locale } if (global.chrome && global.chrome.app && typeof global.chrome.app.getDetails === 'function') { return global.chrome.app.getDetails().current_locale } locale = (global.clientInformation || global.navigator || Object.create(null)).language || (global.navigator && (global.navigator.userLanguage || (global.navigator.languages && global.navigator.languages[0]) || (global.navigator.userAgent && global.navigator.userAgent.match(/;.(\w+\-\w+)/i)[1]))) if (!locale && ['LANG', 'LANGUAGE'].some(Object.hasOwnProperty, process.env)) { return (process.env.LANG || process.env.LANGUAGE || String()).replace(/[.:].*/, '') .replace('_', '-') } return locale } var locale2 = function(locale) { return formatLocale(getLocale(locale)) } exports.locale2 = locale2
Remove the require of auth in onboarding routes.
function getRoute(path, subComponentName) { return { path: path, subComponentName: subComponentName, getComponents(location, cb) { // require.ensure([], (require) => { cb(null, require('../../components/views/OnboardingView')) // }) }, } } export default { path: 'onboarding', getChildRoutes(location, cb) { // require.ensure([], () => { cb(null, [ getRoute('communities', 'CommunityPicker'), getRoute('awesome-people', 'PeoplePicker'), getRoute('profile-header', 'CoverPicker'), getRoute('profile-avatar', 'AvatarPicker'), getRoute('profile-bio', 'InfoPicker'), ]) // }) }, }
function getRoute(path, subComponentName) { return { path: path, subComponentName: subComponentName, onEnter() { require('../../networking/auth') }, getComponents(location, cb) { // require.ensure([], (require) => { cb(null, require('../../components/views/OnboardingView')) // }) }, } } export default { path: 'onboarding', getChildRoutes(location, cb) { // require.ensure([], () => { cb(null, [ getRoute('communities', 'CommunityPicker'), getRoute('awesome-people', 'PeoplePicker'), getRoute('profile-header', 'CoverPicker'), getRoute('profile-avatar', 'AvatarPicker'), getRoute('profile-bio', 'InfoPicker'), ]) // }) }, }
Tweak Engine effect and coloration.
import THREE from 'three.js'; const geometry = new THREE.CylinderGeometry( 0, 0.04, 0.25, 5 ); geometry.rotateX( Math.PI / 2 ); geometry.computeFaceNormals(); geometry.computeVertexNormals(); const material = new THREE.MeshLambertMaterial({ blending: THREE.AdditiveBlending, color: '#fff', emissive: '#f43', transparent: true, opacity: 0.4 }) export class Flame extends THREE.Mesh { constructor() { super( geometry, material ); } } export default class Engine extends THREE.Group { constructor( source, count = 3 ) { super(); this.source = source; let i = count; while( i-- ) { this.add( new Flame() ); } } update() { this.children.forEach( flame => { flame.position.set( THREE.Math.randFloatSpread( 0.005 ), THREE.Math.randFloatSpread( 0.005 ), THREE.Math.randFloatSpread( 0.03 ) ); flame.rotation.z = 2 * Math.PI * Math.random(); flame.scale.setLength( THREE.Math.randFloat( 0.5, 1 ) ); }) } }
import THREE from 'three.js'; const geometry = new THREE.CylinderGeometry( 0, 0.05, 0.3, 3 ); geometry.rotateX( Math.PI / 2 ); geometry.computeFaceNormals(); geometry.computeVertexNormals(); const material = new THREE.MeshBasicMaterial({ blending: THREE.AdditiveBlending, color: '#aaf', transparent: true, opacity: 0.4 }) export class Flame extends THREE.Mesh { constructor() { super( geometry, material ); this.scale.setLength( THREE.Math.randFloat( 0.5, 1 ) ); this.rotation.z = 2 * Math.PI * Math.random(); } } export default class Engine extends THREE.Group { constructor( source, count = 12 ) { super(); this.source = source; let i = count; while( i-- ) { this.add( new Flame() ); } } update() { this.children.forEach( flame => { flame.position.set( THREE.Math.randFloatSpread( 0.03 ), THREE.Math.randFloatSpread( 0.03 ), THREE.Math.randFloatSpread( 0.03 ) ); }) } }
Add a helper function to grab network names
# Taken from txircd: # https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9 def _enum(**enums): return type('Enum', (), enums) ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3) ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3) def isNumber(s): try: float(s) return True except ValueError: return False def parseUserPrefix(prefix): if "!" in prefix: nick = prefix[:prefix.find("!")] ident = prefix[prefix.find("!") + 1:prefix.find("@")] host = prefix[prefix.find("@") + 1:] return nick, ident, host # Not all "users" have idents and hostnames nick = prefix return nick, None, None def networkName(bot, server): return bot.servers[server].supportHelper.network
# Taken from txircd: # https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9 def _enum(**enums): return type('Enum', (), enums) ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3) ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3) def isNumber(s): try: float(s) return True except ValueError: return False def parseUserPrefix(prefix): if "!" in prefix: nick = prefix[:prefix.find("!")] ident = prefix[prefix.find("!") + 1:prefix.find("@")] host = prefix[prefix.find("@") + 1:] return nick, ident, host # Not all "users" have idents and hostnames nick = prefix return nick, None, None
Use continue in task loop
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml from Queue import Queue from threading import Thread from time import sleep load_dotenv(find_dotenv()) directions = ['forward', 'backward'] task_q = Queue() def send_rasp(task_q): while True: sleep(2) if task_q.empty(): continue message = task_q.get() print(message) rasp_signal = Thread(target=send_rasp, args=(task_q, )) rasp_signal.setDaemon(True) rasp_signal.start() app = Flask(__name__) @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): if message.lower() in directions: task_q.put(message.lower()) return 'Message sent' try: degree = float(message) except ValueError as e: return 'Invalid command' task_q.put(str(degree)) return 'Message sent' if __name__ == '__main__': app.run(debug=True)
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml from Queue import Queue from threading import Thread from time import sleep load_dotenv(find_dotenv()) directions = ['forward', 'backward'] task_q = Queue() def send_rasp(task_q): while True: sleep(2) if not task_q.empty(): message = task_q.get() print(message) rasp_signal = Thread(target=send_rasp, args=(task_q, )) rasp_signal.setDaemon(True) rasp_signal.start() app = Flask(__name__) @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): if message.lower() in directions: task_q.put(message.lower()) return 'Message sent' try: degree = float(message) except ValueError as e: return 'Invalid command' task_q.put(str(degree)) return 'Message sent' if __name__ == '__main__': app.run(debug=True)
Allow one or multiple texts to reground
"""This is a Python-based web server that can be run to read with Eidos. To run the server, do python -m indra.sources.eidos.server and then submit POST requests to the `localhost:5000/process_text` endpoint with JSON content as `{'text': 'text to read'}`. The response will be the Eidos JSON-LD output. """ import json import requests from flask import Flask, request from indra.sources.eidos.reader import EidosReader from indra.preassembler.make_wm_ontologies import wm_ont_url wm_yml = requests.get(wm_ont_url).text app = Flask(__name__) @app.route('/process_text', methods=['POST']) def process_text(): text = request.json.get('text') if not text: return {} res = er.process_text(text, 'json_ld') return json.dumps(res) @app.route('/reground_text', methods=['POST']) def reground_text(): text = request.json.get('text') if not text: return [] if isinstance(text, str): res = er.reground_texts([text], wm_yml) elif isinstance(text, list): res = er.reground_texts(text, wm_yml) return json.dumps(res) if __name__ == '__main__': er = EidosReader() er.process_text('hello', 'json_ld') app.run(host='0.0.0.0', port=6666)
"""This is a Python-based web server that can be run to read with Eidos. To run the server, do python -m indra.sources.eidos.server and then submit POST requests to the `localhost:5000/process_text` endpoint with JSON content as `{'text': 'text to read'}`. The response will be the Eidos JSON-LD output. """ import json import requests from flask import Flask, request from indra.sources.eidos.reader import EidosReader from indra.preassembler.make_wm_ontologies import wm_ont_url wm_yml = requests.get(wm_ont_url).text app = Flask(__name__) @app.route('/process_text', methods=['POST']) def process_text(): text = request.json.get('text') if not text: return {} res = er.process_text(text, 'json_ld') return json.dumps(res) @app.route('/reground_text', methods=['POST']) def reground_text(): text = request.json.get('text') if not text: return [] res = er.reground_texts([text], wm_yml) return json.dumps(res) if __name__ == '__main__': er = EidosReader() er.process_text('hello', 'json_ld') app.run(host='0.0.0.0', port=6666)
Add placeholder for removing customer from saltedge
from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db.models.signals import post_save from saltedge.factory import get_saltedge_app class User(AbstractUser): pass class ProfileManager(models.Manager): def create_in_saltedge(self, profile): app = get_saltedge_app() url = "https://www.saltedge.com/api/v5/customers" payload = json.dumps({"data": {"identifier": profile.user.id}}) response = app.post(url, payload) data = response.json() profile.external_id = data["data"]["id"] profile.save() def remove_from_saltedge(self, profile): pass class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) external_id = models.BigIntegerField(blank=True, null=True) objects = ProfileManager() def __str__(self): return str(self.user) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_user_profile, sender=settings.AUTH_USER_MODEL)
from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db.models.signals import post_save from saltedge.factory import get_saltedge_app class User(AbstractUser): pass class ProfileManager(models.Manager): def create_in_saltedge(self, profile): app = get_saltedge_app() url = "https://www.saltedge.com/api/v5/customers" payload = json.dumps({"data": {"identifier": profile.user.id}}) response = app.post(url, payload) data = response.json() profile.external_id = data["data"]["id"] profile.save() class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) external_id = models.BigIntegerField(blank=True, null=True) objects = ProfileManager() def __str__(self): return str(self.user) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_user_profile, sender=settings.AUTH_USER_MODEL)
Use database number from redis url if available.
import json import urlparse from flask import Flask, make_response from flask.ext.restful import Api from flask_peewee.db import Database import redis from redash import settings, utils __version__ = '0.3.2' app = Flask(__name__, template_folder=settings.STATIC_ASSETS_PATH, static_folder=settings.STATIC_ASSETS_PATH, static_path='/static') api = Api(app) # configure our database settings.DATABASE_CONFIG.update({'threadlocals': True}) app.config['DATABASE'] = settings.DATABASE_CONFIG db = Database(app) from redash.authentication import setup_authentication auth = setup_authentication(app) @api.representation('application/json') def json_representation(data, code, headers=None): resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code) resp.headers.extend(headers or {}) return resp redis_url = urlparse.urlparse(settings.REDIS_URL) if redis_url.path: redis_db = redis_url.path[1] else: redis_db = 0 redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_url.password) from redash import data data_manager = data.Manager(redis_connection, db) from redash import controllers
import json import urlparse from flask import Flask, make_response from flask.ext.restful import Api from flask_peewee.db import Database import redis from redash import settings, utils __version__ = '0.3.2' app = Flask(__name__, template_folder=settings.STATIC_ASSETS_PATH, static_folder=settings.STATIC_ASSETS_PATH, static_path='/static') api = Api(app) # configure our database settings.DATABASE_CONFIG.update({'threadlocals': True}) app.config['DATABASE'] = settings.DATABASE_CONFIG db = Database(app) from redash.authentication import setup_authentication auth = setup_authentication(app) @api.representation('application/json') def json_representation(data, code, headers=None): resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code) resp.headers.extend(headers or {}) return resp redis_url = urlparse.urlparse(settings.REDIS_URL) redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=0, password=redis_url.password) from redash import data data_manager = data.Manager(redis_connection, db) from redash import controllers
Change spacing in js file
$(document).ready(function() { // This is called after the document has loaded in its entirety // This guarantees that any elements we bind to will exist on the page // when we try to bind to them // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready() $('.comment-form').on('submit', function(event){ event.preventDefault(); var url = $(this).attr('action'); var data = $(this).serialize(); var request = $.ajax({ url: url, method: 'POST', data: data }); request.done(function(response){ console.log(response); $('.comments ul').append( $('<li>' + response.content + '</li>') ) }); }); });
$(document).ready(function() { // This is called after the document has loaded in its entirety // This guarantees that any elements we bind to will exist on the page // when we try to bind to them // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready() $('.comment-form').on('submit', function(event){ event.preventDefault(); var url = $(this).attr('action'); var data = $(this).serialize(); var request = $.ajax({ url: url, method: 'POST', data: data }); request.done(function(response){ console.log(response); $('.comments ul').append( $('<li>' + response.content + '</li>') ) }); }); });
Remove list of conflicting module. Both modules can be installed and will work in parallele. Thought the workflow logic is different.
# -*- coding: utf-8 -*- ############################################################################## # # Author: Vincent Renaville (Camptocamp) # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Bank Statement Multi currency Extension', 'summary': 'Add an improved view for move line import in bank statement', 'version': '1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'maintainter': 'Camptocamp', 'category': 'Accounting', 'depends': ['account'], 'website': 'http://www.camptocamp.com', 'data': ['view/account_statement_from_invoice_view.xml', 'view/bank_statement_view.xml', ], 'tests': [], 'installable': True, 'license': 'AGPL-3', }
# -*- coding: utf-8 -*- ############################################################################## # # Author: Vincent Renaville (Camptocamp) # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Bank Statement Multi currency Extension', 'summary': 'Add an improved view for move line import in bank statement', 'version': '1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'maintainter': 'Camptocamp', 'category': 'Accounting', 'depends': ['account'], 'website': 'http://www.camptocamp.com', 'data': ['view/account_statement_from_invoice_view.xml', 'view/bank_statement_view.xml', ], 'tests': [], 'installable': True, 'license': 'AGPL-3', 'conflicts': [ 'account_banking_payment_export', ], }
Handle nil value in JSON.Scan
/* Copyright 2016 Paolo Galeone. All right 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. */ // Thanks to: https://coussej.github.io/2016/02/16/Handling-JSONB-in-Go-Structs/ package igor import ( "database/sql/driver" "encoding/json" "errors" ) // JSON is the Go type used to handle JSON PostgreSQL type type JSON map[string]interface{} // Value implements driver.Valuer interface func (js JSON) Value() (driver.Value, error) { return json.Marshal(js) } // Scan implements sql.Scanner interface func (js *JSON) Scan(src interface{}) error { if src == nil { *js = make(JSON) return nil } source, ok := src.([]byte) if !ok { return errors.New("Type assertion .([]byte) failed.") } if err := json.Unmarshal(source, js); err != nil { return err } return nil }
/* Copyright 2016 Paolo Galeone. All right 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. */ // Thanks to: https://coussej.github.io/2016/02/16/Handling-JSONB-in-Go-Structs/ package igor import ( "database/sql/driver" "encoding/json" "errors" ) // JSON is the Go type used to handle JSON PostgreSQL type type JSON map[string]interface{} // Value implements driver.Valuer interface func (js JSON) Value() (driver.Value, error) { return json.Marshal(js) } // Scan implements sql.Scanner interface func (js *JSON) Scan(src interface{}) error { source, ok := src.([]byte) if !ok { return errors.New("Type assertion .([]byte) failed.") } if err := json.Unmarshal(source, js); err != nil { return err } return nil }
Split requires into own string
from setuptools import setup setup( name='pytest-ui', description='Text User Interface for running python tests', version='0.1', license='MIT', platforms=['linux', 'osx', 'win32'], packages=['pytui'], url='https://github.com/martinsmid/pytest-ui', author_email='martin.smid@gmail.com', author='Martin Smid', entry_points={ 'pytest11': [ 'pytui = pytui.runner', ] }, install_requires=['urwid>=1.3.1', 'pytest>=3.0.5'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Testing', 'Topic :: Utilities', 'Programming Language :: Python', ], )
from setuptools import setup setup( name='pytest-ui', description='Text User Interface for running python tests', version='0.1', license='MIT', platforms=['linux', 'osx', 'win32'], packages=['pytui'], url='https://github.com/martinsmid/pytest-ui', author_email='martin.smid@gmail.com', author='Martin Smid', entry_points={ 'pytest11': [ 'pytui = pytui.runner', ] }, install_requires=['urwid>=1.3.1,pytest>=3.0.5'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Testing', 'Topic :: Utilities', 'Programming Language :: Python', ], )
Add player color to the welcome
const $ = require('jquery'); const board = require('./board'); const Piece = require('./piece'); function Game(players, board) { this.players = players; this.turn = 0; this.winner = null; this.over = false; this.board = board; } Game.prototype.start = function(){ welcomePlayers(this.players); placeFirstFourPieces(this.board); }; function placeFirstFourPieces(board) { var square0 = board.squares[27]; var square1 = board.squares[28]; var square2 = board.squares[35]; var square3 = board.squares[36]; var squares = [square0, square1, ,square2, square3]; squares.forEach(function(square,index){ if (index % 2 == 0){ square.piece = new Piece('white', square, square.context); square.createPiece(); } else { square.piece = new Piece('black', square, square.context); square.createPiece(); } }); } function welcomePlayers(players) { var first = players[0]; var second = players[1]; $('#title').prepend(`<h1>Welcome ${first.name}(${first.color}) and ${second.name}(${second.color})!</h1>`) } module.exports = Game;
const $ = require('jquery'); const board = require('./board'); const Piece = require('./piece'); function Game(players, board) { this.players = players; this.turn = 0; this.winner = null; this.over = false; this.board = board; } Game.prototype.start = function(){ welcomePlayers(this.players); placeFirstFourPieces(this.board); }; function placeFirstFourPieces(board) { var square0 = board.squares[27]; var square1 = board.squares[28]; var square2 = board.squares[35]; var square3 = board.squares[36]; var squares = [square0, square1, ,square2, square3]; squares.forEach(function(square,index){ if (index % 2 == 0){ square.piece = new Piece('white', square, square.context); square.createPiece(); } else { square.piece = new Piece('black', square, square.context); square.createPiece(); } }); } function welcomePlayers(players) { $('#title').prepend(`<h1>Welcome ${players[0].name} and ${players[1].name}!</h1>`) } module.exports = Game;
Rename schema fixture to free up parameter name
from pathlib import Path import pytest from sqlalchemy import create_engine from testcontainers import PostgresContainer as _PostgresContainer tests_dir = Path(__file__).parents[0].resolve() test_schema_file = Path(tests_dir, 'data', 'test-schema.sql') class PostgresContainer(_PostgresContainer): POSTGRES_USER = 'alice' POSTGRES_DB = 'db1' @pytest.fixture(scope='session') def postgres_url(): postgres_container = PostgresContainer("postgres:latest") with postgres_container as postgres: yield postgres.get_connection_url() @pytest.fixture(scope='session') def engine(postgres_url): return create_engine(postgres_url) @pytest.fixture(scope='session') def pg_schema(engine): with test_schema_file.open() as fp: engine.execute(fp.read()) @pytest.fixture def connection(engine, pg_schema): with engine.connect() as conn: yield conn
from pathlib import Path import pytest from sqlalchemy import create_engine from testcontainers import PostgresContainer as _PostgresContainer tests_dir = Path(__file__).parents[0].resolve() test_schema_file = Path(tests_dir, 'data', 'test-schema.sql') class PostgresContainer(_PostgresContainer): POSTGRES_USER = 'alice' POSTGRES_DB = 'db1' @pytest.fixture(scope='session') def postgres_url(): postgres_container = PostgresContainer("postgres:latest") with postgres_container as postgres: yield postgres.get_connection_url() @pytest.fixture(scope='session') def engine(postgres_url): return create_engine(postgres_url) @pytest.fixture(scope='session') def schema(engine): with test_schema_file.open() as fp: engine.execute(fp.read()) @pytest.fixture def connection(engine, schema): with engine.connect() as conn: yield conn
Change the str representation of AppHookConfig by using the related CMSApp name instead of the type
# -*- coding: utf-8 -*- from app_data import AppDataField from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class AppHookConfig(models.Model): """ This is the generic (abstract) model that holds the configurations for each AppHookConfig concrete model """ type = models.CharField(max_length=100) namespace = models.CharField(max_length=100) app_data = AppDataField() cmsapp = None class Meta: verbose_name = _(u'app-hook config') verbose_name_plural = _(u'app-hook configs') unique_together = ('type', 'namespace') abstract = True def save(self, *args, **kwargs): self.type = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__) super(AppHookConfig, self).save(*args, **kwargs) def __str__(self): if self.cmsapp: return _(u'%s / %s') % (self.cmsapp.name, self.namespace) else: return _(u'%s / %s') % (self.type, self.namespace)
# -*- coding: utf-8 -*- from app_data import AppDataField from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class AppHookConfig(models.Model): """ This is the generic (abstract) model that holds the configurations for each AppHookConfig concrete model """ type = models.CharField(max_length=100) namespace = models.CharField(max_length=100) app_data = AppDataField() class Meta: verbose_name = _(u'app-hook config') verbose_name_plural = _(u'app-hook configs') unique_together = ('type', 'namespace') abstract = True def save(self, *args, **kwargs): self.type = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__) super(AppHookConfig, self).save(*args, **kwargs) def __str__(self): return _(u'%s / %s') % (self.type, self.namespace)
Remove settings from the routes for the moment
import App from '../containers/App' function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const routes = [ createRedirect('/', '/explore'), { path: '/', component: App, // order matters, so less specific routes should go at the bottom childRoutes: [ require('./post_detail'), ...require('./authentication'), ...require('./discover'), ...require('./streams'), require('./notifications'), ...require('./invitations'), createRedirect('onboarding', '/onboarding/communities'), require('./onboarding'), ...require('./search'), require('./user_detail'), ], }, ] export default routes
import App from '../containers/App' function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const routes = [ createRedirect('/', '/explore'), { path: '/', component: App, // order matters, so less specific routes should go at the bottom childRoutes: [ require('./post_detail'), ...require('./authentication'), ...require('./discover'), ...require('./streams'), require('./notifications'), ...require('./settings'), ...require('./invitations'), createRedirect('onboarding', '/onboarding/communities'), require('./onboarding'), ...require('./search'), require('./user_detail'), ], }, ] export default routes
Fix lifecycle hooks in StoreWatchMixin
module.exports = function(React) { return function() { var storeNames = Array.prototype.slice.call(arguments); return { componentWillMount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).on("change", this._setStateFromFlux) }, this); }, componentWillUnmount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).off("change", this._setStateFromFlux) }, this); }, _setStateFromFlux: function() { this.setState(this.getStateFromFlux()); }, getInitialState: function() { return this.getStateFromFlux(); } } }; };
module.exports = function(React) { return function() { var storeNames = Array.prototype.slice.call(arguments); return { componentDidMount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).on("change", this._setStateFromFlux) }, this); }, componentDidUnmount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).off("change", this._setStateFromFlux) }, this); }, _setStateFromFlux: function() { this.setState(this.getStateFromFlux()); }, getInitialState: function() { return this.getStateFromFlux(); } } }; };
Add v.NewPipeline and Fix if...else Signed-off-by: Koichi Shiraishi <13fbd79c3d390e5d6585a21e11ff5ec1970cff0c@zchee.io>
// Copyright 2016 Koichi Shiraishi. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package nvim import ( "encoding/binary" "github.com/garyburd/neovim-go/vim" ) var ( b vim.Buffer w vim.Window ) func ByteOffset(v *vim.Vim) (int, error) { p := v.NewPipeline() p.CurrentBuffer(&b) p.CurrentWindow(&w) if err := p.Wait(); err != nil { return 0, err } cursor, err := v.WindowCursor(w) if err != nil { return 0, err } byteBuf, err := v.BufferLineSlice(b, 0, -1, true, true) if err != nil { return 0, err } offset := 0 if cursor[0] == 1 { return (1 + (cursor[1] - 1)), nil } line := 1 for _, buf := range byteBuf { if line == cursor[0] { offset++ break } offset += (binary.Size(buf) + 1) line++ } return (offset + (cursor[1] - 1)), nil }
// Copyright 2016 Koichi Shiraishi. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package nvim import ( "encoding/binary" "github.com/garyburd/neovim-go/vim" ) func ByteOffset(v *vim.Vim) (int, error) { b, err := v.CurrentBuffer() if err != nil { return 0, err } w, err := v.CurrentWindow() if err != nil { return 0, err } cursor, err := v.WindowCursor(w) if err != nil { return 0, err } byteBuf, err := v.BufferLineSlice(b, 0, -1, true, true) if err != nil { return 0, err } offset := 0 cursorline := 1 for _, bytes := range byteBuf { if cursor[0] == 1 { offset = 1 break } else if cursorline == cursor[0] { offset++ break } offset += (binary.Size(bytes) + 1) cursorline++ } return (offset + (cursor[1] - 1)), nil }
Use imports from django_xworkflows instead of imports from xworkflows in tests Signed-off-by: Raphaël Barrois <8eb3b37a023209373fcd61a2fdc08256a14fb19c@polyconseil.fr>
from django.db import models as djmodels from django_xworkflows import models class MyWorkflow(models.Workflow): states = ('foo', 'bar', 'baz') transitions = ( ('foobar', 'foo', 'bar'), ('gobaz', ('foo', 'bar'), 'baz'), ('bazbar', 'baz', 'bar'), ) initial_state = 'foo' class MyAltWorkflow(models.Workflow): states = ( ('a', 'StateA'), ('b', 'StateB'), ('c', 'StateC'), ) transitions = ( ('tob', ('a', 'c'), 'b'), ('toa', ('b', 'c'), 'a'), ('toc', ('a', 'b'), 'c'), ) initial_state = 'a' class MyWorkflowEnabled(models.WorkflowEnabled, djmodels.Model): state = MyWorkflow def gobaz(self, foo): return foo * 2 class WithTwoWorkflows(models.WorkflowEnabled, djmodels.Model): state1 = MyWorkflow() state2 = MyAltWorkflow()
from django.db import models as djmodels import xworkflows from django_xworkflows import models class MyWorkflow(xworkflows.Workflow): states = ('foo', 'bar', 'baz') transitions = ( ('foobar', 'foo', 'bar'), ('gobaz', ('foo', 'bar'), 'baz'), ('bazbar', 'baz', 'bar'), ) initial_state = 'foo' class MyAltWorkflow(xworkflows.Workflow): states = ( ('a', 'StateA'), ('b', 'StateB'), ('c', 'StateC'), ) transitions = ( ('tob', ('a', 'c'), 'b'), ('toa', ('b', 'c'), 'a'), ('toc', ('a', 'b'), 'c'), ) initial_state = 'a' class MyWorkflowEnabled(models.WorkflowEnabled, djmodels.Model): state = MyWorkflow def gobaz(self, foo): return foo * 2 class WithTwoWorkflows(models.WorkflowEnabled, djmodels.Model): state1 = MyWorkflow state2 = MyAltWorkflow
Add shameless pleading for funds. We're college students. Our pride is not worth as much as money.
<!DOCTYPE html> <html> <head> <?php include("include/common.html"); ?> <meta charset="utf-8"> <title>About</title> </head> <body> <?php include("include/header.html"); ?> <h1 id="title">About <span class="gamr">GAMR</span></h1> <br> <p class="info"> &nbsp;&nbsp;<span class="gamr">GAMR</span> was written as a team project for the WildHacks 2015 hackathon. It was conceptualized as a way for people who wish to find a party with which to play a multi-player game to find one another and play together. As team member <span class="teammate-name">Murphy Angelo</span> said, <p class="info"> <blockquote>I think that it's disappointing how there are a lot of cool games that people don't really play online, and that you can't really find anyone to play with locally. I wish there was an easier way to find people to play with.</blockquote> <p class="info"> Fellow team members <span class="teammate-name">Elana Stettin</span> and <span class="teammate-name">Ryan Hodin</span> agreed with this sentiment, and thus <span class="gamr">GAMR</span> was born. </p> <br> <p class="info"> <span class="gamr">GAMR</span> continues to this day to be funded entirely by donations. If you like it, please consider clicking the button below to donate. <?php include("include/footer.html"); ?> </body> </html>
<!DOCTYPE html> <html> <head> <?php include("include/common.html"); ?> <meta charset="utf-8"> <title>About</title> </head> <body> <?php include("include/header.html"); ?> <h1 id="title">About <span class="gamr">GAMR</span></h1> <br> <p class="info"> &nbsp;&nbsp;<span class="gamr">GAMR</span> was written as a team project for the WildHacks 2015 hackathon. It was conceptualized as a way for people who wish to find a party with which to play a multi-player game to find one another and play together. As team member <span class="teammate-name">Murphy Angelo</span> said, <p class="info"> <blockquote>I think that it's disappointing how there are a lot of cool games that people don't really play online, and that you can't really find anyone to play with locally. I wish there was an easier way to find people to play with.</blockquote> <p class="info"> Fellow team members <span class="teammate-name">Elana Stettin</span> and <span class="teammate-name">Ryan Hodin</span> agreed with this sentiment, and thus <span class="gamr">GAMR</span> was born. <?php include("include/footer.html"); ?> </body> </html>
Add pymongo as a dependency
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pymongo', 'pyramid', 'pyramid_debugtoolbar', 'waitress', ] setup(name='yith-library-server', version='0.0', description='yith-library-server', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pylons", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="yithlibraryserver", entry_points = """\ [paste.app_factory] main = yithlibraryserver:main """, )
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'pyramid_debugtoolbar', 'waitress', ] setup(name='yith-library-server', version='0.0', description='yith-library-server', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pylons", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, tests_require=requires, test_suite="yithlibraryserver", entry_points = """\ [paste.app_factory] main = yithlibraryserver:main """, )
Update to JMS Serializer to allow manual override
<?php namespace Doctrine\Search\Serializer; use Doctrine\Search\SerializerInterface; use JMS\Serializer\SerializerBuilder; use JMS\Serializer\SerializationContext; use JMS\Serializer\Naming\SerializedNameAnnotationStrategy; use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy; class JMSSerializer implements SerializerInterface { protected $serializer; protected $context; public function __construct(SerializationContext $context = null) { $this->context = $context; $this->serializer = SerializerBuilder::create() ->setPropertyNamingStrategy(new SerializedNameAnnotationStrategy(new IdenticalPropertyNamingStrategy())) ->addDefaultHandlers() ->build(); } public function serialize($object) { $context = $this->context ? clone $this->context : null; return json_decode($this->serializer->serialize($object, 'json', $context), true); } }
<?php namespace Doctrine\Search\Serializer; use Doctrine\Search\SerializerInterface; use JMS\Serializer\SerializerBuilder; use JMS\Serializer\SerializationContext; use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy; class JMSSerializer implements SerializerInterface { protected $serializer; protected $context; public function __construct(SerializationContext $context = null) { $this->context = $context; $this->serializer = SerializerBuilder::create() ->setPropertyNamingStrategy(new IdenticalPropertyNamingStrategy()) ->addDefaultHandlers() ->build(); } public function serialize($object) { $context = $this->context ? clone $this->context : null; return json_decode($this->serializer->serialize($object, 'json', $context), true); } }
Make build process output umd bundle
var path = require('path'); var webpack = require('webpack'); var minify = new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false }, output: { semicolons: false, indent_level: 0 } }); var loaders = [{ "test": /\.imba$/, "loader": path.join(__dirname, "./loader") }]; module.exports = [{ module: {loaders: loaders}, resolve: {extensions: ['*', '.imba', '.js']}, entry: "./src/imba/index.imba", output: { filename: "./imba.js", library: { root: "Imba", amd: "imba", commonjs: "imba" }, libraryTarget: "umd" }, node: {fs: false, process: false, global: false} // plugins: [minify] },{ module: {loaders: loaders}, resolve: {extensions: ['*', '.imba', '.js']}, entry: "./test/index.imba", output: { filename: "./test/client.js"}, node: {fs: false, process: false, global: false} }]
var path = require('path'); var webpack = require('webpack'); var minify = new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false }, output: { semicolons: false, indent_level: 0 } }); var loaders = [{ "test": /\.imba$/, "loader": path.join(__dirname, "./loader") }]; module.exports = [{ module: {loaders: loaders}, resolve: {extensions: ['*', '.imba', '.js']}, entry: "./src/imba/index.imba", output: { filename: "./imba.js"}, node: {fs: false, process: false, global: false}, plugins: [minify] },{ module: {loaders: loaders}, resolve: {extensions: ['*', '.imba', '.js']}, entry: "./test/index.imba", output: { filename: "./test/client.js"}, node: {fs: false, process: false, global: false} }]
ci: Exclude a supplementary directory from set of directories where packages can be located
""" Just a regular `setup.py` file. @author: Nikolay Lysenko """ import os from setuptools import setup, find_packages current_dir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(current_dir, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='dsawl', version='0.1a', description='A set of tools for machine learning', long_description=long_description, url='https://github.com/Nikolay-Lysenko/dsawl', author='Nikolay Lysenko', author_email='nikolay-lysenco@yandex.ru', license='MIT', keywords='machine_learning feature_engineering categorical_features', packages=find_packages(exclude=['docs', 'tests', 'ci']), python_requires='>=3.5', install_requires=['numpy', 'pandas', 'scipy', 'scikit-learn', 'joblib'] )
""" Just a regular `setup.py` file. @author: Nikolay Lysenko """ import os from setuptools import setup, find_packages current_dir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(current_dir, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='dsawl', version='0.1a', description='A set of tools for machine learning', long_description=long_description, url='https://github.com/Nikolay-Lysenko/dsawl', author='Nikolay Lysenko', author_email='nikolay-lysenco@yandex.ru', license='MIT', keywords='machine_learning feature_engineering categorical_features', packages=find_packages(exclude=['docs', 'tests']), python_requires='>=3.5', install_requires=['numpy', 'pandas', 'scipy', 'scikit-learn', 'joblib'] )
Fix issue with Service Provider
<?php namespace KeyCDN; use Illuminate\Support\ServiceProvider; use KeyCDN\Facades\KeyCDNFacade; /** * Class KeyCDNServiceProvider * @package KeyCDN */ class KeyCDNServiceProvider extends ServiceProvider { /** * Register config files */ public function boot() { $this->publishes([ __DIR__.'/../config/keycdn.php' => config_path('keycdn.php'), ], 'keycdn'); } /** * Register Service */ public function register() { $this->mergeConfigFrom( __DIR__.'/../config/keycdn.php', 'keycdn' ); $this->app->bind(KeyCDN::class, function() { return KeyCDN::create(config('keycdn.key')); }); } /** * Get the services provided by the provider. * @return array */ public function provides() { return array('keycdn'); } }
<?php namespace KeyCDN; use Illuminate\Support\ServiceProvider; use KeyCDN\Facades\KeyCDN; use KeyCDN\Facades\KeyCDNFacade; /** * Class KeyCDNServiceProvider * @package KeyCDN */ class KeyCDNServiceProvider extends ServiceProvider { /** * Register config files */ public function boot() { $this->publishes([ __DIR__.'/../config/keycdn.php' => config_path('keycdn.php'), ], 'keycdn'); } /** * Register Service */ public function register() { $this->mergeConfigFrom( __DIR__.'/../config/keycdn.php', 'keycdn' ); $this->app->bind(KeyCDN::class, function() { return KeyCDN::create(config('keycdn.key')); }); } /** * Get the services provided by the provider. * @return array */ public function provides() { return array('keycdn'); } }
Disable Snom config Unit Testuntil we have a new sample of the new config version git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@7409 a612230a-c5fa-0310-af8b-88eea846685b
package org.sipfoundry.sipxconfig.phone.snom; import java.io.StringWriter; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.sipfoundry.sipxconfig.phone.Phone; import org.sipfoundry.sipxconfig.phone.PhoneTestDriver; public class SnomTest extends TestCase { private Phone m_phone; protected void setUp() { m_phone = new SnomPhone(SnomModel.MODEL_360); PhoneTestDriver.supplyTestData(m_phone); } // Disabled until new sample config is ready // public void testGenerateProfiles() throws Exception { // StringWriter profile = new StringWriter(); // m_phone.generateProfile(profile); // String expected = IOUtils.toString(this.getClass() // .getResourceAsStream("expected-360.cfg")); // assertEquals(expected, profile.toString()); // } public void testGetProfileName() { Phone phone = new SnomPhone(SnomModel.MODEL_360); phone.setWebDirectory("web"); // it can be called without serial number //assertEquals("web/snom360.htm", phone.getPhoneFilename()); phone.setSerialNumber("abc123"); assertEquals("web/ABC123.htm", phone.getPhoneFilename()); } }
package org.sipfoundry.sipxconfig.phone.snom; import java.io.StringWriter; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.sipfoundry.sipxconfig.phone.Phone; import org.sipfoundry.sipxconfig.phone.PhoneTestDriver; public class SnomTest extends TestCase { private Phone m_phone; protected void setUp() { m_phone = new SnomPhone(SnomModel.MODEL_360); PhoneTestDriver.supplyTestData(m_phone); } public void testGenerateProfiles() throws Exception { StringWriter profile = new StringWriter(); m_phone.generateProfile(profile); String expected = IOUtils.toString(this.getClass() .getResourceAsStream("expected-360.cfg")); assertEquals(expected, profile.toString()); } public void testGetProfileName() { Phone phone = new SnomPhone(SnomModel.MODEL_360); phone.setWebDirectory("web"); // it can be called without serial number assertEquals("web/snom360.htm", phone.getPhoneFilename()); phone.setSerialNumber("abc123"); assertEquals("web/snom360-ABC123.htm", phone.getPhoneFilename()); } }
Clean up log message in FanStatChannel
package channels type FanState struct { Speed *float64 `json:"speed,omitempty"` // the speed of the fan as a percentage of maximum Direction *string `json:"direction,omitempty"` // the direction of the fan: "forward" or "reverse" } type FanStatActuator interface { SetFanState(fanState *FanState) error } type FanStatChannel struct { baseChannel actuator FanStatActuator } func NewFanStatChannel(actuator FanStatActuator) *FanStatChannel { return &FanStatChannel{ baseChannel: baseChannel{protocol: "fanstat"}, actuator: actuator, } } func (c *FanStatChannel) Set(fanState *FanState) error { return c.actuator.SetFanState(fanState) } func (c *FanStatChannel) SendState(fanState *FanState) error { //log.Printf("SendState: %+v\n, %p", fanState, c.SendEvent) return c.SendEvent("state", fanState) }
package channels import ( "log" ) type FanState struct { Speed *float64 `json:"speed,omitempty"` // the speed of the fan as a percentage of maximum Direction *string `json:"direction,omitempty"` // the direction of the fan: "forward" or "reverse" } type FanStatActuator interface { SetFanState(fanState *FanState) error } type FanStatChannel struct { baseChannel actuator FanStatActuator } func NewFanStatChannel(actuator FanStatActuator) *FanStatChannel { return &FanStatChannel{ baseChannel: baseChannel{protocol: "fanstat"}, actuator: actuator, } } func (c *FanStatChannel) Set(fanState *FanState) error { return c.actuator.SetFanState(fanState) } func (c *FanStatChannel) SendState(fanState *FanState) error { log.Printf("SendState: %+v\n, %p", fanState, c.SendEvent) return c.SendEvent("state", fanState) }
Change window size to fit content
const electron = require('electron'); // Module to control application life. const app = electron.app; // Module to create native browser window. const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow() { // Create the browser window. mainWindow = new BrowserWindow({ width: 750, height: 600, icon: __dirname + '../images/logo/logo.png' }); // and load the index.html of the app. mainWindow.loadURL(`file://${__dirname}/../index.html`); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference window object mainWindow = null; }); } // Called when Electron has finished initialization. app.on('ready', createWindow); ipcMain.on('renderData', function(event, arg) { var dataWindow = new BrowserWindow({ width: 1000, height: 500 }); // Load options page dataWindow.loadURL(`file://${__dirname}/../data.html`); dataWindow.on('closed', function() { // Dereference window object dataWindow = null; }); });
const electron = require('electron'); // Module to control application life. const app = electron.app; // Module to create native browser window. const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow() { // Create the browser window. mainWindow = new BrowserWindow({ width: 870, height: 475, icon: __dirname + '../images/logo/logo.png' }); // and load the index.html of the app. mainWindow.loadURL(`file://${__dirname}/../index.html`); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference window object mainWindow = null; }); } // Called when Electron has finished initialization. app.on('ready', createWindow); ipcMain.on('renderData', function(event, arg) { var dataWindow = new BrowserWindow({ width: 1000, height: 500 }); // Load options page dataWindow.loadURL(`file://${__dirname}/../data.html`); dataWindow.on('closed', function() { // Dereference window object dataWindow = null; }); });
Use Auth mock for Client
<?php class BaseTest extends PHPUnit_Framework_TestCase { /** * @var PHPUnit_Framework_MockObject_MockObject */ protected $mockAuth; /** * @var PHPUnit_Framework_MockObject_MockObject */ protected $mockClient; public function setUp() { $this->mockAuth = $this->getMockBuilder("\BulkSmsCenter\Auth")->setConstructorArgs([ 'YOUR_USERNAME', 'YOUR_PASSWORD', ])->getMock(); $this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock(); } public function testConstructor() { $client = new \BulkSmsCenter\Client(); $this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage()); } public function testHttpClientMock() { $this->mockClient->expects($this->atLeastOnce())->method('setAuth'); $this->mockClient->expects($this->atLeastOnce())->method('setUserAgent'); $client = new \BulkSmsCenter\Client($this->mockAuth,$this->mockClient); } }
<?php class BaseTest extends PHPUnit_Framework_TestCase { /** * @var PHPUnit_Framework_MockObject_MockObject */ protected $mockAuth; /** * @var PHPUnit_Framework_MockObject_MockObject */ protected $mockClient; public function setUp() { $this->mockAuth = $this->getMockBuilder("\BulkSmsCenter\Auth")->setConstructorArgs([ 'YOUR_USERNAME', 'YOUR_PASSWORD', ])->getMock(); $this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock(); } public function testConstructor() { $client = new \BulkSmsCenter\Client(); $this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage()); } public function testHttpClientMock() { $this->mockClient->expects($this->atLeastOnce())->method('setAuth'); $this->mockClient->expects($this->atLeastOnce())->method('setUserAgent'); $client = new \BulkSmsCenter\Client($this->auth,$this->mockClient); } }
Revert "Make nodeModulesBabelLoader compatible with Babel 6" This reverts commit 1bcb78fa
import { includePaths, excludePaths } from '../config/utils'; export default options => ({ test: /\.(mjs|jsx?)$/, use: [ { loader: 'babel-loader', options, }, ], include: includePaths, exclude: excludePaths, }); export const nodeModulesBabelLoader = { test: /\.js$/, include: /\/node_modules\/safe-eval\//, use: [ { loader: 'babel-loader', options: { cacheDirectory: true, babelrc: false, presets: [ [ require.resolve('@babel/preset-env'), { useBuiltIns: 'usage', modules: 'commonjs', }, ], ], }, }, ], };
import { includePaths, excludePaths } from '../config/utils'; export default options => ({ test: /\.(mjs|jsx?)$/, use: [ { loader: 'babel-loader', options, }, ], include: includePaths, exclude: excludePaths, }); export const nodeModulesBabelLoader = { test: /\.js$/, include: /\/node_modules\/safe-eval\//, use: [ { loader: 'babel-loader', options: { cacheDirectory: true, babelrc: false, presets: [ [ 'env', { modules: 'commonjs', }, ], ], }, }, ], };
Fix an error rendering emojis Some leftovers from the default props updates [Fixes: #137486597](https://www.pivotaltracker.com/story/show/137486597)
import React, { PropTypes } from 'react' import classNames from 'classnames' const Emoji = (props) => { const { alt, className, name, size, src, title, width, height } = props const tip = name.replace(/_|-/, ' ') return ( <img {...props} alt={alt || tip} className={classNames(className, 'Emoji')} src={src || `${ENV.AUTH_DOMAIN}/images/emoji/${name}.png`} title={title || tip} width={width || size} height={height || size} size={null} name={null} /> ) } Emoji.propTypes = { alt: PropTypes.string, className: PropTypes.string, name: PropTypes.string, size: PropTypes.number, src: PropTypes.string, title: PropTypes.string, width: PropTypes.number, height: PropTypes.number, } Emoji.defaultProps = { alt: 'ello', className: null, name: 'ello', size: 20, src: null, title: 'ello', width: 20, height: 20, } export default Emoji
import React, { PropTypes } from 'react' import classNames from 'classnames' const Emoji = (props) => { const { alt, className, name = 'ello', size, src, title, width, height } = props const tip = name.replace(/_|-/, ' ') return ( <img {...props} alt={alt || tip} className={classNames(className, 'Emoji')} src={src || `${ENV.AUTH_DOMAIN}/images/emoji/${name}.png`} title={title || tip} width={width || size} height={height || size} size={null} name={null} /> ) } Emoji.propTypes = { alt: PropTypes.string, className: PropTypes.string, name: PropTypes.string, size: PropTypes.number, src: PropTypes.string, title: PropTypes.string, width: PropTypes.number, height: PropTypes.number, } Emoji.defaultProps = { alt: null, className: null, name: null, size: 20, src: null, title: null, width: null, height: null, } export default Emoji
Update track_name, short_label, and long_label per discussions on 2016-09-09
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}'.format(metadata['protein'], metadata['serial_number']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = metadata['protein'] d['long_label'] = 'Predicted {} binding sites (site width = {}); iMADS model {}'.format(metadata['protein'], metadata['width'], metadata['serial_number']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number']) d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
Add the ability to set a content-type for an extension
<?php /* * Assetrinc source code * * Copyright Matt Light <matt.light@lightdatasys.com> * * For copyright and licensing information, please view the LICENSE * that is distributed with this source code. */ namespace Assetrinc; class ContentTypeManager { private $content_types = array( '' => 'text/text', 'css' => 'text/css', 'gif' => 'image/gif', 'ico' => 'image/vnd.microsoft.icon', 'jpg' => 'image/jpeg', 'js' => 'text/javascript', 'png' => 'image/png', ); public function getContentTypeForFileName($name) { $extensions = explode('.', basename($name)); $extension = null; foreach ($extensions as $ext) { if (isset($this->content_types[$ext])) { $extension = $ext; break; } } return $this->content_types["{$extension}"]; } public function setContentTypeForExtension($extension, $content_type) { $this->content_types[$extension] = $content_type; } }
<?php /* * Assetrinc source code * * Copyright Matt Light <matt.light@lightdatasys.com> * * For copyright and licensing information, please view the LICENSE * that is distributed with this source code. */ namespace Assetrinc; class ContentTypeManager { private $content_types = array( '' => 'text/text', 'css' => 'text/css', 'gif' => 'image/gif', 'ico' => 'image/vnd.microsoft.icon', 'jpg' => 'image/jpeg', 'js' => 'text/javascript', 'png' => 'image/png', ); public function getContentTypeForFileName($name) { $extensions = explode('.', basename($name)); $extension = null; foreach ($extensions as $ext) { if (isset($this->content_types[$ext])) { $extension = $ext; break; } } return $this->content_types["{$extension}"]; } }
Update fetching nodes to manually get all keys with iid prefix instead of using an index
import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: # nodes = redis.smembers(IID_INDEX) # all nodes are namespaced with iid nodes = redis.keys('iid:*') feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run()
import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: nodes = redis.smembers(IID_INDEX) feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run()
Fix gulp nodemon commang for windows environments original fix by @mannro
import bg from 'gulp-bg'; import eslint from 'gulp-eslint'; import gulp from 'gulp'; import runSequence from 'run-sequence'; import webpackBuild from './webpack/build'; import os from 'os'; const runEslint = () => { return gulp.src([ 'gulpfile.babel.js', 'src/**/*.js', 'webpack/*.js' // '!**/__tests__/*.*' ]) .pipe(eslint()) .pipe(eslint.format()); }; // Always use Gulp only in development gulp.task('set-dev-environment', () => { process.env.NODE_ENV = 'development'; // eslint-disable-line no-undef }); gulp.task('build', webpackBuild); gulp.task('eslint', () => { return runEslint(); }); gulp.task('eslint-ci', () => { // Exit process with an error code (1) on lint error for CI build. return runEslint().pipe(eslint.failAfterError()); }); gulp.task('test', (done) => { runSequence('eslint-ci', 'build', done); }); gulp.task('server-hot', bg('node', './webpack/server')); gulp.task('server', ['set-dev-environment', 'server-hot'], bg( os.type() == 'Windows_NT' ? '.\\node_modules\\.bin\\nodemon.cmd' : './node_modules/.bin/nodemon', './src/server')); gulp.task('default', ['server']);
import bg from 'gulp-bg'; import eslint from 'gulp-eslint'; import gulp from 'gulp'; import runSequence from 'run-sequence'; import webpackBuild from './webpack/build'; const runEslint = () => { return gulp.src([ 'gulpfile.babel.js', 'src/**/*.js', 'webpack/*.js' // '!**/__tests__/*.*' ]) .pipe(eslint()) .pipe(eslint.format()); }; // Always use Gulp only in development gulp.task('set-dev-environment', () => { process.env.NODE_ENV = 'development'; // eslint-disable-line no-undef }); gulp.task('build', webpackBuild); gulp.task('eslint', () => { return runEslint(); }); gulp.task('eslint-ci', () => { // Exit process with an error code (1) on lint error for CI build. return runEslint().pipe(eslint.failAfterError()); }); gulp.task('test', (done) => { runSequence('eslint-ci', 'build', done); }); gulp.task('server-hot', bg('node', './webpack/server')); gulp.task('server', ['set-dev-environment', 'server-hot'], bg('./node_modules/.bin/nodemon', './src/server')); gulp.task('default', ['server']);
Update solution to handle numbers
from collections import Counter import string import sys def beautiful_strings(line): line = line.rstrip() if line: beauty = 0 count = Counter(''.join(letter for letter in line.lower() if letter in string.lowercase)) for value in xrange(26, 26 - len(count), -1): if count: most_common = count.most_common(1) beauty += most_common[0][1] * value del count[most_common[0][0]] return beauty if __name__ == '__main__': with open(sys.argv[1], 'rt') as f: for line in f: print beautiful_strings(line)
from collections import Counter import string import sys def beautiful_strings(line): line = line.rstrip() if line: beauty = 0 count = Counter(''.join(letter for letter in line.lower() if letter in string.lowercase)) for value in xrange(26, 26 - len(count), -1): if count: most_common = count.most_common(1) beauty += most_common[0][1] * value del count[most_common[0][0]] return beauty if __name__ == '__main__': from pdb import set_trace; set_trace() with open(sys.argv[1], 'rt') as f: for line in f: print beautiful_strings(line)
Add hypothesis as framework for discoverability
from setuptools import setup setup( name='hypothesis-pb', packages=['hypothesis_protobuf'], platforms='any', version='1.2.0', description='Hypothesis extension to allow generating protobuf messages matching a schema.', author='H. Chase Stevens', author_email='chase@chasestevens.com', url='https://github.com/hchasestevens/hypothesis-protobuf', license='MIT', install_requires=[ 'hypothesis>=3.4.2', 'protobuf>=3.3.0,<4.0.0', ], tests_require=['pytest>=3.1.2', 'future>=0.16.0'], extras_require={'dev': ['pytest>=3.1.2', 'future>=0.16.0']}, classifiers=[ 'Framework :: Hypothesis', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ] )
from setuptools import setup setup( name='hypothesis-pb', packages=['hypothesis_protobuf'], platforms='any', version='1.2.0', description='Hypothesis extension to allow generating protobuf messages matching a schema.', author='H. Chase Stevens', author_email='chase@chasestevens.com', url='https://github.com/hchasestevens/hypothesis-protobuf', license='MIT', install_requires=[ 'hypothesis>=3.4.2', 'protobuf>=3.3.0,<4.0.0', ], tests_require=['pytest>=3.1.2', 'future>=0.16.0'], extras_require={'dev': ['pytest>=3.1.2', 'future>=0.16.0']}, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ] )
Exit with non-zero if command fails, useful in scripting and CI
<?php namespace Laravel\CLI; defined('DS') or die('No direct script access.'); use Laravel\Bundle; use Laravel\Config; use Laravel\Request; /** * Fire up the default bundle. This will ensure any dependencies that * need to be registered in the IoC container are registered and that * the auto-loader mappings are registered. */ Bundle::start(DEFAULT_BUNDLE); /** * The default database connection may be set by specifying a value * for the "database" CLI option. This allows migrations to be run * conveniently for a test or staging database. */ if ( ! is_null($database = get_cli_option('db'))) { Config::set('database.default', $database); } /** * We will register all of the Laravel provided tasks inside the IoC * container so they can be resolved by the task class. This allows * us to seamlessly add tasks to the CLI so that the Task class * doesn't have to worry about how to resolve core tasks. */ require path('sys').'cli/dependencies'.EXT; /** * We will wrap the command execution in a try / catch block and * simply write out any exception messages we receive to the CLI * for the developer. Note that this only writes out messages * for the CLI exceptions. All others will not be caught * and will be totally dumped out to the CLI. */ try { Command::run(array_slice($arguments, 1)); } catch (\Exception $e) { echo $e->getMessage().PHP_EOL; exit(1); } echo PHP_EOL;
<?php namespace Laravel\CLI; defined('DS') or die('No direct script access.'); use Laravel\Bundle; use Laravel\Config; use Laravel\Request; /** * Fire up the default bundle. This will ensure any dependencies that * need to be registered in the IoC container are registered and that * the auto-loader mappings are registered. */ Bundle::start(DEFAULT_BUNDLE); /** * The default database connection may be set by specifying a value * for the "database" CLI option. This allows migrations to be run * conveniently for a test or staging database. */ if ( ! is_null($database = get_cli_option('db'))) { Config::set('database.default', $database); } /** * We will register all of the Laravel provided tasks inside the IoC * container so they can be resolved by the task class. This allows * us to seamlessly add tasks to the CLI so that the Task class * doesn't have to worry about how to resolve core tasks. */ require path('sys').'cli/dependencies'.EXT; /** * We will wrap the command execution in a try / catch block and * simply write out any exception messages we receive to the CLI * for the developer. Note that this only writes out messages * for the CLI exceptions. All others will not be caught * and will be totally dumped out to the CLI. */ try { Command::run(array_slice($arguments, 1)); } catch (\Exception $e) { echo $e->getMessage(); } echo PHP_EOL;
Fix missing '/' in forum route
<?php namespace InsaLan\NewsBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use InsaLan\NewsBundle\Entity; class DefaultController extends Controller { /** * @Route("/") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $news = $em->getRepository('InsaLanNewsBundle:News')->getLatest(20); $sliders = $em->getRepository('InsaLanNewsBundle:Slider')->getLatest(20); //$this->get('session')->getFlashBag()->add('info', 'Hey!'); return array('news' => $news, 'sliders' => $sliders); } /** * @Route("/forum/") */ public function forumAction() { return $this->redirect("http://old.insalan.fr/forum"); } }
<?php namespace InsaLan\NewsBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use InsaLan\NewsBundle\Entity; class DefaultController extends Controller { /** * @Route("/") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $news = $em->getRepository('InsaLanNewsBundle:News')->getLatest(20); $sliders = $em->getRepository('InsaLanNewsBundle:Slider')->getLatest(20); //$this->get('session')->getFlashBag()->add('info', 'Hey!'); return array('news' => $news, 'sliders' => $sliders); } /** * @Route("/forum") */ public function forumAction() { return $this->redirect("http://old.insalan.fr/forum"); } }
Enable LoadTimeWeaving to support internal calls to proxied methods
/* * Copyright 2015-2016 EuregJUG. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.euregjug.site; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableLoadTimeWeaving; import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving; import org.springframework.context.annotation.PropertySource; import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; import org.springframework.instrument.classloading.LoadTimeWeaver; import org.springframework.scheduling.annotation.EnableAsync; /** * @author Michael J. Simons, 2015-12-26 */ @SpringBootApplication @EnableCaching @EnableAsync @EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED) @PropertySource("classpath:build.properties") public class Application { @Bean public LoadTimeWeaver loadTimeWeaver() { return new InstrumentationLoadTimeWeaver(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
/* * Copyright 2015-2016 EuregJUG. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.euregjug.site; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.EnableAsync; /** * @author Michael J. Simons, 2015-12-26 */ @SpringBootApplication @EnableCaching @EnableAsync @PropertySource("classpath:build.properties") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Remove trailing comma (part 2) This is starting to become a pain.
define([ 'stache!common/templates/visualisations/completion_numbers', 'extensions/views/view', 'common/views/visualisations/volumetrics/number', 'common/views/visualisations/volumetrics/submissions-graph' ], function (template, View, VolumetricsNumberView, SubmissionGraphView) { var CompletionNumbersView = View.extend({ template: template, views: { '#volumetrics-submissions-selected': { view: VolumetricsNumberView, options: { valueAttr: 'mean', selectionValueAttr: 'uniqueEvents', labelPrefix: 'mean per week over the' } }, '#volumetrics-submissions': { view: SubmissionGraphView, options: { valueAttr:'uniqueEvents' } } } }); return CompletionNumbersView; });
define([ 'stache!common/templates/visualisations/completion_numbers', 'extensions/views/view', 'common/views/visualisations/volumetrics/number', 'common/views/visualisations/volumetrics/submissions-graph', ], function (template, View, VolumetricsNumberView, SubmissionGraphView) { var CompletionNumbersView = View.extend({ template: template, views: { '#volumetrics-submissions-selected': { view: VolumetricsNumberView, options: { valueAttr: 'mean', selectionValueAttr: 'uniqueEvents', labelPrefix: 'mean per week over the' } }, '#volumetrics-submissions': { view: SubmissionGraphView, options: { valueAttr:'uniqueEvents' } } } }); return CompletionNumbersView; });
Fix /users/me for anonymous users
from rest_framework import viewsets from .models import User from .permissions import IsUserOrReadOnly from .serializers import AuthenticatedUserSerializer, UserSerializer class UserViewSet(viewsets.ModelViewSet): """API endpoint for viewing and editing users.""" queryset = User.objects.all() permission_classes = (IsUserOrReadOnly,) def get_serializer_class(self): return (AuthenticatedUserSerializer if self.request.user == self.get_object() else UserSerializer) def retrieve(self, request, pk=None): """Retrieve given user or current user if ``pk`` is "me".""" if pk == 'me' and request.user.is_authenticated(): pk = request.user.pk self.kwargs = {'pk': pk} return super().retrieve(request, pk)
from django.shortcuts import redirect from rest_framework import viewsets from .models import User from .permissions import IsUserOrReadOnly from .serializers import AuthenticatedUserSerializer, UserSerializer class UserViewSet(viewsets.ModelViewSet): """API endpoint for viewing and editing users.""" queryset = User.objects.all() permission_classes = (IsUserOrReadOnly,) def get_serializer_class(self): return (AuthenticatedUserSerializer if self.request.user == self.get_object() else UserSerializer) def retrieve(self, request, pk=None): """Retrieve given user or current user if ``pk`` is "me".""" if pk == 'me': pk = request.user.pk self.kwargs = {'pk': pk} return super().retrieve(request, pk)