text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change key for console namespace
<?php /** * This file is part of laravel-stubs package. * * @author ATehnix <atehnix@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ATehnix\LaravelStubs\Console; use Illuminate\Foundation\Console\ConsoleMakeCommand as BaseConsoleMakeCommand; class ConsoleMakeCommand extends BaseConsoleMakeCommand { /** * Get the stub file for the generator. * * @return string */ protected function getStub() { $stub = config('stubs.path') . '/console.stub'; return file_exists($stub) ? $stub : parent::getStub(); } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace . config('stubs.namespaces.command'); } }
<?php /** * This file is part of laravel-stubs package. * * @author ATehnix <atehnix@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ATehnix\LaravelStubs\Console; use Illuminate\Foundation\Console\ConsoleMakeCommand as BaseConsoleMakeCommand; class ConsoleMakeCommand extends BaseConsoleMakeCommand { /** * Get the stub file for the generator. * * @return string */ protected function getStub() { $stub = config('stubs.path').'/console.stub'; return file_exists($stub) ? $stub : parent::getStub(); } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.config('stubs.namespaces.console'); } }
Change what happens when there is no field on SmartDashboard
package org.robockets.robotswitcher; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** Used to get and initialize a SmartDashboard field for a robot number * * * @author Jake Backer * @version v.1.sleepy.1.0.ocean.1450230474.7 * * * * */ public class Switcher { /** Holds the value of the SmartDashboard field*/ public int currentRobot; /** Initializes the currentRobot field*/ public Switcher() { try{ currentRobot = getRobot(); }catch(DoesNotExistException e){ System.out.println("SmartDashboard field does not exist! Run initRobotNumber()"); } } /** * Stores the value of the field in SmartDashboard in currentRobot * @return The value of currentRobot * @throws DoesNotExistException Thrown if field on SmartDashboard does not exist */ public int getRobot() throws DoesNotExistException{ currentRobot = (int) SmartDashboard.getNumber("RobotNumber"); return currentRobot; } /** Initializes the field on SmartDashboard TEMPORARY*/ public void initRobotNumber() { SmartDashboard.putNumber("RobotNumber", 0); //TEMP } }
package org.robockets.robotswitcher; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** Used to get and initialize a SmartDashboard field for a robot number * * * @author Jake Backer * @version v.1.sleepy.1.0.ocean.1450230474.7 * * * * */ public class Switcher { /** Holds the value of the SmartDashboard field*/ public int currentRobot; /** Initializes the currentRobot field*/ public Switcher() { try{ currentRobot = getRobot(); }catch(DoesNotExistException e){ e.printStackTrace(); } } /** * Stores the value of the field in SmartDashboard in currentRobot * @return The value of currentRobot * @throws DoesNotExistException Thrown if field on SmartDashboard does not exist */ public int getRobot() throws DoesNotExistException{ currentRobot = (int) SmartDashboard.getNumber("RobotNumber"); return currentRobot; } /** Initializes the field on SmartDashboard TEMPORARY*/ public void initRobotNumber() { SmartDashboard.putNumber("RobotNumber", 0); //TEMP } }
Update authors in the comment We need to do this so that our teachers are not confused who wrote the code.
/* * (c) 2009. Ivan Voras <ivoras@fer.hr> * Released under the 2-clause BSDL. */ package enotes; import java.io.File; import javax.swing.UIManager; /** * * @author tbabej and company */ public class Main { static final String VERSION = "1.0beta6"; /** * @param args the command line arguments */ public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) {} MainForm mf = new MainForm(); mf.setSize(800, 550); mf.setLocationRelativeTo(null); mf.setVisible(true); if (args.length == 1) { File f = new File(args[0]); if (!f.canRead()) { System.err.println("File not found or access denied: "+args[0]); return; } if (!mf.internalOpenFile(new File(args[0]))) System.err.println("Cannot open file: "+args[0]); } } }
/* * (c) 2009. Ivan Voras <ivoras@fer.hr> * Released under the 2-clause BSDL. */ package enotes; import java.io.File; import javax.swing.UIManager; /** * * @author ivoras */ public class Main { static final String VERSION = "1.0beta6"; /** * @param args the command line arguments */ public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) {} MainForm mf = new MainForm(); mf.setSize(800, 550); mf.setLocationRelativeTo(null); mf.setVisible(true); if (args.length == 1) { File f = new File(args[0]); if (!f.canRead()) { System.err.println("File not found or access denied: "+args[0]); return; } if (!mf.internalOpenFile(new File(args[0]))) System.err.println("Cannot open file: "+args[0]); } } }
Update Validator to be compatible with Symfony 2.1 See why: https://github.com/symfony/symfony/blob/master/UPGRADE-2.1.md#validator
<?php /* * This file is part of the DoctrineEnumBundle package. * * (c) smurfy <https://github.com/smurfy> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Smurfy\DoctrineEnumBundle\Validator; use Symfony\Component\Validator\Constraints\ChoiceValidator; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * Doctrine Enum Type Validator */ class DoctrineEnumTypeValidator extends ChoiceValidator { /** * Checks if the value is valid * * @param string $value Value to validate * @param Constraint $constraint The Constraint executing this Validator * * @return boolean */ public function validate($value, Constraint $constraint) { if (!$constraint->entity) { throw new ConstraintDefinitionException('Entity not specified'); } $entity = $constraint->entity; $constraint->choices = $entity::getChoices(); return parent::validate($value, $constraint); } }
<?php /* * This file is part of the DoctrineEnumBundle package. * * (c) smurfy <https://github.com/smurfy> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Smurfy\DoctrineEnumBundle\Validator; use Symfony\Component\Validator\Constraints\ChoiceValidator; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * Doctrine Enum Type Validator */ class DoctrineEnumTypeValidator extends ChoiceValidator { /** * Checks if the value is valid * * @param string $value Value to validate * @param Constraint $constraint The Constraint executing this Validator * * @return boolean */ public function isValid($value, Constraint $constraint) { if (!$constraint->entity) { throw new ConstraintDefinitionException('Entity not specified'); } $entity = $constraint->entity; $constraint->choices = $entity::getChoices(); return parent::isValid($value, $constraint); } }
engine: Modify excepted exception to match impl The patch modifies the expected exception to the correct package so test could pass successfully. Change-Id: I016ced1da2d86e27497149fac82fea832ce01a1e Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com>
package org.ovirt.engine.core.dao; import static org.mockito.Mockito.mock; import org.apache.commons.lang.NotImplementedException; import org.junit.Before; import org.junit.Test; import org.ovirt.engine.core.compat.Guid; /** * A sparse test case for {@link NetworkDAOHibernateImpl} * intended to fail once we start implementing actual methods */ public class NetworkDAOHibernateImplTest { /** The DAO to test */ private NetworkDAOHibernateImpl dao; @Before public void setUp() { dao = new NetworkDAOHibernateImpl(); } @Test(expected = NotImplementedException.class) public void testUnimplementedMethods() { dao.getAllForCluster(mock(Guid.class), mock(Guid.class), true); } }
package org.ovirt.engine.core.dao; import static org.mockito.Mockito.mock; import org.junit.Before; import org.junit.Test; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NotImplementedException; /** * A sparse test case for {@link NetworkDAOHibernateImpl} * intended to fail once we start implementing actual methods */ public class NetworkDAOHibernateImplTest { /** The DAO to test */ private NetworkDAOHibernateImpl dao; @Before public void setUp() { dao = new NetworkDAOHibernateImpl(); } @Test(expected = NotImplementedException.class) public void testUnimplementedMethods() { dao.getAllForCluster(mock(Guid.class), mock(Guid.class), true); } }
Allow examples to use ES7 class properties
var fs = require('fs'); var path = require('path'); var webpack = require('webpack'); function isDirectory(dir) { return fs.lstatSync(dir).isDirectory(); } module.exports = { devtool: 'inline-source-map', entry: fs.readdirSync(__dirname).reduce(function (entries, dir) { var isDraft = dir.charAt(0) === '_'; if (!isDraft && isDirectory(path.join(__dirname, dir))) entries[dir] = path.join(__dirname, dir, 'app.js'); return entries; }, {}), output: { path: 'examples/__build__', filename: '[name].js', chunkFilename: '[id].chunk.js', publicPath: '/__build__/' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?optional=es7.classProperties' } ] }, resolve: { alias: { 'react-router': '../../modules' } }, plugins: [ new webpack.optimize.CommonsChunkPlugin('shared.js'), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') }) ] };
var fs = require('fs'); var path = require('path'); var webpack = require('webpack'); function isDirectory(dir) { return fs.lstatSync(dir).isDirectory(); } module.exports = { devtool: 'inline-source-map', entry: fs.readdirSync(__dirname).reduce(function (entries, dir) { var isDraft = dir.charAt(0) === '_'; if (!isDraft && isDirectory(path.join(__dirname, dir))) entries[dir] = path.join(__dirname, dir, 'app.js'); return entries; }, {}), output: { path: 'examples/__build__', filename: '[name].js', chunkFilename: '[id].chunk.js', publicPath: '/__build__/' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, resolve: { alias: { 'react-router': '../../modules/index' } }, plugins: [ new webpack.optimize.CommonsChunkPlugin('shared.js'), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') }) ] };
Remove incompatible backticks from migration. Closes GH-90
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AlterTableIncidentsRemoveDefaultComponent extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('incidents', function (Blueprint $table) { DB::statement("ALTER TABLE incidents CHANGE component_id component_id TINYINT(4) NOT NULL DEFAULT '0';"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('incidents', function (Blueprint $table) { DB::statement("ALTER TABLE incidents CHANGE component_id component_id TINYINT(4) NOT NULL DEFAULT '1';"); }); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AlterTableIncidentsRemoveDefaultComponent extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('incidents', function (Blueprint $table) { DB::statement("ALTER TABLE `incidents` CHANGE `component_id` `component_id` TINYINT(4) NOT NULL DEFAULT '0';"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('incidents', function (Blueprint $table) { DB::statement("ALTER TABLE `incidents` CHANGE `component_id` `component_id` TINYINT(4) NOT NULL DEFAULT '1';"); }); } }
Fix overrides enabled check to stop getting exceptions git-svn-id: 28fe03dfd74dd77dcc8ecfe99fabcec8eed81bba@3461 8555b757-d854-4b86-925a-82fd84c90ff4
<div class="box"> <h1>{tr:admin_page}</h1> <?php $sections = array('statistics', 'transfers', 'guests'); if(Config::get('config_overrides')) $sections[] = 'config'; $section = 'statistics'; if(array_key_exists('as', $_REQUEST)) $section = $_REQUEST['as']; if(!in_array($section, $sections)) throw new GUIUnknownAdminSectionException($section); ?> <div class="menu"> <ul> <?php foreach($sections as $s) { ?> <li class="<?php if($s == $section) echo 'current' ?>"> <a href="?s=admin&as=<?php echo $s ?>"> <?php echo Lang::tr('admin_'.$s.'_section') ?> </a> </li> <?php } ?> </ul> </div> <div class="<?php echo $section ?>_section section"> <?php Template::display('admin_'.$section.'_section') ?> </div> </div>
<div class="box"> <h1>{tr:admin_page}</h1> <?php $sections = array('statistics', 'transfers', 'guests'); try { if(count(Config::overrides())) $sections[] = 'config'; } catch(ConfigOverrideDisabledException $e) {} $section = 'statistics'; if(array_key_exists('as', $_REQUEST)) $section = $_REQUEST['as']; if(!in_array($section, $sections)) throw new GUIUnknownAdminSectionException($section); ?> <div class="menu"> <ul> <?php foreach($sections as $s) { ?> <li class="<?php if($s == $section) echo 'current' ?>"> <a href="?s=admin&as=<?php echo $s ?>"> <?php echo Lang::tr('admin_'.$s.'_section') ?> </a> </li> <?php } ?> </ul> </div> <div class="<?php echo $section ?>_section section"> <?php Template::display('admin_'.$section.'_section') ?> </div> </div>
Fix page-titles for unparameterized routes
import getHeaderSubtitleData from './modules/utils/getHeaderSubtitleData'; import qs from 'qs'; // Given the props of a component which has withRouter, return the parsed query // from the URL. export function parseQuery(location) { let query = location?.search; if (!query) return {}; // The unparsed query string looks like ?foo=bar&numericOption=5&flag but the // 'qs' parser wants it without the leading question mark, so strip the // question mark. if (query.startsWith('?')) query = query.substr(1); return qs.parse(query); } // Given the props of a component which has withRouter, return a subtitle for // the page. export function getHeaderSubtitleDataFromRouterProps(props) { const query = parseQuery(props.location); const params = props.match.params; const client = props.client; const { subtitleText = props.currentRoute?.title || "", subtitleLink = "" } = getHeaderSubtitleData(props.currentRoute?.routeName, query, params, client) || {}; return { subtitleText, subtitleLink }; }
import getHeaderSubtitleData from './modules/utils/getHeaderSubtitleData'; import qs from 'qs'; // Given the props of a component which has withRouter, return the parsed query // from the URL. export function parseQuery(location) { let query = location?.search; if (!query) return {}; // The unparsed query string looks like ?foo=bar&numericOption=5&flag but the // 'qs' parser wants it without the leading question mark, so strip the // question mark. if (query.startsWith('?')) query = query.substr(1); return qs.parse(query); } // Given the props of a component which has withRouter, return a subtitle for // the page. export function getHeaderSubtitleDataFromRouterProps(props) { const routeName = ""; //TODO const currentRoute = null; //TODO const query = parseQuery(props.location); const params = props.match.params; const client = props.client; const { subtitleText = currentRoute?.title || "", subtitleLink = "" } = getHeaderSubtitleData(routeName, query, params, client) || {}; return { subtitleText, subtitleLink }; }
Add html test coverage reporting The html reporter for test coverage provides a visual representation of exactly which lines/code have test coverage, so its very useful in tracking down missing tests. This will only affect development.
module.exports = function(config) { config.set({ basePath: '../', frameworks: ['jasmine'], files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'src/*.js', 'test/helpers/*.helper.js', 'test/specs/*.spec.js' ], reporters: ['progress', 'coverage'], preprocessors: { 'src/*.js': ['coverage'] }, coverageReporter: { reporters: [ { type: 'lcov' }, { type: 'text-summary' } ] }, port: 8089, runnerPort: 9109, urlRoot: '/__karma/', colors: true, logLevel: config.LOG_INFO, autoWatch: true, autoWatchInterval: 0, browsers: ['Firefox'], singleRun: true }); };
module.exports = function(config) { config.set({ basePath: '../', frameworks: ['jasmine'], files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'src/*.js', 'test/helpers/*.helper.js', 'test/specs/*.spec.js' ], reporters: ['progress', 'coverage'], preprocessors: { 'src/*.js': ['coverage'] }, coverageReporter: { reporters: [ { type: 'lcovonly' }, { type: 'text-summary' } ] }, port: 8089, runnerPort: 9109, urlRoot: '/__karma/', colors: true, logLevel: config.LOG_INFO, autoWatch: true, autoWatchInterval: 0, browsers: ['Firefox'], singleRun: true }); };
Use proxy logger + fix formatting
package com.wavefront.agent; import java.io.IOException; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; /** * This RESTEasy interceptor allows disabling GZIP compression even for methods annotated with @GZIP by removing the * Content-Encoding header. * RESTEasy always adds "Content-Encoding: gzip" header when it encounters @GZIP annotation, but if the request body * is actually sent uncompressed, it violates section 3.1.2.2 of RFC7231. * * Created by vasily@wavefront.com on 6/9/17. */ public class DisableGZIPEncodingInterceptor implements WriterInterceptor { private static final Logger logger = Logger.getLogger(DisableGZIPEncodingInterceptor.class.getCanonicalName()); public DisableGZIPEncodingInterceptor() { } public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { logger.fine("Interceptor : " + this.getClass().getName() + ", Method : aroundWriteTo"); Object encoding = context.getHeaders().getFirst("Content-Encoding"); if (encoding != null && encoding.toString().equalsIgnoreCase("gzip")) { context.getHeaders().remove("Content-Encoding"); } context.proceed(); } }
package com.wavefront.agent; import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages; import java.io.IOException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; /** * This RESTEasy interceptor allows disabling GZIP compression even for methods annotated with @GZIP by removing the * Content-Encoding header. * RESTEasy always adds "Content-Encoding: gzip" header when it encounters @GZIP annotation, but if the request body * is actually sent uncompressed, it violates section 3.1.2.2 of RFC7231. * * Created by vasily@wavefront.com on 6/9/17. */ public class DisableGZIPEncodingInterceptor implements WriterInterceptor { public DisableGZIPEncodingInterceptor() { } public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", this.getClass().getName()); Object encoding = context.getHeaders().getFirst("Content-Encoding"); if(encoding != null && encoding.toString().equalsIgnoreCase("gzip")) { context.getHeaders().remove("Content-Encoding"); } context.proceed(); } }
Fix Remove banner still showing, use inline css instead.
// ==UserScript== // @author sk3dsu(Fadli Ishak) // @name MyLowyat // @version 0.2.2 // @description Removing some elements of the forum to be a bit cleaner for SFW. // @namespace https://github.com/mfadliishak/lowyatAvatars // @icon https://forum.lowyat.net/favicon.ico // @match http*://forum.lowyat.net/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js // @run-at document-idle // ==/UserScript== /** * 1. Remove all those annoying avatars! * */ var avatars = $('.avatarwrap'); for (i = 0; i < avatars.length; i++) { var item = avatars[i]; item.style.display = "none"; } /** * 2. Remove that big banner up there. * */ var banner = $('.borderwrap #logostrip'); if (banner.length) { banner.css("display", "none"); }
// ==UserScript== // @author sk3dsu(Fadli Ishak) // @name MyLowyat // @version 0.2.1 // @description Removing some elements of the forum to be a bit cleaner for SFW. // @namespace https://github.com/mfadliishak/lowyatAvatars // @icon https://forum.lowyat.net/favicon.ico // @match http*://forum.lowyat.net/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js // ==/UserScript== /** * 1. Remove all those annoying avatars! * */ var avatars = $('.avatarwrap'); for (i = 0; i < avatars.length; i++) { var item = avatars[i]; item.style = "display:none;"; } /** * 2. Remove that big banner up there. * */ var banner = $('.borderwrap'); if (banner) { banner.style = "display:none;"; }
Add default page for getSources
<?php namespace Politix\PolitikportalBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; // use Politix\PolitikportalBundle\Model; class SourcesController extends Controller { function getSourceAction($source) { $out['source'] = $source; $sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10'; $out['items'] = $this->getDB($sql); return $this->render('PolitikportalBundle:Default:items.html.twig', $out); } function getSourcesAction($page = 1) { $db = $this->get('SourceModel'); $out['sources'] = $db->getSources($page); $out['page'] = $page; return $this->render('PolitikportalBundle:Default:sources.html.twig', $out); } }
<?php namespace Politix\PolitikportalBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; // use Politix\PolitikportalBundle\Model; class SourcesController extends Controller { function getSourceAction($source) { $out['source'] = $source; $sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10'; $out['items'] = $this->getDB($sql); return $this->render('PolitikportalBundle:Default:items.html.twig', $out); } function getSourcesAction($page) { $db = $this->get('SourceModel'); $out['sources'] = $db->getSources($page); return $this->render('PolitikportalBundle:Default:sources.html.twig', $out); } }
Fix CIPANGO-99: Creating a DiameterServletRequest without specifying the destinationhost field leads to a null pointer exception when sending a the request
// ======================================================================== // Copyright 2010 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.diameter.router; import java.util.Hashtable; import java.util.Map; import org.cipango.diameter.node.DiameterRequest; import org.cipango.diameter.node.Peer; public class DefaultRouter implements DiameterRouter { private Map<String, Peer> _peers = new Hashtable<String, Peer>(); public Peer getRoute(DiameterRequest request) { if (request.getDestinationHost() == null) return null; return _peers.get(request.getDestinationHost()); } public void peerAdded(Peer peer) { _peers.put(peer.getHost(), peer); } public void peerRemoved(Peer peer) { _peers.remove(peer.getHost()); } }
// ======================================================================== // Copyright 2010 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.diameter.router; import java.util.Hashtable; import java.util.Map; import org.cipango.diameter.node.DiameterRequest; import org.cipango.diameter.node.Node; import org.cipango.diameter.node.Peer; public class DefaultRouter implements DiameterRouter { private Map<String, Peer> _peers = new Hashtable<String, Peer>(); public Peer getRoute(DiameterRequest request) { return _peers.get(request.getDestinationHost()); } public void peerAdded(Peer peer) { _peers.put(peer.getHost(), peer); } public void peerRemoved(Peer peer) { _peers.remove(peer.getHost()); } }
Switch to postgis for Travis At least until I have time to figure out the spatialite automatic build.
from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'atlas_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine' } }
from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'ENGINE': 'django.db.backends.sqlite3', #'NAME': 'atlas_test', #'USER': 'postgres', 'PASSWORD': '', 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine' } }
Fix for older versions of django
from test_plus.test import TestCase from django_private_chat.views import * from django.test import RequestFactory from django.urlresolvers import reverse from django_private_chat.models import * class TestDialogListView(TestCase): def setUp(self): self.factory = RequestFactory() self.owner_user = self.make_user(username="owuser") self.oponet_user = self.make_user(username="opuser") self.dialog = Dialog() self.dialog.owner = self.owner_user self.dialog.opponent = self.oponet_user self.dialog.save() self.right_dialog = self.dialog self.dialog = Dialog() self.dialog.owner = self.make_user(username="user1") self.dialog.opponent = self.make_user(username="user2") self.dialog.save() def test_get_queryset(self): request = self.factory.get(reverse('dialogs_detail', kwargs={'username':'opuser'})) request.user = self.owner_user test_view = DialogListView() test_view.request = request queryset = list(test_view.get_queryset()) required_queryset = [self.right_dialog] self.assertEqual(queryset, required_queryset)
from test_plus.test import TestCase from django_private_chat.views import * from django.test import RequestFactory from django.urls import reverse from django_private_chat.models import * class TestDialogListView(TestCase): def setUp(self): self.factory = RequestFactory() self.owner_user = self.make_user(username="owuser") self.oponet_user = self.make_user(username="opuser") self.dialog = Dialog() self.dialog.owner = self.owner_user self.dialog.opponent = self.oponet_user self.dialog.save() self.right_dialog = self.dialog self.dialog = Dialog() self.dialog.owner = self.make_user(username="user1") self.dialog.opponent = self.make_user(username="user2") self.dialog.save() def test_get_queryset(self): request = self.factory.get(reverse('dialogs_detail', kwargs={'username':'opuser'})) request.user = self.owner_user test_view = DialogListView() test_view.request = request queryset = list(test_view.get_queryset()) required_queryset = [self.right_dialog] self.assertEqual(queryset, required_queryset)
Handle error if autocomplete query fails
$(document).ready(function() { $("[data-autocomplete-source]").each(function() { var url = $(this).data("autocomplete-source"); var target = $(this).data("autocomplete-rel"); $(this).autocomplete({ minLength: 2, source: function(request,response) { $.ajax({ url: url, data: { term: request.term }, success: function(data) { var list = $.map(data, function(patient) { return { label: patient.unique_label, id: patient.id }; }); response(list); }, error: function(jqXHR, textStatus, errorThrown) { var msg = "An error occurred. Please contact an administrator."; response({ label: msg, id: 0}); } }); }, search: function(event, ui) { $(target).val(""); }, select: function(event, ui) { $(target).val(ui.item.id); } }); }); });
$(document).ready(function() { $("[data-autocomplete-source]").each(function() { var url = $(this).data("autocomplete-source"); var target = $(this).data("autocomplete-rel"); $(this).autocomplete({ minLength: 2, source: function(request,response) { var path = url + "?term=" + request.term $.getJSON(path, function(data) { var list = $.map(data, function(patient) { return { label: patient.unique_label, value: patient.unique_label, id: patient.id }; }); response(list); }) }, search: function(event, ui) { $(target).val(""); }, select: function(event, ui) { $(target).val(ui.item.id); } }); }); });
Change default mode on files that won't exist much longer. I know kind of pointless, but still. Also the mode doesn't do anything yet.
package fs import ( "time" ) var vfs map[string]*Item type Item struct { Contents string Dir bool User string Group string Mode uint CreatedAt time.Time UpdatedAt time.Time } func init() { now := time.Now() vfs = map[string]*Item{ "/": &Item{ Contents: "", Dir: true, User: "root", Group: "root", Mode: 644, CreatedAt: now, UpdatedAt: now, }, "/README": &Item{ Contents: "Welcomeeeeee!", Dir: false, User: "root", Group: "root", Mode: 644, CreatedAt: now, UpdatedAt: now, }, } }
package fs import ( "time" ) var vfs map[string]*Item type Item struct { Contents string Dir bool User string Group string Mode uint CreatedAt time.Time UpdatedAt time.Time } func init() { now := time.Now() vfs = map[string]*Item{ "/": &Item{ Contents: "", Dir: true, User: "root", Group: "root", Mode: 777, CreatedAt: now, UpdatedAt: now, }, "/README": &Item{ Contents: "Welcomeeeeee!", Dir: false, User: "root", Group: "root", Mode: 777, CreatedAt: now, UpdatedAt: now, }, } }
Add 'newusername' id to username on signup page Needed for js frontend.
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, PasswordField, HiddenField from wtforms.validators import DataRequired, Length, URL, Optional class LoginForm(FlaskForm): username = StringField('Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}) password = PasswordField('Password', [Length(max=1024)]) class SignupForm(FlaskForm): username = StringField( 'Username', [Length(min=3, max=255)], render_kw={'inputmode': 'verbatim'}, id='newusername', ) password = PasswordField('Password', [Length(min=8, max=1024)]) class AddForm(FlaskForm): title = StringField('Title', [Length(max=255)]) url = StringField('URL', [Optional(), URL(), Length(max=255)]) username = StringField( 'Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}, ) other = TextAreaField('Other') class EditForm(AddForm): id = HiddenField()
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, PasswordField, HiddenField from wtforms.validators import DataRequired, Length, URL, Optional class LoginForm(FlaskForm): username = StringField('Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}) password = PasswordField('Password', [Length(max=1024)]) class SignupForm(FlaskForm): username = StringField('Username', [Length(min=3, max=255)], render_kw={'inputmode': 'verbatim'}) password = PasswordField('Password', [Length(min=8, max=1024)]) class AddForm(FlaskForm): title = StringField('Title', [Length(max=255)]) url = StringField('URL', [Optional(), URL(), Length(max=255)]) username = StringField( 'Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}, ) other = TextAreaField('Other') class EditForm(AddForm): id = HiddenField()
Add missing bundle registration for the SensioBuzzBundle.
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = [ new Sensio\Bundle\BuzzBundle\SensioBuzzBundle(), new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new PlatinumPixs\Aws\PlatinumPixsAwsBundle(), new ROH\Bundle\StackManagerBundle\ROHStackManagerBundle(), new ROH\Bundle\TemporalScalingBundle\ROHTemporalScalingBundle(), ]; if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new PlatinumPixs\Aws\PlatinumPixsAwsBundle(), new ROH\Bundle\StackManagerBundle\ROHStackManagerBundle(), new ROH\Bundle\TemporalScalingBundle\ROHTemporalScalingBundle(), ]; if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
Test fix: always use full cms-models config state as default
<?php namespace Czim\CmsModels\Test; abstract class TestCase extends \Orchestra\Testbench\TestCase { /** * {@inheritdoc} */ protected function getEnvironmentSetUp($app) { $app['config']->set('translatable.locales', [ 'en', 'nl' ]); $app['config']->set('translatable.use_fallback', true); $app['config']->set('translatable.fallback_locale', 'en'); $app['config']->set('cms-models', include(realpath(dirname(__DIR__) . '/config/cms-models.php'))); $app['config']->set('cms-models.analyzer.database.class', null); $app['view']->addNamespace('cms-models', realpath(dirname(__DIR__) . '/resources/views')); } }
<?php namespace Czim\CmsModels\Test; abstract class TestCase extends \Orchestra\Testbench\TestCase { /** * {@inheritdoc} */ protected function getEnvironmentSetUp($app) { $app['config']->set('translatable.locales', [ 'en', 'nl' ]); $app['config']->set('translatable.use_fallback', true); $app['config']->set('translatable.fallback_locale', 'en'); $app['config']->set('cms-models.analyzer.traits.listify', [ \Czim\Listify\Listify::class, ]); $app['view']->addNamespace('cms-models', realpath(dirname(__DIR__) . '/resources/views')); } }
Add trailing slash to chrome_proxy telemetry test page URL. BUG=507797 Review URL: https://codereview.chromium.org/1229563002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#337895}
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry import story class ReenableAfterBypassPage(page_module.Page): """A test page for the re-enable after bypass tests. Attributes: bypass_seconds_min: The minimum number of seconds that the bypass triggered by loading this page should last. bypass_seconds_max: The maximum number of seconds that the bypass triggered by loading this page should last. """ def __init__(self, url, page_set, bypass_seconds_min, bypass_seconds_max): super(ReenableAfterBypassPage, self).__init__(url=url, page_set=page_set) self.bypass_seconds_min = bypass_seconds_min self.bypass_seconds_max = bypass_seconds_max class ReenableAfterBypassStorySet(story.StorySet): """ Chrome proxy test sites """ def __init__(self): super(ReenableAfterBypassStorySet, self).__init__() # Test page for "Chrome-Proxy: block=0". Loading this page should cause all # data reduction proxies to be bypassed for one to five minutes. self.AddStory(ReenableAfterBypassPage( url="http://check.googlezip.net/block/", page_set=self, bypass_seconds_min=60, bypass_seconds_max=300))
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry import story class ReenableAfterBypassPage(page_module.Page): """A test page for the re-enable after bypass tests. Attributes: bypass_seconds_min: The minimum number of seconds that the bypass triggered by loading this page should last. bypass_seconds_max: The maximum number of seconds that the bypass triggered by loading this page should last. """ def __init__(self, url, page_set, bypass_seconds_min, bypass_seconds_max): super(ReenableAfterBypassPage, self).__init__(url=url, page_set=page_set) self.bypass_seconds_min = bypass_seconds_min self.bypass_seconds_max = bypass_seconds_max class ReenableAfterBypassStorySet(story.StorySet): """ Chrome proxy test sites """ def __init__(self): super(ReenableAfterBypassStorySet, self).__init__() # Test page for "Chrome-Proxy: block=0". Loading this page should cause all # data reduction proxies to be bypassed for one to five minutes. self.AddStory(ReenableAfterBypassPage( url="http://check.googlezip.net/block", page_set=self, bypass_seconds_min=60, bypass_seconds_max=300))
Sort the single letter aliases first
function Option(aliases, description, name, def) { var opt = {}; if (aliases.constructor === Object) { opt = aliases; } else { opt.aliases = aliases; opt.value = null; opt.def = def; opt.description = description; opt.name = name; } if (typeof opt.aliases === "string") { opt.aliases = [opt.aliases]; } opt.aliases.forEach(function (c, i) { opt.aliases[i] = c.length === 1 ? "-" + c : ("--" + c); }); opt.aliases.sort(function (a, b) { return a.length === 2 ? -1 : 1; }); opt.is_provided = false; return opt; } module.exports = Option;
function Option(aliases, description, name, def) { var opt = {}; if (aliases.constructor === Object) { opt = aliases; } else { opt.aliases = aliases; opt.value = null; opt.def = def; opt.description = description; opt.name = name; } if (typeof opt.aliases === "string") { opt.aliases = [opt.aliases]; } opt.aliases.forEach(function (c, i) { opt.aliases[i] = c.length === 1 ? "-" + c : ("--" + c); }); opt.is_provided = false; return opt; } module.exports = Option;
Add XML files in template folder to package data
from setuptools import setup setup( name = 'saml2idp', version = '0.18', author = 'John Samuel Anderson', author_email = 'john@andersoninnovative.com', description = 'SAML 2.0 IdP for Django', long_description = 'SAML 2.0 Identity Provider app for Django projects.', install_requires = [ 'M2Crypto>=0.20.1', 'BeautifulSoup>=3.2.0', ], license = 'MIT', packages = ['saml2idp', 'saml2idp.tests'], package_dir = {'saml2idp': 'idptest/saml2idp'}, package_data = {'saml2idp': ['templates/saml2idp/*.html', 'templates/saml2idp/*.xml']}, url = 'http://code.google.com/p/django-saml2-idp/', zip_safe = True, )
from setuptools import setup setup( name = 'saml2idp', version = '0.18', author = 'John Samuel Anderson', author_email = 'john@andersoninnovative.com', description = 'SAML 2.0 IdP for Django', long_description = 'SAML 2.0 Identity Provider app for Django projects.', install_requires = [ 'M2Crypto>=0.20.1', 'BeautifulSoup>=3.2.0', ], license = 'MIT', packages = ['saml2idp', 'saml2idp.tests'], package_dir = {'saml2idp': 'idptest/saml2idp'}, package_data = {'saml2idp': ['templates/saml2idp/*.html']}, url = 'http://code.google.com/p/django-saml2-idp/', zip_safe = True, )
Cover the "__debug__" attribute as well.
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de # # Python tests originally created or extracted from other peoples work. The # parts were too small to be protected. # # 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. # """ Some module documentation. With newline and stuff.""" import os print "doc:", __doc__ print "filename:", __file__ print "builtins:", __builtins__ print "debug", __debug__
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de # # Python tests originally created or extracted from other peoples work. The # parts were too small to be protected. # # 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. # """ Some module documentation. With newline and stuff.""" import os print "doc:", __doc__ print "filename:", __file__ print "builtins:", __builtins__
Check for both env variables.
require('dotenv').config() const http = require('http') const url = require('url') require('isomorphic-fetch') const log = require('./log') const auth = require('./auth') const playlist = require('./playlist') if (!process.env.SPOTIFY_CLIENT_ID || !process.env.SPOTIFY_CLIENT_SECRET) { log.error('Set environment variables specified in README.') process.exit(1) } function requestHandler(request, response) { const urlObj = url.parse(request.url, true) log.debug(urlObj) if (urlObj.query.error) { response.end() log.error(urlObj.query.error) return } if (urlObj.query.code) { response.end() log.info(`got auth code: ${urlObj.query.code}`) auth.authCodeFlow(urlObj.query.code) .then(a => console.log(a)) // .then(playlist.gen) } else { const html = `<!DOCTYPE html> <button onclick="document.location.assign('${auth.url}')"> Click to Authorize </button>` response.end(html) } } ;(() => { http.createServer(requestHandler).listen(8080) })()
require('dotenv').config() const http = require('http') const url = require('url') require('isomorphic-fetch') const log = require('./log') const auth = require('./auth') const playlist = require('./playlist') if (!process.env.SPOTIFY_CLIENT_ID) { log.error('Set environment variable SPOTIFY_CLIENT_ID') process.exit(1) } function requestHandler(request, response) { const urlObj = url.parse(request.url, true) log.debug(urlObj) if (urlObj.query.error) { response.end() log.error(urlObj.query.error) return } if (urlObj.query.code) { response.end() log.info(`got auth code: ${urlObj.query.code}`) auth.authCodeFlow(urlObj.query.code) .then(a => console.log(a)) // .then(playlist.gen) } else { const html = `<!DOCTYPE html> <button onclick="document.location.assign('${auth.url}')"> Click to Authorize </button>` response.end(html) } } ;(() => { http.createServer(requestHandler).listen(8080) })()
Add algorithm argument to get_hash
# -*- coding: utf-8 -*- ''' Use pycrypto to generate random passwords on the fly. ''' # Import python libraries try: import Crypto.Random # pylint: disable=E0611 HAS_RANDOM = True except ImportError: HAS_RANDOM = False import crypt import re import salt.exceptions def secure_password(length=20): ''' Generate a secure password. ''' if not HAS_RANDOM: raise ImportError('generating passwords requires >= pycrypto v2.1.0') pw = '' while len(pw) < length: pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1)) return pw def gen_hash(salt=None, password=None, algorithm='sha512'): ''' Generate /etc/shadow hash ''' hash_algorithms = {'md5':'$1$', 'blowfish':'$2a$', 'sha256':'$5$', 'sha512':'$6$'} if algorithm not in hash_algorithms: raise salt.exceptions.SaltInvocationError('Not support {0} algorithm'.format(algorithm)) if password is None: password = secure_password() if salt is None: salt = secure_password(8) salt = hash_algorithms[algorithm] + salt return crypt.crypt(password, salt)
# -*- coding: utf-8 -*- ''' Use pycrypto to generate random passwords on the fly. ''' # Import python libraries try: import Crypto.Random # pylint: disable=E0611 HAS_RANDOM = True except ImportError: HAS_RANDOM = False import crypt import re def secure_password(length=20): ''' Generate a secure password. ''' if not HAS_RANDOM: raise ImportError('generating passwords requires >= pycrypto v2.1.0') pw = '' while len(pw) < length: pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1)) return pw def gen_hash(salt=None, password=None): ''' Generate /etc/shadow hash ''' if password is None: password = secure_password() if salt is None: salt = '$6' + secure_password(8) return crypt.crypt(password, salt)
Send return values back correctly
// @flow /** * Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { return function() { if (!self) { self = this; } var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(res){ last.apply(self, [null, res]); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
// @flow /** * Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { return function() { if (!self) { self = this; } var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(){ last.apply(self, arguments); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
Fix an issue with the new aprslib
import aprslib import logging import nmea class AprsIS: logger = None def __init__(self, callsign, password): self.logger = logging.getLogger(__name__) self.aprs_connection = aprslib.IS(callsign, password) self.aprs_connection.connect() def send_beacon(self, callsign, sfx, message, gpgga): position = nmea.gpgga_get_position(gpgga) aprs_frame = callsign+'>APK'+sfx+',DSTAR*:!'+position['lat'] + position['lat_coord'] + '\\'+position['long']+position['long_coord']+'a/A=' + position['height'] + message self.logger.info("Sending APRS Frame: " + aprs_frame) try: self.aprs_connection.sendall(aprs_frame) self.logger.info("APRS Beacon sent!") except Exception, e: self.logger.info("Invalid aprs frame [%s] - %s" % (aprs_frame, str(e))
import aprslib import logging import nmea class AprsIS: logger = None def __init__(self, callsign, password): self.logger = logging.getLogger(__name__) self.aprs_connection = aprslib.IS(callsign, password) self.aprs_connection.connect() def send_beacon(self, callsign, sfx, message, gpgga): position = nmea.gpgga_get_position(gpgga) aprs_frame = callsign+'>APK'+sfx+',DSTAR*:!'+position['lat'] + position['lat_coord'] + '\\'+position['long']+position['long_coord']+'a/A=' + position['height'] + message self.logger.info("Sending APRS Frame: " + aprs_frame) try: self.aprs_connection.sendall(aprs.Frame(aprs_frame)) except: self.logger.info("Invalid aprs frame: " + aprs_frame)
Fix POSTing from the client
#!/usr/bin/python import time import subprocess from os import path, chdir, getcwd import requests from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class ProjectEventHandler(FileSystemEventHandler): def on_any_event(self, event): print('Dispatching request.') # Find the git root # TODO this could be made more efficient with popen cwd = getcwd() chdir(path.dirname(event.src_path)) repo_root = subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], universal_newlines=True) repo_url = subprocess.check_output(['git', 'remote', 'get-url', 'origin'], universal_newlines=True) chdir(cwd) payload = { 'action': 'edit', 'url': repo_url } r = requests.post('http://localhost:8000/api/people/aj', json=payload) print(r.status_code, r.reason) print('realtime.recurse.com client starting up...') event_handler = ProjectEventHandler() observer = Observer() observer.schedule(event_handler, path='.', recursive=True) observer.start() print('Listening for filesystem events.') try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
#!/usr/bin/python import time import subprocess from os import path, chdir, getcwd import requests from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class ProjectEventHandler(FileSystemEventHandler): def on_any_event(self, event): print('Dispatching request.') # Find the git root # TODO this could be made more efficient with popen cwd = getcwd() chdir(path.dirname(event.src_path)) repo_root = subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], universal_newlines=True) repo_url = subprocess.check_output(['git', 'remote', 'get-url', 'origin'], universal_newlines=True) chdir(cwd) payload = { 'action': 'edit', 'repo_url': repo_url } r = requests.post('http://localhost:8000', json=payload) print('realtime.recurse.com client starting up...') event_handler = ProjectEventHandler() observer = Observer() observer.schedule(event_handler, path='.', recursive=True) observer.start() print('Listening for filesystem events.') try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
Add mocha reporter to karma configuration
export default function configureKarma (config) { const { projectPath, watch, webpackConfig, karmaConfig: userKarmaConfig } = config const defaultKarmaConfig = { basePath: projectPath, frameworks: ['jasmine', 'phantomjs-shim', 'sinon'], browsers: ['PhantomJS'], reporters: ['mocha'], files: [ 'src/**/*.spec.*', { pattern: 'src/**/*', watched: true, included: false } ], preprocessors: { // add webpack as preprocessor 'src/**/*.spec.*': ['webpack'] }, webpack: webpackConfig, webpackServer: { noInfo: true }, singleRun: !watch, autoWatch: watch } const karmaConfig = { ...defaultKarmaConfig, ...userKarmaConfig } return { ...config, karmaConfig } }
export default function configureKarma (config) { const { projectPath, watch, webpackConfig, karmaConfig: userKarmaConfig } = config const defaultKarmaConfig = { basePath: projectPath, frameworks: ['jasmine', 'phantomjs-shim', 'sinon'], browsers: ['PhantomJS'], files: [ 'src/**/*.spec.*', { pattern: 'src/**/*', watched: true, included: false } ], preprocessors: { // add webpack as preprocessor 'src/**/*.spec.*': ['webpack'] }, webpack: webpackConfig, webpackServer: { noInfo: true }, singleRun: !watch, autoWatch: watch } const karmaConfig = { ...defaultKarmaConfig, ...userKarmaConfig } return { ...config, karmaConfig } }
Improve NamespaceBasedFactory + remove UrlDispatcherCache - Prepare NamespaceBasedFactory for migrating to PHP-DI 6.0 - NamespaceBasedFactoryBuilder introduced - Client code refactoring - Various CS fixes
<?php namespace Spotman\Acl\ResourceRulesCollectorFactory; use BetaKiller\Factory\NamespaceBasedFactoryBuilder; use Spotman\Acl\ResourceInterface; use Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface; class GenericAclResourceRulesCollectorFactory implements AclResourceRulesCollectorFactoryInterface { /** * @var \BetaKiller\Factory\NamespaceBasedFactory */ private $factory; /** * GenericAclResourceRulesCollectorFactory constructor. * * @param \BetaKiller\Factory\NamespaceBasedFactoryBuilder $factoryBuilder */ public function __construct(NamespaceBasedFactoryBuilder $factoryBuilder) { $this->factory = $factoryBuilder ->createFactory() ->setClassNamespaces('Acl', 'ResourceRulesCollector') ->setClassSuffix('ResourceRulesCollector') ->setExpectedInterface(ResourceRulesCollectorInterface::class); } /** * @param \Spotman\Acl\ResourceInterface $resource * * @return \Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface * @throws \BetaKiller\Factory\FactoryException */ public function createCollector(ResourceInterface $resource): ResourceRulesCollectorInterface { $collectorName = $resource->getResourceId(); return $this->factory->create($collectorName, [ 'resource' => $resource, ]); } }
<?php namespace Spotman\Acl\ResourceRulesCollectorFactory; use BetaKiller\Factory\NamespaceBasedFactory; use Spotman\Acl\ResourceInterface; use Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface; class GenericAclResourceRulesCollectorFactory implements AclResourceRulesCollectorFactoryInterface { /** * @var \BetaKiller\Factory\NamespaceBasedFactory */ private $factory; /** * GenericAclResourceRulesCollectorFactory constructor. * * @param \BetaKiller\Factory\NamespaceBasedFactory $factory */ public function __construct(NamespaceBasedFactory $factory) { $this->factory = $factory ->setClassNamespaces('Acl', 'ResourceRulesCollector') ->setClassSuffix('ResourceRulesCollector') ->setExpectedInterface(ResourceRulesCollectorInterface::class); } /** * @param \Spotman\Acl\ResourceInterface $resource * * @return \Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface */ public function createCollector(ResourceInterface $resource) { $collectorName = $resource->getResourceId(); return $this->factory->create($collectorName, [ 'resource' => $resource, ]); } }
Fix exception type in a test
# -*- coding: utf-8 -*- from blox.file import File from pytest import raises_regexp class TestFile(object): def test_mode(self, tmpfile): raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo') assert File(tmpfile).mode == 'r' assert File(tmpfile, 'w').mode == 'w' def test_filename(self, tmpfile): raises_regexp(IOError, 'No such file', File, '/foo/bar/baz') assert File(tmpfile).filename == tmpfile def test_create_dataset(self, tmpfile): raises_regexp(IOError, 'file is not writable', File(tmpfile).create_dataset, 'a', [])
# -*- coding: utf-8 -*- from blox.file import File from pytest import raises_regexp class TestFile(object): def test_mode(self, tmpfile): raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo') assert File(tmpfile).mode == 'r' assert File(tmpfile, 'w').mode == 'w' def test_filename(self, tmpfile): raises_regexp(IOError, 'No such file', File, '/foo/bar/baz') assert File(tmpfile).filename == tmpfile def test_create_dataset(self, tmpfile): raises_regexp(ValueError, 'file is not writable', File(tmpfile).create_dataset, 'a', [])
Remove unused variable in CRNA
const mergeDirs = require('merge-dirs').default; const helpers = require('../../lib/helpers'); const path = require('path'); const latestVersion = require('latest-version'); module.exports = latestVersion('@storybook/react-native').then(version => { // copy all files from the template directory to project directory mergeDirs(path.resolve(__dirname, 'template/'), '.', 'overwrite'); const packageJson = helpers.getPackageJson(); packageJson.dependencies = packageJson.dependencies || {}; packageJson.devDependencies = packageJson.devDependencies || {}; packageJson.devDependencies['@storybook/react-native'] = `^${version}`; if (!packageJson.dependencies['react-dom'] && !packageJson.devDependencies['react-dom']) { packageJson.devDependencies['react-dom'] = '^15.5.4'; } packageJson.scripts = packageJson.scripts || {}; packageJson.scripts['storybook'] = 'storybook start -p 7007'; helpers.writePackageJson(packageJson); });
const mergeDirs = require('merge-dirs').default; const helpers = require('../../lib/helpers'); const path = require('path'); const shell = require('shelljs'); const latestVersion = require('latest-version'); module.exports = latestVersion('@storybook/react-native').then(version => { // copy all files from the template directory to project directory mergeDirs(path.resolve(__dirname, 'template/'), '.', 'overwrite'); const packageJson = helpers.getPackageJson(); packageJson.dependencies = packageJson.dependencies || {}; packageJson.devDependencies = packageJson.devDependencies || {}; packageJson.devDependencies['@storybook/react-native'] = `^${version}`; if (!packageJson.dependencies['react-dom'] && !packageJson.devDependencies['react-dom']) { packageJson.devDependencies['react-dom'] = '^15.5.4'; } packageJson.scripts = packageJson.scripts || {}; packageJson.scripts['storybook'] = 'storybook start -p 7007'; helpers.writePackageJson(packageJson); });
Support explicit adding of file names.
package org.reldb.dbrowser.hooks; import java.util.ArrayList; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.reldb.dbrowser.DBrowser; public class OpenDocumentEventProcessor implements Listener { private ArrayList<String> filesToOpen = new ArrayList<String>(1); private boolean retrieved = false; public synchronized void handleEvent(Event event) { if (event.text != null) if (retrieved) DBrowser.openFile(event.text); else filesToOpen.add(event.text); } public synchronized String[] retrieveFilesToOpen() { try { return filesToOpen.toArray(new String[filesToOpen.size()]); } finally { filesToOpen.clear(); retrieved = true; } } public synchronized void addFilesToOpen(String[] fileNames) { for (String argument: fileNames) filesToOpen.add(argument); } }
package org.reldb.dbrowser.hooks; import java.util.ArrayList; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.reldb.dbrowser.DBrowser; public class OpenDocumentEventProcessor implements Listener { private ArrayList<String> filesToOpen = new ArrayList<String>(1); private boolean retrieved = false; public synchronized void handleEvent(Event event) { if (event.text != null) if (retrieved) DBrowser.openFile(event.text); else filesToOpen.add(event.text); } public synchronized String[] retrieveFilesToOpen() { try { return filesToOpen.toArray(new String[filesToOpen.size()]); } finally { filesToOpen.clear(); retrieved = true; } } }
Fix Team component (missing style)
import React from "react" import { StaticQuery, graphql } from "gatsby" import Member from "./Member" import "./index.module.css" const Team = ({ members }) => ( <ul styleName="root"> {members.map((data, index) => ( <li key={index}> <Member {...data} /> </li> ))} </ul> ) export default () => ( <StaticQuery query={teamQuery} render={({ allTeamYaml: { edges: team } }) => ( <Team members={team.map(m => m.node)} /> )} /> ) const teamQuery = graphql` query TeamQuery { allTeamYaml { edges { node { name role photo { childImageSharp { fluid(maxWidth: 320, quality: 100) { ...GatsbyImageSharpFluid_noBase64 } } } social { twitter github dribbble } } } } } `
import React from "react" import { StaticQuery, graphql } from "gatsby" import Member from "./Member" import "./index.module.css" const Team = ({ members }) => ( <ul styleName="root"> {members.map((data, index) => ( <li key={index} styleName="member"> <Member {...data} /> </li> ))} </ul> ) export default () => ( <StaticQuery query={teamQuery} render={({ allTeamYaml: { edges: team } }) => ( <Team members={team.map(m => m.node)} /> )} /> ) const teamQuery = graphql` query TeamQuery { allTeamYaml { edges { node { name role photo { childImageSharp { fluid(maxWidth: 320, quality: 100) { ...GatsbyImageSharpFluid_noBase64 } } } social { twitter github dribbble } } } } } `
Use egg attribute of the links To correct install it you must do: $ python setup.py install or $ pip install --process-dependency-links bankbarcode
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='bankbarcode', version='0.1.1', packages=find_packages(), url='https://github.com/gisce/bankbarcode', license='GNU Affero General Public License v3', author='GISCE-TI, S.L.', author_email='devel@gisce.net', # We need python-barcode v0.8, to have Code128 (EAN128), not released yet # https://bitbucket.org/whitie/python-barcode/issues/16/pypi-08-release-request dependency_links=[ "https://bitbucket.org/whitie/python-barcode/get/6c22b96.zip#egg=pybarcode-0.8b1" ], install_requires=[ 'pybarcode>=0.8b1' ], description='barcodes for financial documents' )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='bankbarcode', version='0.1.1', packages=find_packages(), url='https://github.com/gisce/bankbarcode', license='GNU Affero General Public License v3', author='GISCE-TI, S.L.', author_email='devel@gisce.net', # We need python-barcode v0.8, to have Code128 (EAN128), not released yet # https://bitbucket.org/whitie/python-barcode/issues/16/pypi-08-release-request dependency_links=[ "https://bitbucket.org/whitie/python-barcode/get/6c22b96a2ca2.zip" ], install_requires=[ 'pybarcode>=0.8b1' ], description='barcodes for financial documents' )
Make Watch also a context manager
import asyncio class Watch: """Represents an inotify watch as added by InotifyProtocol.watch()""" def __init__(self, watch_descriptor, callback, protocol): """ :param int watch_descriptor: The watch descriptor as returned by inotify_add_watch :param callback: A function with one positional argument (the event object) called when an inotify event happens. """ self.watch_descriptor = watch_descriptor self._callback = callback self._closed = False self._protocol = protocol def __enter__(self): return self def __exit__(self, *exc): self.close() @asyncio.coroutine def dispatch_event(self, event): if not self._closed: yield from self._callback(event) def close(self): if not self._closed: self._protocol._remove_watch(self.watch_descriptor) self._closed = True
import asyncio class Watch: """Represents an inotify watch as added by InotifyProtocol.watch()""" def __init__(self, watch_descriptor, callback, protocol): """ :param int watch_descriptor: The watch descriptor as returned by inotify_add_watch :param callback: A function with one positional argument (the event object) called when an inotify event happens. """ self.watch_descriptor = watch_descriptor self._callback = callback self._closed = False self._protocol = protocol @asyncio.coroutine def dispatch_event(self, event): if not self._closed: yield from self._callback(event) def close(self): if not self._closed: self._protocol._remove_watch(self.watch_descriptor) self._closed = True
Fix AOS detection in MutationObserver
let callback = () => {}; function containsAOSNode(nodes) { let i, currentNode, result; for (i = 0; i < nodes.length; i += 1) { currentNode = nodes[i]; if (currentNode.dataset && currentNode.dataset.aos) { return true; } result = currentNode.children && containsAOSNode(currentNode.children); if (result) { return true; } } return false; } function ready(selector, fn) { const doc = window.document; const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; const observer = new MutationObserver(check); callback = fn; observer.observe(doc.documentElement, { childList: true, subtree: true, removedNodes: true }); } function check(mutations) { if (!mutations) return; mutations.forEach(mutation => { const addedNodes = Array.prototype.slice.call(mutation.addedNodes); const removedNodes = Array.prototype.slice.call(mutation.removedNodes); const allNodes = addedNodes.concat(removedNodes); if (containsAOSNode(allNodes)) { return callback(); } }); } export default ready;
let callback = () => {}; function ready(selector, fn) { const doc = window.document; const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; const observer = new MutationObserver(check); callback = fn; observer.observe(doc.documentElement, { childList: true, subtree: true, removedNodes: true }); } function check(mutations) { if (!mutations) return; mutations.forEach(mutation => { const addedNodes = Array.prototype.slice.call(mutation.addedNodes); const removedNodes = Array.prototype.slice.call(mutation.removedNodes); const anyAOSElementAdded = addedNodes .concat(removedNodes) .filter(el => el.hasAttribute && el.hasAttribute('data-aos')).length; if (anyAOSElementAdded) { callback(); } }); } export default ready;
Create default logger object if one is not sent
var winston = require('winston'), path = require('path'); var logLevel = 'warn'; var sharedLogger = function(filename) { return new winston.Logger({ level: logLevel, transports: [ new winston.transports.Console({ prettyPrint: true, timestamp: true, level: logLevel, label: path.basename(filename, '.js') }) ] }); }; sharedLogger.setLevel = function (val) { logLevel = val; } function failedPromiseHandler(logger) { logger = logger || sharedLogger(__filename); return function(err) { logger.error(err.stack); }; } function uuid() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } module.exports = { logger: sharedLogger, failedPromiseHandler: failedPromiseHandler, uuid: uuid }
var winston = require('winston'), path = require('path'); var logLevel = 'warn'; var sharedLogger = function(filename) { return new winston.Logger({ level: logLevel, transports: [ new winston.transports.Console({ prettyPrint: true, timestamp: true, level: logLevel, label: path.basename(filename, '.js') }) ] }); }; sharedLogger.setLevel = function (val) { logLevel = val; } function failedPromiseHandler(logger) { logger = logger || sharedLogger; return function(err) { logger.error(err.stack); }; } function uuid() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } module.exports = { logger: sharedLogger, failedPromiseHandler: failedPromiseHandler, uuid: uuid }
Make new zips appear at the top
import React from 'react'; import ZipCodeEntry from './ZipCodeEntry'; import WeatherDisplay from './WeatherDisplay'; export default class App extends React.Component { constructor(props) { super(props); this.handleNewZip = this.handleNewZip.bind(this); this.state = { zips: [] }; } render() { const displays = this.state.zips.map((zip, i) => ( <WeatherDisplay key={i} zip={zip} /> )).reverse(); return ( <div style={{ padding: '1em' }}> <ZipCodeEntry newZip={this.handleNewZip} /> {displays} </div> ); } handleNewZip(zip) { if (/\d{5}/.test(zip)) { this.setState({ zips: this.state.zips.concat(zip) }); } else { alert("That's not a valid zip code!"); } } }
import React from 'react'; import ZipCodeEntry from './ZipCodeEntry'; import WeatherDisplay from './WeatherDisplay'; export default class App extends React.Component { constructor(props) { super(props); this.handleNewZip = this.handleNewZip.bind(this); this.state = { zips: [] }; } render() { const displays = this.state.zips.map((zip, i) => ( <WeatherDisplay key={i} zip={zip} /> )); return ( <div style={{ padding: '1em' }}> <ZipCodeEntry newZip={this.handleNewZip} /> {displays} </div> ); } handleNewZip(zip) { if (/\d{5}/.test(zip)) { this.setState({ zips: this.state.zips.concat(zip) }); } else { alert("That's not a valid zip code!"); } } }
Make sure it does not pick as well
const path = require('path'); const expect = require('chai').expect; const findProject = require('../../src/config/ios/findProject'); const mockFs = require('mock-fs'); const projects = require('../fixtures/projects'); describe('ios::findProject', () => { before(() => { mockFs({ testDir: projects }); }); it('should return path to xcodeproj if found', () => { const userConfig = {}; mockFs(projects.flat); expect(findProject('')).to.contain('.xcodeproj'); }); it('should ignore xcodeproj from example folders', () => { const userConfig = {}; mockFs({ examples: projects.flat, Examples: projects.flat, App: projects.flat, }); expect(findProject('').toLowerCase()).to.not.contain('examples'); }); it('should ignore xcodeproj from test folders at any level', () => { const userConfig = {}; mockFs({ test: projects.flat, IntegrationTests: projects.flat, tests: projects.flat, app: { tests: projects.flat, src: projects.flat, }, }); expect(findProject('').toLowerCase()).to.not.contain('test'); }); afterEach(() => { mockFs.restore(); }); });
const path = require('path'); const expect = require('chai').expect; const findProject = require('../../src/config/ios/findProject'); const mockFs = require('mock-fs'); const projects = require('../fixtures/projects'); describe('ios::findProject', () => { before(() => { mockFs({ testDir: projects }); }); it('should return path to xcodeproj if found', () => { const userConfig = {}; mockFs(projects.flat); expect(findProject('')).to.contain('.xcodeproj'); }); it('should ignore xcodeproj from example folders', () => { const userConfig = {}; mockFs({ examples: projects.flat, Examples: projects.flat, App: projects.flat, }); expect(findProject('').toLowerCase()).to.not.contain('examples'); }); it('should ignore xcodeproj from test folders at any level', () => { const userConfig = {}; mockFs({ test: projects.flat, IntegrationTests: projects.flat, tests: projects.flat, app: { tests: projects.flat, src: projects.flat, }, }); expect(findProject('').toLowerCase()).to.not.contain('tests'); }); afterEach(() => { mockFs.restore(); }); });
Move classifier from Pre-Alpha to Beta
import os, sys from setuptools import setup, find_packages pkgname = "SHARPpy" ### GET VERSION INFORMATION ### setup_path = os.path.split(os.path.abspath(__file__))[0] sys.path.append(os.path.join(setup_path, pkgname.lower())) import version version.write_git_version() ver = version.get_version().split("+")[0] sys.path.pop() ### ACTUAL SETUP VALUES ### name = pkgname version = ver author = "Patrick Marsh, Kelton Halbert, and Greg Blumberg" author_email = "patrick.marsh@noaa.gov, keltonhalbert@ou.edu, wblumberg@ou.edu" description = "Sounding/Hodograph Analysis and Research Program for Python" long_description = "" license = "BSD" keywords = "meteorology soundings analysis" url = "https://github.com/sharppy/SHARPpy" packages = find_packages() package_data = {"": ["*.md", "*.txt", "*.png"],} include_package_data = True classifiers = ["Development Status :: 4 - Beta"] setup( name = name, version = version, author = author, author_email = author_email, description = description, long_description = long_description, license = license, keywords = keywords, url = url, packages = packages, package_data = package_data, include_package_data = include_package_data, classifiers = classifiers )
import os, sys from setuptools import setup, find_packages pkgname = "SHARPpy" ### GET VERSION INFORMATION ### setup_path = os.path.split(os.path.abspath(__file__))[0] sys.path.append(os.path.join(setup_path, pkgname.lower())) import version version.write_git_version() ver = version.get_version().split("+")[0] sys.path.pop() ### ACTUAL SETUP VALUES ### name = pkgname version = ver author = "Patrick Marsh, Kelton Halbert, and Greg Blumberg" author_email = "patrick.marsh@noaa.gov, keltonhalbert@ou.edu, wblumberg@ou.edu" description = "Sounding/Hodograph Analysis and Research Program for Python" long_description = "" license = "BSD" keywords = "meteorology soundings analysis" url = "https://github.com/sharppy/SHARPpy" packages = find_packages() package_data = {"": ["*.md", "*.txt", "*.png"],} include_package_data = True classifiers = ["Development Status :: 2 - Pre-Alpha"] setup( name = name, version = version, author = author, author_email = author_email, description = description, long_description = long_description, license = license, keywords = keywords, url = url, packages = packages, package_data = package_data, include_package_data = include_package_data, classifiers = classifiers )
Fix typos in WER scorer Summary: Fix typos in WER scorer - The typos lead to using prediction length as the denominator in the formula, which is wrong. Reviewed By: alexeib Differential Revision: D23139261 fbshipit-source-id: d1bba0044365813603ce358388e880c1b3f9ec6b
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import editdistance from fairseq.scoring import register_scoring @register_scoring("wer") class WerScorer(object): def __init__(self, *unused): self.reset() def reset(self): self.distance = 0 self.ref_length = 0 def add_string(self, ref, pred): ref_items = ref.split() pred_items = pred.split() self.distance += editdistance.eval(ref_items, pred_items) self.ref_length += len(ref_items) def result_string(self): return f"WER: {self.score()}" def score(self): return ( 100.0 * self.distance / self.ref_length if self.ref_length > 0 else 0 )
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import editdistance from fairseq.scoring import register_scoring @register_scoring("wer") class WerScorer(object): def __init__(self, *unused): self.reset() def reset(self): self.distance = 0 self.target_length = 0 def add_string(self, ref, pred): pred_items = ref.split() targ_items = pred.split() self.distance += editdistance.eval(pred_items, targ_items) self.target_length += len(targ_items) def result_string(self): return f"WER: {self.score()}" def score(self): return ( 100.0 * self.distance / self.target_length if self.target_length > 0 else 0 )
Send source information on virtual account opening
var VirtualAccOpeningData = (function(){ "use strict"; function getDetails(password, residence, verificationCode){ var req = { new_account_virtual: 1, client_password: password, residence: residence, verification_code: verificationCode }; // Add AdWords parameters // NOTE: following lines can be uncommented (Re-check property names) // once these fields added to this ws call // var utm_data = AdWords.getData(); // req.source = utm_data.utm_source || utm_data.referrer || 'direct'; // if(utm_data.utm_medium) req.medium = utm_data.utm_medium; // if(utm_data.utm_campaign) req.campaign = utm_data.utm_campaign; if ($.cookie('affiliate_tracking')) { req.affiliate_token = JSON.parse($.cookie('affiliate_tracking')).t; } BinarySocket.send(req); } return { getDetails: getDetails }; }());
var VirtualAccOpeningData = (function(){ "use strict"; function getDetails(password, residence, verificationCode){ var req = { new_account_virtual: 1, client_password: password, residence: residence, verification_code: verificationCode }; if ($.cookie('affiliate_tracking')) { req.affiliate_token = JSON.parse($.cookie('affiliate_tracking')).t; } BinarySocket.send(req); } return { getDetails: getDetails }; }());
PLFM-7403: Add missing mapping for datasetcollection updates
package org.sagebionetworks.repo.manager.table; import java.util.HashMap; import java.util.Map; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Simple mapping of entity types to transaction managers. * */ @Service public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider { private Map<EntityType, TableUpdateRequestManager> managerMap; @Autowired public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) { managerMap = new HashMap<>(); managerMap.put(EntityType.table, tableEntityUpdateManager); managerMap.put(EntityType.entityview, tableViewUpdateManager); managerMap.put(EntityType.submissionview, tableViewUpdateManager); managerMap.put(EntityType.dataset, tableViewUpdateManager); managerMap.put(EntityType.datasetcollection, tableViewUpdateManager); } @Override public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) { ValidateArgument.required(type, "type"); TableUpdateRequestManager manager = managerMap.get(type); if (manager == null){ throw new IllegalArgumentException("Unknown type: "+type); } return manager; } }
package org.sagebionetworks.repo.manager.table; import java.util.HashMap; import java.util.Map; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Simple mapping of entity types to transaction managers. * */ @Service public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider { private Map<EntityType, TableUpdateRequestManager> managerMap; @Autowired public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) { managerMap = new HashMap<>(); managerMap.put(EntityType.table, tableEntityUpdateManager); managerMap.put(EntityType.entityview, tableViewUpdateManager); managerMap.put(EntityType.submissionview, tableViewUpdateManager); managerMap.put(EntityType.dataset, tableViewUpdateManager); } @Override public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) { ValidateArgument.required(type, "type"); TableUpdateRequestManager manager = managerMap.get(type); if (manager == null){ throw new IllegalArgumentException("Unknown type: "+type); } return manager; } }
Use start and end of day
import chrono from 'chrono-node' import wholeMonth from 'chrono-refiner-wholemonth' export default extractDates const parser = new chrono.Chrono parser.refiners.push(wholeMonth) function extractDates(str) { let extracted = str const dates = [] for (let match of parser.parse(str)) { let startMoment = match.start.moment().startOf('day').utc() let endMoment = match.end.moment().endOf('day').utc() let start = startMoment.toDate() let end = endMoment.toDate() let startArr = JSON.stringify(startMoment.toArray()) let endArr = JSON.stringify(endMoment.toArray()) let text = `(startArr >= ${startArr} and startArr <= ${endArr})` dates.push( { start, end, text } ) extracted = extracted.replace(match.text, '') } return {extracted, dates} }
import chrono from 'chrono-node' import wholeMonth from 'chrono-refiner-wholemonth' export default extractDates const parser = new chrono.Chrono parser.refiners.push(wholeMonth) function extractDates(str) { let extracted = str const dates = [] for (let match of parser.parse(str)) { let start = match.start.moment().utc().toDate() let end = match.end.moment().utc().toDate() let startArr = JSON.stringify(match.start.moment().utc().toArray()) let endArr = JSON.stringify(match.end.moment().utc().toArray()) let text = `(startArr >= ${startArr} and startArr <= ${endArr})` dates.push( { start, end, text } ) extracted = extracted.replace(match.text, '') } return {extracted, dates} }
Fix a bug, where fading in .hidden on contact page would also fade in searchField, since there was a class collision.
$(document).ready(function() { $("form.contact").on("submit", function(e) { var $fadeElement = $(".fade-on-submit"); if (!$fadeElement) return; e.preventDefault(); fadeOutAndRevealBeneath($fadeElement); }); var imageId = 1; $("img.replaceable").on("click", function() { var image = $(this); imageId++; if (imageId > 3) imageId = 1; image.attr("src", "assets/timeline_images/" + imageId + ".jpg"); }); $(".switch-on-click").on("click", function() { fadeOutAndRevealBeneath($(this), 200, function() { $("#searchField").focus(); }); }); function fadeOutAndRevealBeneath(element, speed, completionFunction) { if (!speed) speed = 400; var hidden = element.siblings(".hidden"); element.fadeOut(speed, function() { hidden.fadeIn(speed, function() { hidden.removeClass("hidden"); completionFunction(); }); }); } });
$(document).ready(function() { $("form.contact").on("submit", function(e) { var $fadeElement = $(".fade-on-submit"); if (!$fadeElement) return; e.preventDefault(); fadeOutAndRevealBeneath($fadeElement); }); var imageId = 1; $("img.replaceable").on("click", function() { var image = $(this); imageId++; if (imageId > 3) imageId = 1; image.attr("src", "assets/timeline_images/" + imageId + ".jpg"); }); $(".switch-on-click").on("click", function() { fadeOutAndRevealBeneath($(this), 200, function() { $("#searchField").focus(); }); }); function fadeOutAndRevealBeneath(element, speed, completionFunction) { if (!speed) speed = 400; var hidden = $(".hidden"); element.fadeOut(speed, function() { hidden.fadeIn(speed, function() { hidden.removeClass("hidden"); completionFunction(); }); }); } });
Update interface implementation in baseSocial
var _ = require('lodash'); /** * Create base social instance * @param {Object} [_config] * @constructor */ function BaseSocial(_config) { this._config = {}; _.forOwn(_config, function (value, key) { this.set(key, value); }.bind(this)); } /** * Get configuration value * @param {String} [path] * @returns {*} */ BaseSocial.prototype.get = function (path) { return typeof path === 'undefined' ? this._config : _.get(this._config, path); }; /** * Set configuration value * @param {String} path * @param {*} value * @returns {BaseSocial} */ BaseSocial.prototype.set = function (path, value) { _.set(this._config, path, value); return this; }; /** * Get provider for sending notifications * @returns {*} */ BaseSocial.prototype.getProvider = function () { return this._provider; }; /** * Set new provider to this pusher * @param {*} provider * @returns {BaseSocial} */ BaseSocial.prototype.setProvider = function (provider) { this._provider = provider; return this; }; BaseSocial.prototype.getFriends = _; BaseSocial.prototype.getPhotos = _; module.exports = BaseSocial;
var _ = require('lodash'); /** * Create base social instance * @param {Object} [_config] * @constructor */ function BaseSocial(_config) { this._config = {}; _.forOwn(_config, function (value, key) { this.set(key, value); }.bind(this)); } /** * Get configuration value * @param {String} [path] * @returns {*} */ BaseSocial.prototype.get = function (path) { return typeof path === 'undefined' ? this._config : _.get(this._config, path); }; /** * Set configuration value * @param {String} path * @param {*} value * @returns {BaseSocial} */ BaseSocial.prototype.set = function (path, value) { _.set(this._config, path, value); return this; }; /** * Get provider for sending notifications * @returns {*} */ BaseSocial.prototype.getProvider = function () { return this._provider; }; /** * Set new provider to this pusher * @param {*} provider * @returns {BaseSocial} */ BaseSocial.prototype.setProvider = function (provider) { this._provider = provider; return this; }; BaseSocial.prototype.friends = _; BaseSocial.prototype.photos = _; module.exports = BaseSocial;
Make ConfigUtil runnable in both processes.
'use strict'; const process = require('process'); const JsonDB = require('node-json-db'); let instance = null; let app = null; /* To make the util runnable in both main and renderer process */ if (process.type === 'renderer') { app = require('electron').remote.app; } else { app = require('electron').app; } class ConfigUtil { constructor() { if (instance) { return instance; } else { instance = this; } this.db = new JsonDB(app.getPath('userData') + '/config.json', true, true); return instance; } getConfigItem(key, defaultValue = null) { const value = this.db.getData('/')[key]; if (value === undefined) { this.setConfigItem(key, value); return defaultValue; } else { return value; } } setConfigItem(key, value) { this.db.push(`/${key}`, value, true); } removeConfigItem(key) { this.db.delete(`/${key}`); } } module.exports = new ConfigUtil();
'use strict'; const {app} = require('electron').remote; const JsonDB = require('node-json-db'); let instance = null; class ConfigUtil { constructor() { if (instance) { return instance; } else { instance = this; } this.db = new JsonDB(app.getPath('userData') + '/config.json', true, true); return instance; } getConfigItem(key, defaultValue = null) { const value = this.db.getData('/')[key]; if (value === undefined) { this.setConfigItem(key, value); return defaultValue; } else { return value; } } setConfigItem(key, value) { this.db.push(`/${key}`, value, true); } removeConfigItem(key) { this.db.delete(`/${key}`); } } module.exports = new ConfigUtil();
Check to validated xml file has been loaded already; if so, dont load it again.
package org.recap.route; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.impl.DefaultMessage; import org.recap.model.jpa.ReportEntity; import org.recap.repository.ReportDetailRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.List; /** * Created by peris on 8/20/16. */ @Component public class XMLFileLoadValidator implements Processor { @Autowired ReportDetailRepository reportDetailRepository; /** * Check to see if the xml file has been loaded already. If so, set empty body such that the file doesn't get * processed again. * @param exchange * @throws Exception */ @Override public void process(Exchange exchange) throws Exception { String camelFileName = (String) exchange.getIn().getHeader("CamelFileName"); List<ReportEntity> reportEntity = reportDetailRepository.findByFileName(camelFileName); if(!CollectionUtils.isEmpty(reportEntity)){ DefaultMessage defaultMessage = new DefaultMessage(); defaultMessage.setBody(""); exchange.setIn(defaultMessage); exchange.setOut(defaultMessage); } } }
package org.recap.route; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.impl.DefaultMessage; import org.recap.model.jpa.ReportEntity; import org.recap.repository.ReportDetailRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.List; /** * Created by peris on 8/20/16. */ @Component public class XMLFileLoadValidator implements Processor { @Autowired ReportDetailRepository reportDetailRepository; @Override public void process(Exchange exchange) throws Exception { String camelFileName = (String) exchange.getIn().getHeader("CamelFileName"); List<ReportEntity> reportEntity = reportDetailRepository.findByFileName(camelFileName); if(!CollectionUtils.isEmpty(reportEntity)){ DefaultMessage defaultMessage = new DefaultMessage(); defaultMessage.setBody(""); exchange.setIn(defaultMessage); exchange.setOut(defaultMessage); } } }
Move process.nextTick() to run() method Hope this fixes the tests. Thanks @janmeier
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); return this; } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this return this } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
Add Preconditions NPE check to pool release method Reviewed By: oprisnik Differential Revision: D14706933 fbshipit-source-id: 5ef5a1dbee73ce1ec11533efeb61845fa15a61a5
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.memory; import android.graphics.Bitmap; import com.facebook.common.internal.Preconditions; import com.facebook.common.memory.MemoryTrimType; import com.facebook.imageutils.BitmapUtil; public class DummyBitmapPool implements BitmapPool { @Override public void trim(MemoryTrimType trimType) { // nop } @Override public Bitmap get(int size) { return Bitmap.createBitmap( 1, (int) Math.ceil(size / (double) BitmapUtil.RGB_565_BYTES_PER_PIXEL), Bitmap.Config.RGB_565); } @Override public void release(Bitmap value) { Preconditions.checkNotNull(value); value.recycle(); } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.memory; import android.graphics.Bitmap; import com.facebook.common.memory.MemoryTrimType; import com.facebook.imageutils.BitmapUtil; public class DummyBitmapPool implements BitmapPool { @Override public void trim(MemoryTrimType trimType) { // nop } @Override public Bitmap get(int size) { return Bitmap.createBitmap( 1, (int) Math.ceil(size / (double) BitmapUtil.RGB_565_BYTES_PER_PIXEL), Bitmap.Config.RGB_565); } @Override public void release(Bitmap value) { value.recycle(); } }
Support Sort Order For TEXT Index
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = { "$meta": "textScore" } """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
#!/bin/env python # # Copyright 2010 bit.ly # # 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. """ AsyncMongo is an asynchronous library for accessing mongo http://github.com/bitly/asyncmongo """ try: import bson except ImportError: raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver") # also update in setup.py version = "1.3" version_info = (1, 3) ASCENDING = 1 """Ascending sort order.""" DESCENDING = -1 """Descending sort order.""" GEO2D = "2d" """Index specifier for a 2-dimensional `geospatial index`""" TEXT = { $meta: "textScore" } """TEXT Index sort order.""" from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError, DataError, IntegrityError, ProgrammingError, NotSupportedError) from client import Client
Add h5py as a dependency
from setuptools import setup setup(name='emopy', version='0.1', description='Emotion Recognition Package for Python', url='http://github.com/selameab/emopy', author='Selameab', author_email='email@selameab.com', license='', package_data={'emopy': ['models/*.h5', 'models/*.json']}, include_package_data=True, packages=['emopy'], dependency_links=["https://github.com/tensorflow/tensorflow/tarball/master"], install_requires=[ 'dlib', 'tensorflow', 'keras>=2.0', 'h5py' ], zip_safe=False)
from setuptools import setup setup(name='emopy', version='0.1', description='Emotion Recognition Package for Python', url='http://github.com/selameab/emopy', author='Selameab', author_email='email@selameab.com', license='', package_data={'emopy': ['models/*.h5', 'models/*.json']}, include_package_data=True, packages=['emopy'], dependency_links=["https://github.com/tensorflow/tensorflow/tarball/master"], install_requires=[ 'dlib', 'tensorflow', 'keras>=2.0' ], zip_safe=False)
Adjust the difficulties a bit
module.exports = { Env: process.env.NODE_ENV || 'development', Permissions: { viewPage: 'viewPage' }, boxWidth: 55, boxHeight: 30, Difficulties: { 1: { name: 'Very Easy', percent: 10 }, 2: { name: 'Easy', percent: 15 }, 3: { name: 'Medium', percent: 20 }, 4: { name: 'Hard', percent: 30 }, 5: { name: 'Nightmare', percent: 60 }, 6: { name: 'Impossibruuu!!', percent: 90 } } };
module.exports = { Env: process.env.NODE_ENV || 'development', Permissions: { viewPage: 'viewPage' }, boxWidth: 55, boxHeight: 30, Difficulties: { 1: { name: 'Easy', percent: 10 }, 2: { name: 'Medium', percent: 25 }, 3: { name: 'Hard', percent: 40 }, 4: { name: 'Nightmare', percent: 60 } } };
Fix PDFjs links in kiosk mode
import ko from "knockout"; import sortBy from "lodash/collection/sortBy"; import api from "../api"; import formatter from "../ko/formatter"; import store from "../store"; export default class Document { constructor(data) { Object.assign(this, data); // replace stub (id-only) objects this.lectures = sortBy(data.lectures.map(l => store.lecturesById.get(l.id)), 'name'); this.examinants = sortBy(data.examinants.map(e => store.examinantsById.get(e.id)), 'name'); this.date = new Date(data.date); this.validation_time = data.validation_time ? new Date(data.validation_time) : null; // retain some consistency this.numberOfPages = this.number_of_pages; this.documentType = this.document_type; this.validationTime = this.validation_time; ko.track(this, ['validated']); } get extendedAttributes() { return formatter.formatDate(this.date) + ', ' + this.comment; } get examinantsText() { return this.examinants.map(e => e.name).join(', '); } get previewURL() { return `${api.baseUrl}view/${this.id}`; } get PDFjsURL() { return `pdfjs/web/viewer.html?file=${encodeURIComponent(this.previewURL)}`; } get editURL() { return `${api.baseUrl}../admin/document/edit/?id=${this.id}`; } get store() { return store; } }
import ko from "knockout"; import sortBy from "lodash/collection/sortBy"; import api from "../api"; import formatter from "../ko/formatter"; import store from "../store"; export default class Document { constructor(data) { Object.assign(this, data); // replace stub (id-only) objects this.lectures = sortBy(data.lectures.map(l => store.lecturesById.get(l.id)), 'name'); this.examinants = sortBy(data.examinants.map(e => store.examinantsById.get(e.id)), 'name'); this.date = new Date(data.date); this.validation_time = data.validation_time ? new Date(data.validation_time) : null; // retain some consistency this.numberOfPages = this.number_of_pages; this.documentType = this.document_type; this.validationTime = this.validation_time; ko.track(this, ['validated']); } get extendedAttributes() { return formatter.formatDate(this.date) + ', ' + this.comment; } get examinantsText() { return this.examinants.map(e => e.name).join(', '); } get previewURL() { return `${api.baseUrl}view/${this.id}`; } get PDFjsURL() { return `/pdfjs/web/viewer.html?file=${encodeURIComponent(this.previewURL)}`; } get editURL() { return `${api.baseUrl}../admin/document/edit/?id=${this.id}`; } get store() { return store; } }
Implement skipping of non-existing files If any other plugin leaves `files` with entry that does not correspond to an existing file this entry should be skipped silently.
var fs = require('fs'); var path = require('path'); var each = require('async').each; var debug = require('debug')('metalsmith-mtime'); /** * Expose `plugin`. */ module.exports = plugin; /** * A Metalsmith plugin that adds files mtimes to their metadata. * * @return {Function} */ function plugin() { return addAllMtimes; } function addAllMtimes(files, metalsmith, done) { // File system will be accessed for each element so iterate in parallel. each(Object.keys(files), getAddMtime, done); function getAddMtime(file, done) { fs.stat(path.join(metalsmith.source(), file), addMtime); function addMtime(err, stats) { if (err) { // Skip elements of `files` that don't point to existing files. // This can happen if some other Metalsmith plugin does something // strange with `files`. if (err.code === 'ENOENT') { debug('file %s not found', file); return done(); } return done(err); } debug('mtime of file %s is %s', file, stats.mtime); files[file].mtime = stats.mtime; done(); } } }
var fs = require('fs'); var path = require('path'); var each = require('async').each; var debug = require('debug')('metalsmith-mtime'); /** * Expose `plugin`. */ module.exports = plugin; /** * A Metalsmith plugin that adds files mtimes to their metadata. * * @return {Function} */ function plugin() { return addAllMtimes; } function addAllMtimes(files, metalsmith, done) { // File system will be accessed for each element so iterate in parallel. each(Object.keys(files), getAddMtime, done); function getAddMtime(file, done) { fs.stat(path.join(metalsmith.source(), file), addMtime); function addMtime(err, stats) { if (err) { return done(err); } debug('mtime of file %s is %s', file, stats.mtime); files[file].mtime = stats.mtime; done(); } } }
Enable the SmartyPants filter; need to document it later
""" Filters for converting plain text to HTML and enhancing the typographic appeal of text on the Web. """ from django.conf import settings from django.template import Library from template_utils.markup import formatter def apply_markup(value, arg=None): """ Applies text-to-HTML conversion. Takes an optional argument to specify the name of a filter to use. """ if arg is not None: return formatter(value, filter_name=arg) return formatter(value) def smartypants(value): """ Applies SmartyPants to a piece of text, applying typographic niceties. Requires the Python SmartyPants library to be installed; see http://web.chad.org/projects/smartypants.py/ """ try: from smartypants import smartyPants except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in smartypants filter: the Python smartypants module is not installed or could not be imported") return value else: return smartyPants(value) register = Library() register.filter(apply_markup) register.filter(smartypants)
""" Filters for converting plain text to HTML and enhancing the typographic appeal of text on the Web. """ from django.conf import settings from django.template import Library from template_utils.markup import formatter def apply_markup(value, arg=None): """ Applies text-to-HTML conversion. Takes an optional argument to specify the name of a filter to use. """ if arg is not None: return formatter(value, filter_name=arg) return formatter(value) def smartypants(value): """ Applies SmartyPants to a piece of text, applying typographic niceties. Requires the Python SmartyPants library to be installed; see http://web.chad.org/projects/smartypants.py/ """ try: from smartypants import smartyPants except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in smartypants filter: the Python smartypants module is not installed or could not be imported") return value else: return smartyPants(value) register = Library() register.filter(apply_markup)
Adjust pulling tags in CI
#!/usr/bin/env python3 import os import subprocess import semver def tag_to_version(tag): return tag.split('-')[1].lstrip('v') subprocess.check_call('git fetch --tags', shell=True) tags = subprocess.check_output( 'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines() versions = sorted(list(set([tag_to_version(tag) for tag in tags])), key=semver.parse_version_info) versions_to_delete = versions[:-3] cmd_delete_local = 'git tag --delete' cmd_delete_remote = 'git push --delete ' GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN') if GITHUB_TOKEN: cmd_delete_remote += ( 'https://{}@github.com/autozimu/LanguageClient-neovim.git' .format(GITHUB_TOKEN)) else: cmd_delete_remote += 'origin' for tag in tags: if tag_to_version(tag) in versions_to_delete: cmd_delete_local += ' ' + tag cmd_delete_remote += ' ' + tag if not cmd_delete_local.endswith('delete'): subprocess.check_call(cmd_delete_local, shell=True) if not (cmd_delete_remote.endswith('origin') or cmd_delete_remote.endswith('.git')): subprocess.check_call(cmd_delete_remote, shell=True)
#!/usr/bin/env python3 import os import subprocess import semver def tag_to_version(tag): return tag.split('-')[1].lstrip('v') subprocess.check_call('git pull --tags', shell=True) tags = subprocess.check_output( 'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines() versions = sorted(list(set([tag_to_version(tag) for tag in tags])), key=semver.parse_version_info) versions_to_delete = versions[:-3] cmd_delete_local = 'git tag --delete' cmd_delete_remote = 'git push --delete ' GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN') if GITHUB_TOKEN: cmd_delete_remote += ( 'https://{}@github.com/autozimu/LanguageClient-neovim.git' .format(GITHUB_TOKEN)) else: cmd_delete_remote += 'origin' for tag in tags: if tag_to_version(tag) in versions_to_delete: cmd_delete_local += ' ' + tag cmd_delete_remote += ' ' + tag if not cmd_delete_local.endswith('delete'): subprocess.check_call(cmd_delete_local, shell=True) if not (cmd_delete_remote.endswith('origin') or cmd_delete_remote.endswith('.git')): subprocess.check_call(cmd_delete_remote, shell=True)
Update Feed Story page for newPage Summary: Cleans up Feed Story individual page Test Plan: View an individual story by clicking on date. Reviewers: epriestley Reviewed By: epriestley Subscribers: Korvin Differential Revision: https://secure.phabricator.com/D15599
<?php final class PhabricatorFeedDetailController extends PhabricatorFeedController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $story = id(new PhabricatorFeedQuery()) ->setViewer($viewer) ->withChronologicalKeys(array($id)) ->executeOne(); if (!$story) { return new Aphront404Response(); } if ($request->getStr('text')) { $text = $story->renderText(); return id(new AphrontPlainTextResponse())->setContent($text); } $feed = array($story); $builder = new PhabricatorFeedBuilder($feed); $builder->setUser($viewer); $feed_view = $builder->buildView(); $title = pht('Story'); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($title); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($feed_view); } }
<?php final class PhabricatorFeedDetailController extends PhabricatorFeedController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $story = id(new PhabricatorFeedQuery()) ->setViewer($viewer) ->withChronologicalKeys(array($id)) ->executeOne(); if (!$story) { return new Aphront404Response(); } if ($request->getStr('text')) { $text = $story->renderText(); return id(new AphrontPlainTextResponse())->setContent($text); } $feed = array($story); $builder = new PhabricatorFeedBuilder($feed); $builder->setUser($viewer); $feed_view = $builder->buildView(); $title = pht('Story'); $feed_view = phutil_tag_div('phabricator-feed-frame', $feed_view); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($title); return $this->buildApplicationPage( array( $crumbs, $feed_view, ), array( 'title' => $title, )); } }
Fix field editors for names that have dashes
import { camelize } from '@ember/string'; import Ember from 'ember'; export function fieldType(content, fieldName) { if (!content) { return; } let meta; fieldName = camelize(fieldName); try { meta = content.constructor.metaForProperty(fieldName); } catch (err) { return; } // meta.options.fieldType is our convention for annotating // models. meta.type is the name of the transform that ember-data // is using, which we keep as a fallback. let type = meta.options && meta.options.fieldType; if (!type && meta.type) { // lift the default ember-data transform names into our core // types type = `@cardstack/core-types::${meta.type}`; } if (type) { type = stripNamespace(type); } return type; } function stripNamespace(type) { // Right now the actual field editor components get flattened down // out of their namespaces, so we throw away everything but the // last bit of their names here. This problem is easier to solve // once I can integrate a module-unification resolver, so I'm // leaving it like this for now. let parts = type.split(/[/:]/g); return parts[parts.length - 1]; } export default Ember.Helper.helper(fieldType);
import Ember from 'ember'; export function fieldType(content, fieldName) { if (!content) { return; } let meta; try { meta = content.constructor.metaForProperty(fieldName); } catch (err) { return; } // meta.options.fieldType is our convention for annotating // models. meta.type is the name of the transform that ember-data // is using, which we keep as a fallback. let type = meta.options && meta.options.fieldType; if (!type && meta.type) { // lift the default ember-data transform names into our core // types type = `@cardstack/core-types::${meta.type}`; } if (type) { type = stripNamespace(type); } return type; } function stripNamespace(type) { // Right now the actual field editor components get flattened down // out of their namespaces, so we throw away everything but the // last bit of their names here. This problem is easier to solve // once I can integrate a module-unification resolver, so I'm // leaving it like this for now. let parts = type.split(/[/:]/g); return parts[parts.length - 1]; } export default Ember.Helper.helper(fieldType);
Make it work with private messages, add env variables for stuff and refactor.
#!/usr/bin/env node var weechat = require('weechat'), notify = require('osx-notifier'), client; var properties = { server: process.env.SERVER, port: 8001, password: process.env.PASSWORD, ssl: false, nicks: process.env.NICKS.split(',') }; var raiseNotification = function(from, message) { notify({ type: 'info', title: 'WeeChat', subtitle: from, message: message, group: 'WeeChat' }); }; var connect = function() { return weechat.connect(properties.server, properties.port, properties.password, properties.ssl, function() { console.log('Connected.'); }); }; client = connect(); client.on('line', function(line) { var from = weechat.noStyle(line.prefix); var message = weechat.noStyle(line.message); var containsNick = properties.nicks.some(function(nick) { return message.indexOf(nick) !== -1; }); var isPrivate = line.tags_array.indexOf('notify_private') !== -1; var isSelf = from === properties.nick; // Make sure the message is either a highlight or a PM: if ((!isSelf && containsNick) || isPrivate) { raiseNotification(from, message); } });
var properties = { server: '', port: 9000, password: '', ssl: false, nick: '' }; var weechat = require('weechat'); var notify = require('osx-notifier'); var raise_notification = function(from, message) { notify({ type: 'info', title: 'Weechat', subtitle: from, message: message, group: 'Weechat' }); }; var client = weechat.connect(properties.server, properties.port, properties.password, properties.ssl, function() { client.on('error', function(err) { console.error(err); }); client.on('end', function() { console.log('end'); }); client.on('line', function(line) { console.log(line); var from = weechat.noStyle(line.prefix); var message = weechat.noStyle(line.message); if (message.indexOf(properties.nick) >= 0 && from.indexOf(properties.nick) == -1){ raise_notification(from, message); } }); });
Test that Node is a function before using instanceof on it
/** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && ( typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string' )); } module.exports = isNode;
/** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && ( typeof Node !== 'undefined' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string' )); } module.exports = isNode;
Add utility to spy events
package org.realityforge.arez.gwt.examples; import elemental2.dom.DomGlobal; import javax.annotation.Nonnull; import org.realityforge.arez.Arez; import org.realityforge.arez.ArezContext; import org.realityforge.arez.extras.WhyRun; final class ExampleUtil { private ExampleUtil() { } static void spyEvents() { Arez.context().getSpy().addSpyEventHandler( SpyUtil::emitEvent ); } static void whyRun() { DomGlobal.console.log( new WhyRun( Arez.context().getSpy() ).whyRun() ); } static void logAllErrors( @Nonnull final ArezContext context ) { context.addObserverErrorHandler( ( observer, error, throwable ) -> { DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer ); if ( null != throwable ) { DomGlobal.console.log( throwable ); } } ); } }
package org.realityforge.arez.gwt.examples; import elemental2.dom.DomGlobal; import javax.annotation.Nonnull; import org.realityforge.arez.Arez; import org.realityforge.arez.ArezContext; import org.realityforge.arez.extras.WhyRun; final class ExampleUtil { private ExampleUtil() { } static void whyRun() { DomGlobal.console.log( new WhyRun( Arez.context().getSpy() ).whyRun() ); } static void logAllErrors( @Nonnull final ArezContext context ) { context.addObserverErrorHandler( ( observer, error, throwable ) -> { DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer ); if ( null != throwable ) { DomGlobal.console.log( throwable ); } } ); } }
Switch to PhantomJS for Karma tests since we no longer use HTML5 form validation [closes #47]
module.exports = function(config) { config.set({ files: [ 'node_modules/angular/angular.min.js', 'node_modules/angular-mocks/angular-mocks.js', 'webapp/main/treeline.module.js', 'webapp/main/**/*.js', 'webapp/main/**/*.html', 'webapp/test/**/*.js' ], singleRun: true, frameworks: ['jasmine-jquery', 'jasmine'], browsers: ['PhantomJS'], plugins: [ 'karma-chrome-launcher', 'karma-jasmine', 'karma-jasmine-jquery', 'karma-ng-html2js-preprocessor', 'karma-phantomjs-launcher' ], preprocessors: { 'webapp/main/**/*.html': ['ng-html2js'] }, ngHtml2JsPreprocessor: { moduleName: 'templates', stripPrefix: 'webapp/main/', prependPrefix: 'templates/' }, reporters: ['progress'] }) }
module.exports = function(config) { config.set({ files: [ 'node_modules/angular/angular.min.js', 'node_modules/angular-mocks/angular-mocks.js', 'webapp/main/treeline.module.js', 'webapp/main/**/*.js', 'webapp/main/**/*.html', 'webapp/test/**/*.js' ], singleRun: true, frameworks: ['jasmine-jquery', 'jasmine'], browsers: ['Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-jasmine', 'karma-jasmine-jquery', 'karma-ng-html2js-preprocessor', 'karma-phantomjs-launcher' ], preprocessors: { 'webapp/main/**/*.html': ['ng-html2js'] }, ngHtml2JsPreprocessor: { moduleName: 'templates', stripPrefix: 'webapp/main/', prependPrefix: 'templates/' }, reporters: ['progress'] }) }
Make this a bit more readable.
__name__ = "Year View" __author__ = "Decklin Foster <decklin@red-bean.com>" __description__ = "Calendar of all dates in a given year." import time def make(instance, entries, all, vars): # we get all the entries for this year in ``entries``, in here we want to # build some monthly calendars to pass to the next bit cal = {} for e in entries: m = time.strftime('%m', e.date) d = time.strftime('%d', e.date) cal.setdefault(m, {}) cal[m].setdefault(d, 0) cal[m][d] += 1 months = [muse.expand('calendar', y=instance, m=month, days=days, **vars) for month, days in cal.items()] sidebar = muse.expand('sidebar', entries=entries, all=all, **vars) footer = 'Footer' pagetitle = 'Year %s - %s' % (instance, vars['blogtitle']) return muse.expand('page', layout=__name__, body="\n".join(months), pagetitle=pagetitle, sidebar=sidebar, footer=footer, **vars)
__name__ = "Year View" __author__ = "Decklin Foster <decklin@red-bean.com>" __description__ = "Calendar of all dates in a given year." import time def make(instance, entries, all, vars): # we get all the entries for this year in ``entries``, in here we want to # build some monthly calendars to pass to the next bit cal = {} for e in entries: m = time.strftime('%m', e.date) d = time.strftime('%d', e.date) cal.setdefault(m, {}) cal[m].setdefault(d, 0) cal[m][d] += 1 months = [muse.expand('calendar', m=m, days=d, **vars) for m, d in cal.items()] sidebar = muse.expand('sidebar', entries=entries, all=all, **vars) footer = 'Footer' pagetitle = 'Year %s - %s' % (instance, vars['blogtitle']) return muse.expand('page', layout=__name__, body="\n".join(months), pagetitle=pagetitle, sidebar=sidebar, footer=footer, **vars)
Use raw PathInfo for matching urls
<?php /** * ownCloud * * @author Frank Karlitschek * @copyright 2012 Frank Karlitschek frank@owncloud.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ require_once('../lib/base.php'); use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Exception\MethodNotAllowedException; try { OC::getRouter()->match('/ocs'.OC_Request::getRawPathInfo()); } catch (ResourceNotFoundException $e) { OC_OCS::notFound(); } catch (MethodNotAllowedException $e) { OC_Response::setStatus(405); }
<?php /** * ownCloud * * @author Frank Karlitschek * @copyright 2012 Frank Karlitschek frank@owncloud.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ require_once('../lib/base.php'); use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Exception\MethodNotAllowedException; try { OC::getRouter()->match('/ocs'.$_SERVER['PATH_INFO']); } catch (ResourceNotFoundException $e) { OC_OCS::notFound(); } catch (MethodNotAllowedException $e) { OC_Response::setStatus(405); }
Fix Bug Liens du menus configuration ne se mettent pas en actif
define([ 'app', ], function(app){ /****************************************** * Header View */ var HeaderView = Backbone.View.extend({ el : '#header-navbar', templateHTML : 'header', // The DOM events // events: { 'click li.disabled' : 'preventDefault' }, /** View Initialization */ initialize: function () { this.render(); }, /** Display the view */ render: function(){ var self = this; var currentModule = _(Backbone.history.fragment).strLeft('/'); var currentUrl = _(_(Backbone.history.fragment).strRight('/')).strLeft('/'); if(currentUrl == app.config.menus.openbase){ currentUrl = _(_(_(Backbone.history.fragment).strRight('/')).strRight('/')).strLeft('/'); } $.get("templates/" + this.templateHTML + ".html", function(templateData) { var template = _.template(templateData, { lang : app.lang, user : app.models.user, menusToLoad : app.config.menus, currentModule: currentModule, currentUrl : currentUrl }); $(self.el).html(template); }); }, preventDefault: function(event){ event.preventDefault(); }, }); return HeaderView; });
define([ 'app', ], function(app){ /****************************************** * Header View */ var HeaderView = Backbone.View.extend({ el : '#header-navbar', templateHTML : 'header', // The DOM events // events: { 'click li.disabled' : 'preventDefault' }, /** View Initialization */ initialize: function () { this.render(); }, /** Display the view */ render: function(){ var self = this; $.get("templates/" + this.templateHTML + ".html", function(templateData) { var template = _.template(templateData, { lang : app.lang, user : app.models.user, menusToLoad : app.config.menus, currentModule: _(Backbone.history.fragment).strLeft('/'), currentUrl : _(_(Backbone.history.fragment).strRight('/')).strLeft('/') }); $(self.el).html(template); }); }, preventDefault: function(event){ event.preventDefault(); }, }); return HeaderView; });
Change variable name in hook injector
<?php namespace Gitonomy\Bundle\CoreBundle\Git; use Gitonomy\Bundle\CoreBundle\EventDispatcher\Event\ProjectCreateEvent; use Gitonomy\Bundle\CoreBundle\Git\RepositoryPool; class HookInjector { protected $hooks; /** * @var Gitonomy\Bundle\CoreBundle\Git\RepositoryPool */ protected $repositoryPool; public function __construct(RepositoryPool $repositoryPool, array $hooks) { $this->hooks = $hooks; $this->repositoryPool = $repositoryPool; } public function onProjectCreate(ProjectCreateEvent $event) { $repository = $this->repositoryPool->getGitRepository($event->getProject()); $hooks = $repository->getHooks(); foreach ($this->hooks as $name => $file) { $hooks->setSymlink($name, $file); } } }
<?php namespace Gitonomy\Bundle\CoreBundle\Git; use Gitonomy\Bundle\CoreBundle\EventDispatcher\Event\ProjectCreateEvent; use Gitonomy\Bundle\CoreBundle\Git\RepositoryPool; class HookInjector { protected $hooks; /** * @var Gitonomy\Bundle\CoreBundle\Git\RepositoryPool */ protected $repositoryPool; public function __construct(RepositoryPool $repositoryPool, array $hooks) { $this->hooks = $hooks; $this->repositoryPool = $repositoryPool; } public function onProjectCreate(ProjectCreateEvent $event) { $repository = $this->repositoryPool->getGitRepository($event->getProject()); $hooks = $repository->getHooks(); foreach ($this->hooks as $name => $content) { $hooks->setSymlink($name, $content); } } }
Fix issues with capturing stdout and error messages for the runner.
package main import ( "fmt" "io" "log" "os" "os/exec" "time" ) func runner(what string) { f, err := os.OpenFile("testlogfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic("NOOOOO") } defer f.Close() log.SetOutput(f) log.Println("### Starting:") defer log.Println("### Done:") cmd := exec.Command(what) output := io.MultiWriter(f, os.Stdout) cmd.Stdout = output cmd.Stderr = output err = cmd.Run() if err != nil { fmt.Fprintln(output, "Error running: ", what) fmt.Fprintln(output, err) } } func main() { runner("speedtest-cli") period := 10 * time.Minute for _ = range time.Tick(period) { runner("speedtest-cli") } }
package main import ( "io" "log" "os" "os/exec" "time" ) func runner(what string) { f, err := os.OpenFile("testlogfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic("NOOOOO") } defer f.Close() log.SetOutput(f) log.Println("### Starting:") cmd := exec.Command(what) cmd.Stdout = io.MultiWriter(f, os.Stdout) cmd.Stderr = os.Stderr cmd.Run() log.Println("### Done:") } func main() { runner("speedtest-cli") period := 10 * time.Minute for _ = range time.Tick(period) { runner("speedtest-cli") } }
Convert rendered html to unicode before substring matching
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.tests.test_website import set_request from frappe.website.render import render class TestBlogPost(unittest.TestCase): def test_generator_view(self): pages = frappe.get_all('Blog Post', fields=['name', 'route'], filters={'published': 1, 'route': ('!=', '')}, limit =1) set_request(path=pages[0].route) response = render() self.assertTrue(response.status_code, 200) html = response.get_data().decode() self.assertTrue('<article class="blog-content" itemscope itemtype="http://schema.org/BlogPosting">' in html) def test_generator_not_found(self): pages = frappe.get_all('Blog Post', fields=['name', 'route'], filters={'published': 0}, limit =1) frappe.db.set_value('Blog Post', pages[0].name, 'route', 'test-route-000') set_request(path='test-route-000') response = render() self.assertTrue(response.status_code, 404)
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.tests.test_website import set_request from frappe.website.render import render class TestBlogPost(unittest.TestCase): def test_generator_view(self): pages = frappe.get_all('Blog Post', fields=['name', 'route'], filters={'published': 1, 'route': ('!=', '')}, limit =1) set_request(path=pages[0].route) response = render() self.assertTrue(response.status_code, 200) html = response.get_data() self.assertTrue('<article class="blog-content" itemscope itemtype="http://schema.org/BlogPosting">' in html) def test_generator_not_found(self): pages = frappe.get_all('Blog Post', fields=['name', 'route'], filters={'published': 0}, limit =1) frappe.db.set_value('Blog Post', pages[0].name, 'route', 'test-route-000') set_request(path='test-route-000') response = render() self.assertTrue(response.status_code, 404)
Add missing `var`s in animation code JavaScript isn't CoffeeScript!
var updateClock = (function() { var sDial = document.getElementById("secondDial"); var mDial = document.getElementById("minuteDial"); var hDial = document.getElementById("hourDial"); function moveDials(hours, minutes, seconds) { var hDeg = (360 / 12) * (hours + minutes/60); var mDeg = (360 / 60) * minutes; var sDeg = (360 / 60) * seconds; sDial.setAttribute("transform", "rotate("+sDeg+")"); mDial.setAttribute("transform", "rotate("+mDeg+")"); hDial.setAttribute("transform", "rotate("+hDeg+")"); } function update() { var currentTime = new Date(); moveDials(currentTime.getHours(), currentTime.getMinutes(), currentTime.getSeconds()); }; return update; })(); // update every 50ms, just to be sure setInterval(updateClock, 50);
var updateClock = (function() { var sDial = document.getElementById("secondDial"); var mDial = document.getElementById("minuteDial"); var hDial = document.getElementById("hourDial"); function moveDials(hours, minutes, seconds) { hDeg = (360 / 12) * (hours + minutes/60); mDeg = (360 / 60) * minutes; sDeg = (360 / 60) * seconds; sDial.setAttribute("transform", "rotate("+sDeg+")"); mDial.setAttribute("transform", "rotate("+mDeg+")"); hDial.setAttribute("transform", "rotate("+hDeg+")"); } function update() { var currentTime = new Date(); moveDials(currentTime.getHours(), currentTime.getMinutes(), currentTime.getSeconds()); }; return update; })(); // update every 50ms, just to be sure setInterval(updateClock, 50);
Allow to set maxReviewers on a project from the WebUI Change-Id: I8c3d9d7659b935652004fad29c22b23a6326d2d0 Signed-off-by: Edwin Kempin <b444e279ad95fdef4fbdd82c813b624595df204a@sap.com>
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.reviewersbyblame; import com.google.gerrit.common.ChangeListener; import com.google.gerrit.extensions.annotations.Exports; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.server.config.FactoryModule; import com.google.gerrit.server.config.ProjectConfigEntry; public class ReviewersByBlameModule extends FactoryModule { @Override protected void configure() { DynamicSet.bind(binder(), ChangeListener.class).to( ChangeUpdatedListener.class); factory(ReviewersByBlame.Factory.class); bind(ProjectConfigEntry.class) .annotatedWith(Exports.named("maxReviewers")) .toInstance(new ProjectConfigEntry("Max Reviewers", 3, true, "The maximum number of reviewers that should be automatically added" + " to a change based on the git blame computation on the changed files.")); } }
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.reviewersbyblame; import com.google.gerrit.common.ChangeListener; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.server.config.FactoryModule; public class ReviewersByBlameModule extends FactoryModule { @Override protected void configure() { DynamicSet.bind(binder(), ChangeListener.class).to( ChangeUpdatedListener.class); factory(ReviewersByBlame.Factory.class); } }
Use readable job status code
<?php class DeleteJobAction extends ApiActionBase { protected static $required_privileges = array(Auth::PROCESS_MANAGE); protected static $rules = array( 'jobID' => array('type' => 'int', 'required' => true) ); protected function execute($params) { $pdo = DBConnector::getConnection(); $pdo->beginTransaction(); CadResult::lock(); Job::lock(); $target = new Job($params['jobID']); if (!isset($target->job_id)) throw new ApiOperationException('Target job not found (may be already deleted).'); if ($target->status == Job::JOB_NOT_ALLOCATED || $target->status == Job::JOB_ALLOCATED) { Job::delete($target->job_id); CadResult::delete($target->job_id); } else if($target->status == Job::JOB_PROCESSING) { Job::abortJob($target->job_id); } else { $pdo->rollback(); throw new ApiOperationException( 'The target job can not be deleted (status: ' . Job::codeToStatusName($target->status) . ')' ); } $pdo->commit(); return null; } }
<?php class DeleteJobAction extends ApiActionBase { protected static $required_privileges = array(Auth::PROCESS_MANAGE); protected static $rules = array( 'jobID' => array('type' => 'int', 'required' => true) ); protected function execute($params) { $pdo = DBConnector::getConnection(); $pdo->beginTransaction(); CadResult::lock(); Job::lock(); $target = new Job($params['jobID']); if (!isset($target->job_id)) throw new ApiOperationException('Target job not found (may be already deleted).'); if ($target->status == Job::JOB_NOT_ALLOCATED || $target->status == Job::JOB_ALLOCATED) { Job::delete($target->job_id); CadResult::delete($target->job_id); } else if($target->status == Job::JOB_PROCESSING) { Job::abortJob($target->job_id); } else { throw new ApiOperationException( 'The target job can not be deleted (status: ' . $target->status . ')'); } $pdo->commit(); return null; } }
Fix typo in description of config item
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Splatalogue Catalog Query Tool ----------------------------------- :Author: Adam Ginsburg (adam.g.ginsburg@gmail.com) :Originally contributed by: Magnus Vilhelm Persson (magnusp@vilhelm.nu) """ from astropy import config as _config class Conf(_config.ConfigNamespace): """ Configuration parameters for `astroquery.splatalogue`. """ slap_url = _config.ConfigItem( 'http://find.nrao.edu/splata-slap/slap', 'Splatalogue SLAP interface URL (not used).') query_url = _config.ConfigItem( 'http://www.cv.nrao.edu/php/splat/c_export.php', 'Splatalogue web interface URL.') timeout = _config.ConfigItem( 60, 'Time limit for connecting to Splatalogue server.') lines_limit = _config.ConfigItem( 1000, 'Limit to number of lines exported.') conf = Conf() from . import load_species_table from . import utils from .core import Splatalogue, SplatalogueClass __all__ = ['Splatalogue', 'SplatalogueClass', 'Conf', 'conf', ]
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Splatalogue Catalog Query Tool ----------------------------------- :Author: Adam Ginsburg (adam.g.ginsburg@gmail.com) :Originally contributed by: Magnus Vilhelm Persson (magnusp@vilhelm.nu) """ from astropy import config as _config class Conf(_config.ConfigNamespace): """ Configuration parameters for `astroquery.splatalogue`. """ slap_url = _config.ConfigItem( 'http://find.nrao.edu/splata-slap/slap', 'Splatalogue SLAP interface URL (not used).') query_url = _config.ConfigItem( 'http://www.cv.nrao.edu/php/splat/c_export.php', 'SSplatalogue web interface URL.') timeout = _config.ConfigItem( 60, 'Time limit for connecting to Splatalogue server.') lines_limit = _config.ConfigItem( 1000, 'Limit to number of lines exported.') conf = Conf() from . import load_species_table from . import utils from .core import Splatalogue, SplatalogueClass __all__ = ['Splatalogue', 'SplatalogueClass', 'Conf', 'conf', ]
Increase max buffer to 1MB
var childProcess = require('child_process'); // Exit the process if the command failed and only call the callback if the // command succeed, output of the command would also be piped. exports.safeExec = function(command, options, callback) { if (!callback) { callback = options; options = {}; } if (!options) options = {}; // This needed to be increase for `apm test` runs that generate tons of failures // The default is 200KB. options.maxBuffer = 1024 * 1024; var child = childProcess.exec(command, options, function(error, stdout, stderr) { if (error) process.exit(error.code || 1); else callback(null); }); child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout); } // Same with safeExec but call child_process.spawn instead. exports.safeSpawn = function(command, args, options, callback) { if (!callback) { callback = options; options = {}; } var child = childProcess.spawn(command, args, options); child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout); child.on('exit', function(code) { if (code != 0) process.exit(code); else callback(null); }); }
var childProcess = require('child_process'); // Exit the process if the command failed and only call the callback if the // command succeed, output of the command would also be piped. exports.safeExec = function(command, options, callback) { if (!callback) { callback = options; options = {}; } var child = childProcess.exec(command, options, function(error, stdout, stderr) { if (error) process.exit(error.code || 1); else callback(null); }); child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout); } // Same with safeExec but call child_process.spawn instead. exports.safeSpawn = function(command, args, options, callback) { if (!callback) { callback = options; options = {}; } var child = childProcess.spawn(command, args, options); child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout); child.on('exit', function(code) { if (code != 0) process.exit(code); else callback(null); }); }
JasonLeyba: Make a test case insensitive. git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@11860 07704840-8298-11de-bf8c-fd130f914ac9
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class TagNameTest extends AbstractDriverTestCase { @Test public void shouldReturnInput() { driver.get(pages.formPage); WebElement selectBox = driver.findElement(By.id("cheese")); assertThat(selectBox.getTagName().toLowerCase(), is("input")); } }
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class TagNameTest extends AbstractDriverTestCase { @Test public void shouldReturnInput() { driver.get(pages.formPage); WebElement selectBox = driver.findElement(By.id("cheese")); assertThat(selectBox.getTagName(), is("input")); } }
Fix float problem on episode page
<div class="torrent_file"> <!-- <?php echo $torrent->getFile(), '(', $torrent->getMimeType(), ') ', pretty_size($torrent->getSize()) ?> --> <?php echo $torrent->getFeed()->getTitle(); ?> <ul class="links"> <div class="divider">&nbsp;</div> <li> <span>Web </span> <?php echo link_to($torrent->getUrl(false),$torrent->getUrl(false)); ?> </li> <li> <span>Torrent </span> <?php echo link_to($torrent->getUrl(true),$torrent->getUrl(true)) ?> </li> <li class="clearfix"> <span>Magnet </span> <?php echo '<a href="',$torrent->getMagnet(),'">',$torrent->getFileSha1(),'</a>'; ?> </li> </ul> <?php if(@$delete): ?><?php echo delete_form_for_object($torrent); ?><?php endif; ?> </div>
<div class="torrent_file"> <!-- <?php echo $torrent->getFile(), '(', $torrent->getMimeType(), ') ', pretty_size($torrent->getSize()) ?> --> <?php echo $torrent->getFeed()->getTitle(); ?> <ul class="links"> <div class="divider">&nbsp;</div> <li> <span>Web </span> <?php echo link_to($torrent->getUrl(false),$torrent->getUrl(false)); ?> </li> <li> <span>Torrent </span> <?php echo link_to($torrent->getUrl(true),$torrent->getUrl(true)) ?> </li> <li> <span>Magnet </span> <?php echo '<a href="',$torrent->getMagnet(),'">',$torrent->getFileSha1(),'</a>'; ?> </li> </ul> <?php if(@$delete): ?><?php echo delete_form_for_object($torrent); ?><?php endif; ?> </div>
Add test for the historic endpoint
describe('traffic', function() { beforeEach(function() { window.matrix.settings = { profileId: '' }; subject = window.matrix.traffic; }); it('has initial points', function() { expect(subject.points).to.eq(720); }); it('has empty counts', function() { expect(subject.counts).to.eql([]); }); it('has interval of 2 minutes', function() { expect(subject.interval).to.eq(120000); }); describe('#endpoint', function() { it('returns the path to the servers realtime endpoint', function() { expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:activeUsers&max-results=10'); }); context('with profileId', function() { beforeEach(function() { window.matrix.settings = { profileId: 'Test' }; }); it('returns correct profile Id in the endpoint path', function() { expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:activeUsers&max-results=10'); }); }); }); describe('#historic', function() { it('returns the path to the servers historic endpoint', function() { expect(subject.historic()).to.eql('/historic?ids=ga:&dimensions=ga%3AnthMinute&metrics=ga%3Asessions&start-date=2015-08-03&end-date=2015-08-04&max-results=1000'); }); }); });
describe('traffic', function() { beforeEach(function() { window.matrix.settings = { profileId: '' }; subject = window.matrix.traffic; }); it('has initial points', function() { expect(subject.points).to.eq(720); }); it('has empty counts', function() { expect(subject.counts).to.eql([]); }); it('has interval of 2 minutes', function() { expect(subject.interval).to.eq(120000); }); describe('#endpoint', function() { it('returns the path to the servers realtime endpoint', function() { expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:activeUsers&max-results=10'); }); context('with profileId', function() { beforeEach(function() { window.matrix.settings = { profileId: 'Test' }; }); it('returns correct profile Id in the endpoint path', function() { expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:activeUsers&max-results=10'); }); }); }); });
Remove `return`, get Ziggs instead of Renekton, since we're saving as Ziggs
import cassiopeia as cass from cassiopeia.core import Champion def test_cass(): #annie = Champion(name="Annie", region="NA") annie = Champion(name="Annie") print(annie.name) print(annie.title) print(annie.title) for spell in annie.spells: print(spell.name, spell.keywords) print(annie.info.difficulty) print(annie.passive.name) #print(annie.recommended_itemsets[0].item_sets[0].items) print(annie.free_to_play) print(annie._Ghost__all_loaded) print(annie) print() #ziggs = cass.get_champion(region="NA", "Ziggs") ziggs = cass.get_champion("Ziggs") print(ziggs.name) print(ziggs.region) #print(ziggs.recommended_itemset[0].item_sets[0].items) print(ziggs.free_to_play) for spell in ziggs.spells: for var in spell.variables: print(spell.name, var) print(ziggs._Ghost__all_loaded) if __name__ == "__main__": test_cass()
import cassiopeia as cass from cassiopeia.core import Champion def test_cass(): #annie = Champion(name="Annie", region="NA") annie = Champion(name="Annie") print(annie.name) print(annie.title) print(annie.title) for spell in annie.spells: print(spell.name, spell.keywords) print(annie.info.difficulty) print(annie.passive.name) #print(annie.recommended_itemsets[0].item_sets[0].items) print(annie.free_to_play) print(annie._Ghost__all_loaded) print(annie) return print() #ziggs = cass.get_champion(region="NA", "Ziggs") ziggs = cass.get_champion("Renekton") print(ziggs.name) print(ziggs.region) #print(ziggs.recommended_itemset[0].item_sets[0].items) print(ziggs.free_to_play) for spell in ziggs.spells: for var in spell.variables: print(spell.name, var) print(ziggs._Ghost__all_loaded) if __name__ == "__main__": test_cass()
Move update notifier to bin
#! /usr/bin/env node 'use strict'; var chalk = require('chalk'), pkg = require('../package.json'); var nodeVersion = process.version.replace('v',''), nodeVersionRequired = pkg.engines.node.replace('>=',''); // check node version compatibility if(nodeVersion <= nodeVersionRequired){ console.log(); console.error(chalk.red.bold('✗ '), chalk.red.bold('NODE ' + process.version + ' was detected. Siteshooter requires node version ' + pkg.engines.node)); console.log(); process.exit(1); } else{ // check for new version of Siteshooter var updater = require('update-notifier'); updater({pkg: pkg}).notify({defer: true}); } var siteshooter = require('../index'), args = [].slice.call(process.argv, 2); var exitCode = 0, isDebug = args.indexOf('--debug') !== -1; siteshooter.cli(args).then(function() { if (isDebug) { console.log('CLI promise complete'); } process.exit(exitCode); }).catch(function(err) { exitCode = 1; if (!isDebug) { console.error(err.stack); } process.exit(exitCode); }); process.on('exit', function() { if (isDebug) { console.log('EXIT', arguments); } process.exit(exitCode); });
#! /usr/bin/env node 'use strict'; var chalk = require('chalk'), pkg = require('../package.json'); var nodeVersion = process.version.replace('v',''), nodeVersionRequired = pkg.engines.node.replace('>=',''); // check node version compatibility if(nodeVersion <= nodeVersionRequired){ console.log(); console.error(chalk.red.bold('✗ '), chalk.red.bold('Siteshooter requires node version ' + pkg.engines.node)); console.log(); process.exit(1); } var siteshooter = require('../index'), args = [].slice.call(process.argv, 2); var exitCode = 0, isDebug = args.indexOf('--debug') !== -1; siteshooter.cli(args).then(function() { if (isDebug) { console.log('CLI promise complete'); } process.exit(exitCode); }).catch(function(err) { exitCode = 1; if (!isDebug) { console.error(err.stack); } process.exit(exitCode); }); process.on('exit', function() { if (isDebug) { console.log('EXIT', arguments); } process.exit(exitCode); });
Fix inefficient use of run.once by EmberEnvironment.async
import Ember from 'ember'; import { defer } from 'rsvp'; import { Environment } from './external/environment'; import { assert } from '@ember/debug'; import { join, next, schedule } from '@ember/runloop'; export class EmberEnvironment extends Environment { assert(...args) { assert(...args); } async(callback) { join(() => schedule('actions', callback)); } reportUncaughtRejection(error) { next(null, function () { if (Ember.onerror) { Ember.onerror(error); } else { throw error; } }); } defer() { return defer(); } globalDebuggingEnabled() { return Ember.ENV.DEBUG_TASKS; } } export const EMBER_ENVIRONMENT = new EmberEnvironment();
import Ember from 'ember'; import { defer } from 'rsvp'; import { Environment } from './external/environment'; import { assert } from '@ember/debug'; import { join, next, once } from '@ember/runloop'; export class EmberEnvironment extends Environment { assert(...args) { assert(...args); } async(callback) { join(() => once(null, callback)); } reportUncaughtRejection(error) { next(null, function () { if (Ember.onerror) { Ember.onerror(error); } else { throw error; } }); } defer() { return defer(); } globalDebuggingEnabled() { return Ember.ENV.DEBUG_TASKS; } } export const EMBER_ENVIRONMENT = new EmberEnvironment();
Return profile from get_profile view instead of user
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from linked_accounts import LINKED_ACCOUNTS_HANDLERS HANDLERS = getattr( settings, 'LINKED_ACCOUNTS_HANDLERS', LINKED_ACCOUNTS_HANDLERS ) def get_profile(service=None, token=None): handler_module = dict(HANDLERS).get(service, None) if handler_module: module, handler = handler_module.rsplit('.', 1) handler_class = getattr(import_module(module), handler) handler = handler_class() profile = handler.get_profile(token) return profile else: raise ImproperlyConfigured('No handler for service %s' % service)
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from linked_accounts import LINKED_ACCOUNTS_HANDLERS HANDLERS = getattr( settings, 'LINKED_ACCOUNTS_HANDLERS', LINKED_ACCOUNTS_HANDLERS ) def get_profile(service=None, token=None): handler_module = dict(HANDLERS).get(service, None) if handler_module: module, handler = handler_module.rsplit('.', 1) handler_class = getattr(import_module(module), handler) handler = handler_class() profile = handler.get_profile(token) return profile.user else: raise ImproperlyConfigured('No handler for service %s' % service)
Fix loop to delete branches from xml.
"""IEEE Xplore API Request. Usage: IEEE/main.py -h [-au AUTHOR] [-ti TITLE] [-ab ABSTRACT] [-py YEAR] [-hc NUMBER] Options: -h --help show this -au AUTHOR Terms to search for in Author [default: ""] -ti TITLE Terms to search for in Title [default: ""] -ab ABSTRACT Terms to search for in the Abstract [default: ""] -py YEAR Terms to search for in Year [default: ""] -hc NUMBER Number of records to fetch. [default: 25] """ from scraping.tools import * from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__, version='IEEE Xplore API Request') parameters = [arguments['-au'], arguments['-ti'], arguments['-ab'], arguments['-py'], arguments['-hc']] standard = 'http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?' url = create_url_search(parameters=parameters, standard=standard) root = fetch_xml(url) parents = root.getchildren() for _ in range(2): parents.remove(parents[0]) for document in parents: article = xml_to_dict(document) post = iee_to_axelbib(article) send = post_to_axelbib(post)
"""IEEE Xplore API Request. Usage: IEEE/main.py -h [-au AUTHOR] [-ti TITLE] [-ab ABSTRACT] [-py YEAR] [-hc NUMBER] Options: -h --help show this -au AUTHOR Terms to search for in Author [default: ""] -ti TITLE Terms to search for in Title [default: ""] -ab ABSTRACT Terms to search for in the Abstract [default: ""] -py YEAR Terms to search for in Year [default: ""] -hc NUMBER Number of records to fetch. [default: 25] """ from scraping.tools import * from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__, version='IEEE Xplore API Request') parameters = [arguments['-au'], arguments['-ti'], arguments['-ab'], arguments['-py'], arguments['-hc']] standard = 'http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?' url = create_url_search(parameters=parameters, standard=standard) root = fetch_xml(url) parents = root.getchildren() [parents.remove(parents[0]) for _ in range(2)] for document in parents: article = xml_to_dict(document) post = iee_to_axelbib(article) send = post_to_axelbib(post)
Fix get_credentials so it returns a dict.
# -*- coding: utf-8 -*- # # © 2011 SimpleGeo, Inc. All rights reserved. # Author: Paul Lathrop <paul@simplegeo.com> # """Utility functions for AWS-related tasks.""" from getpass import getpass import boto.pyami.config as boto_config def get_credentials(batch=False): """Return a dictionary of AWS credentials. Credentials are loaded via boto first (which checks the environment and a couple well-known files). If boto cannot find any credentials, and the 'batch' kwarg is set to False, this method will request credentials from the user interactively via the console.""" config = boto_config.Config() key = config.get('Credentials', 'aws_access_key_id', False) secret = config.get('Credentials', 'aws_secret_access_key', False) if key and secret: return {'aws_access_key_id': key, 'aws_secret_access_key': secret} if batch: return None return prompt_for_credentials() def prompt_for_credentials(): """Prompt the user to enter their AWS credentials, and return them as a dictionary.""" print 'Could not load AWS credentials from environment or boto configuration.' print 'Please enter your AWS credentials.' print key = raw_input('AWS Access Key ID: ') secret = getpass('AWS Secret Access Key: ') return {'aws_access_key_id': key, 'aws_secret_access_key': secret}
# -*- coding: utf-8 -*- # # © 2011 SimpleGeo, Inc. All rights reserved. # Author: Paul Lathrop <paul@simplegeo.com> # """Utility functions for AWS-related tasks.""" from getpass import getpass import boto.pyami.config as boto_config def get_credentials(batch=False): """Return a tuple (key, secret) of AWS credentials. Credentials are loaded via boto first (which checks the environment and a couple well-known files). If boto cannot find any credentials, and the 'batch' kwarg is set to False, this method will request credentials from the user interactively via the console.""" config = boto_config.Config() key = config.get('Credentials', 'aws_access_key_id', False) secret = config.get('Credentials', 'aws_secret_access_key', False) if key and secret: return (key, secret) if batch: return None return prompt_for_credentials() def prompt_for_credentials(): """Prompt the user to enter their AWS credentials, and return them as a tuple of (key, secret).""" print 'Could not load AWS credentials from environment or boto configuration.' print 'Please enter your AWS credentials.' print key = raw_input('AWS Access Key ID: ') secret = getpass('AWS Secret Access Key: ') return (key, secret)
Make TraceID a string in response, so it can be truly omitted
package controller import ( "fmt" "net/http" "github.com/rs/xid" ) // RequestID is the unique Request ID for each request type TraceID struct { xid.ID } // StandardResponseFields is meant to be included in all response bodies // and includes "standard" response fields type StandardResponseFields struct { Path string `json:"path,omitempty"` TraceID string `json:"trace_id,omitempty"` } // NewTraceID is an initializer for TraceID func NewTraceID(id xid.ID) TraceID { return TraceID{ID: id} } // NewMockTraceID is an initializer for TraceID which returns a // static "mocked" func NewMockTraceID() TraceID { x, err := xid.FromString("bpa182jipt3b2b78879g") if err != nil { fmt.Println(err) } return TraceID{ID: x} } // NewStandardResponseFields is an initializer for the StandardResponseFields struct func NewStandardResponseFields(id TraceID, r *http.Request) StandardResponseFields { var sr StandardResponseFields sr.TraceID = id.String() sr.Path = r.URL.EscapedPath() return sr }
package controller import ( "fmt" "net/http" "github.com/rs/xid" ) // RequestID is the unique Request ID for each request type TraceID struct { xid.ID } // StandardResponseFields is meant to be included in all response bodies // and includes "standard" response fields type StandardResponseFields struct { Path string `json:"path,omitempty"` TraceID TraceID `json:"trace_id,omitempty"` } // NewTraceID is an initializer for TraceID func NewTraceID(id xid.ID) TraceID { return TraceID{ID: id} } // NewMockTraceID is an initializer for TraceID which returns a // static "mocked" func NewMockTraceID() TraceID { x, err := xid.FromString("bpa182jipt3b2b78879g") if err != nil { fmt.Println(err) } return TraceID{ID: x} } // NewStandardResponseFields is an initializer for the StandardResponseFields struct func NewStandardResponseFields(id TraceID, r *http.Request) StandardResponseFields { var sr StandardResponseFields sr.TraceID = id sr.Path = r.URL.EscapedPath() return sr }
Handle the TERM signal like the INT signal
<?php namespace Emphloyer; /** * Cli is the class used by the command line runner to execute input commands. */ class Cli { protected $lastSignal; protected $pipeline; protected $numberOfEmployees = 0; /** * Configure with PHP code from a file. */ public function configure($filename) { require $filename; $this->numberOfEmployees = $numberOfEmployees; $this->pipeline = new Pipeline($pipelineBackend); } /** * Run jobs. */ public function run() { $this->workshop = new Workshop(new Boss($this->pipeline), $this->numberOfEmployees); declare(ticks = 100); pcntl_signal(\SIGINT, array($this, 'handleSignal')); pcntl_signal(\SIGTERM, array($this, 'handleSignal')); $this->workshop->run(); } /** * Clear all jobs from the pipeline. */ public function clear() { $this->pipeline->clear(); } /** * Signal handler. * @param int $signo */ public function handleSignal($signo) { switch ($signo) { case \SIGINT: case \SIGTERM: if (!is_null($this->lastSignal) && $this->lastSignal <= (time() - 5)) { $this->workshop->stopNow(); } else { $this->lastSignal = time(); $this->workshop->stop(); } break; } } }
<?php namespace Emphloyer; /** * Cli is the class used by the command line runner to execute input commands. */ class Cli { protected $lastSignal; protected $pipeline; protected $numberOfEmployees = 0; /** * Configure with PHP code from a file. */ public function configure($filename) { require $filename; $this->numberOfEmployees = $numberOfEmployees; $this->pipeline = new Pipeline($pipelineBackend); } /** * Run jobs. */ public function run() { $this->workshop = new Workshop(new Boss($this->pipeline), $this->numberOfEmployees); declare(ticks = 100); pcntl_signal(\SIGINT, array($this, 'handleSignal')); $this->workshop->run(); } /** * Clear all jobs from the pipeline. */ public function clear() { $this->pipeline->clear(); } /** * Signal handler. * @param int $signo */ public function handleSignal($signo) { switch ($signo) { case \SIGINT: if (!is_null($this->lastSignal) && $this->lastSignal <= (time() - 5)) { $this->workshop->stopNow(); } else { $this->lastSignal = time(); $this->workshop->stop(); } break; } } }
Edit text for installer page
<?php $this->pageTitle = Yii::app()->name . '- Further Steps'; ?> <h1><?php echo CHtml::encode(Yii::app()->name); ?> - Further Steps</h1> <p><b>Success! The database has been set up and Metadata Games has been installed.</b></p> <p>Now to configure your install of Metadata Games:</p> <p><b>All links below will open in a new tab or window to allow you to return to this list.</b></p> <ol> <li><a href="<?php echo Yii::app()->baseUrl; ?>/index.php/user/login" target="_blank">Login</a> to gain access to the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin" target="_blank">admin tool</a>. </li> <li>Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/plugins" target="_blank">plugin tool</a>.</li> <li><a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/imageSet" target="_blank">Create image sets</a> and <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/import" target="_blank">import images</a>.</li> <li>Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/games" target="_blank">games tool</a> and activate the ones you want to use.</li> <li>Go to the <a href="<?php echo Yii::app()->baseUrl; ?>" target="_blank">Arcade</a> and play!</li> </ol>
<?php $this->pageTitle = Yii::app()->name . '- Further Steps'; ?> <h1><?php echo CHtml::encode(Yii::app()->name); ?> - Further Steps</h1> <p><b>Success! The database has been set up and Metadata Games has been configured.</b></p> <p>Some things are however left to to do:</p> <p><b>All links below will open in a new tab or window to allow you to return to this list.</b></p> <ol> <li><a href="<?php echo Yii::app()->baseUrl; ?>/index.php/user/login" target="_blank">Login</a> gain access to the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin" target="_blank">admin tool</a>. </li> <li>Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/plugins" target="_blank">plugin tool</a></li> <li><a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/imageSet" target="_blank">Create image sets</a> and <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/admin/import" target="_blank">import images</a></li> <li>Visit the <a href="<?php echo Yii::app()->baseUrl; ?>/index.php/games" target="_blank">games tool</a> and activate the ones you want to make use of</li> <li>Goto the <a href="<?php echo Yii::app()->baseUrl; ?>" target="_blank">Arcade</a> and play!</li> </ol>
Add fluent interface for setTransformer in builder
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\SettingsBundle\Schema; use Sylius\Bundle\SettingsBundle\Transformer\ParameterTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * Settings builder. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class SettingsBuilder extends OptionsResolver implements SettingsBuilderInterface { /** * Transformers array. * * @var ParameterTransformerInterface[] */ protected $transformers; /** * Constructor. */ public function __construct() { parent::__construct(); $this->transformers = array(); } /** * {@inheritdoc} */ public function setTransformer($parameterName, ParameterTransformerInterface $transformer) { $this->transformers[$parameterName] = $transformer; return $this; } /** * {@inheritdoc} */ public function getTransformers() { return $this->transformers; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\SettingsBundle\Schema; use Sylius\Bundle\SettingsBundle\Transformer\ParameterTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * Settings builder. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class SettingsBuilder extends OptionsResolver implements SettingsBuilderInterface { /** * Transformers array. * * @var ParameterTransformerInterface[] */ protected $transformers; /** * Constructor. */ public function __construct() { parent::__construct(); $this->transformers = array(); } /** * {@inheritdoc} */ public function setTransformer($parameterName, ParameterTransformerInterface $transformer) { $this->transformers[$parameterName] = $transformer; } /** * {@inheritdoc} */ public function getTransformers() { return $this->transformers; } }
Move $state setup to run block
angular.module('resourceSolver', []) .provider('resourceSolver', function ResourceSolver() { var baseUrl = ''; this.setBaseUrl = function(url) { baseUrl = url; }; this.$get = function() { return { getBaseUrl: function() { return baseUrl; } }; }; }).run(function($rootScope, $state) { $rootScope.$on('$stateChangeStart', function(event, state, params) { $state.next = state; $state.nextParams = params; }); }) .constant('rs', function(res) { function Solver($resource, resourceSolver, $state) { var baseUrl = resourceSolver.getBaseUrl(); var action = res.action || 'get'; return $resource(baseUrl+res.url, $state.nextParams)[action]().$promise; }; return ['$resource', 'resourceSolver', '$state', Solver]; });
angular.module('resourceSolver', []) .provider('resourceSolver', function ResourceSolver() { var baseUrl = ''; this.setBaseUrl = function(url) { baseUrl = url; }; this.$get = function($rootScope, $state) { $rootScope.$on('$stateChangeStart', function(event, state, params) { $state.next = state; $state.nextParams = params; }); return { getBaseUrl: function() { return baseUrl; } }; }; }) .constant('rs', function(res) { function Solver($resource, resourceSolver, $state) { var baseUrl = resourceSolver.getBaseUrl(); var action = res.action || 'get'; return $resource(baseUrl+res.url, $state.nextParams)[action]().$promise; }; return ['$resource', 'resourceSolver', '$state', Solver]; });
Use loadend to capture error or result
/* global FileReader */ var methods = { arraybuffer: 'readAsArrayBuffer', dataurl: 'readAsDataURL', text: 'readAsText' }; function readBlob (blob, type, cb) { var promise; if (typeof type !== 'string') { cb = type; type = 'arraybuffer'; } if (!cb) { promise = new Promise(function (resolve, reject) { cb = function (err, result) { if (err) reject(err); else resolve(result); }; }); } var method = methods[type.toLowerCase()]; var reader = new FileReader(); reader.addEventListener('loadend', function onend (e) { reader.removeEventListener('loadend', onend); if (e.error) { cb(e.error); } else { cb(null, reader.result); } }); if (method) { reader[method](blob); } else { // assume the output value is a text encoding reader.readAsText(blob, type); } return promise; } module.exports = readBlob; // add arraybuffer, dataurl, and text methods // as aliases to their options counterpart Object.keys(methods).forEach(function (type) { readBlob[type] = function (blob, cb) { return readBlob(blob, type, cb); }; });
/* global FileReader */ var methods = { arraybuffer: 'readAsArrayBuffer', dataurl: 'readAsDataURL', text: 'readAsText' }; function readBlob (blob, type, cb) { var promise; if (typeof type !== 'string') { cb = type; type = 'arraybuffer'; } if (!cb) { promise = new Promise(function (resolve, reject) { cb = function (err, result) { if (err) reject(err); else resolve(result); }; }); } var method = methods[type.toLowerCase()]; var reader = new FileReader(); reader.onload = function () { cb(null, reader.result); }; reader.onerror = function () { cb(reader.error); }; reader.onabort = function () { cb(reader.error); }; if (method) { reader[method](blob); } else { // assume the output value is a text encoding reader.readAsText(blob, type); } return promise; } module.exports = readBlob; // add arraybuffer, dataurl, and text methods // as aliases to their options counterpart Object.keys(methods).forEach(function (type) { readBlob[type] = function (blob, cb) { return readBlob(blob, type, cb); }; });
Remove clear_id for signup page Still need it for /act so we get zip codes.
requirejs.config({ shim: { 'call': { deps: ['form', 'jquery', 'campaign'], exports: 'call' }, 'campaign': { deps: ['form', 'jquery'], exports: 'campaign' }, 'form_mods': { deps: ['jquery', 'form'], exports: 'form_mods', }, 'form' : { deps : ['an', 'jquery' ], exports: 'form', }, 'heads' : { deps : ['form', 'jquery' ], exports: 'heads', } }, paths: { an: 'https://actionnetwork.org/widgets/v2/form/stop-the-worst-of-the-worst?format=js&source=widget&style=full', }, baseUrl: '/democrats/app/' }); //Should be able to magically turn a form into a caling form by requiring 'call' require(['form', 'form_mods', 'heads', 'referrer_controls']);
requirejs.config({ shim: { 'call': { deps: ['form', 'jquery', 'campaign'], exports: 'call' }, 'campaign': { deps: ['form', 'jquery'], exports: 'campaign' }, 'form_mods': { deps: ['jquery', 'form'], exports: 'form_mods', }, 'form' : { deps : ['an', 'jquery' ], exports: 'form', }, 'heads' : { deps : ['form', 'jquery' ], exports: 'heads', } }, paths: { an: 'https://actionnetwork.org/widgets/v2/form/stop-the-worst-of-the-worst?format=js&source=widget&style=full&clear_id=true', }, baseUrl: '/democrats/app/' }); //Should be able to magically turn a form into a caling form by requiring 'call' require(['form', 'form_mods', 'heads', 'referrer_controls']);
Change log level for file handler
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger("blockbuster") logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.INFO) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger("blockbuster") logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
Make sure the challenge is loaded in the edit-contribution form too
import Ember from 'ember' import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin' const { Route, inject } = Ember export default Route.extend(AuthenticatedRouteMixin, { currentUser: inject.service(), model({ id }) { return this.store.findRecord('contribution', id) }, afterModel(model) { return model.get('challenge') }, actions: { async save(record) { await record.save() this.transitionTo('day', record.get('date')) }, async delete(record) { await record.destroyRecord() this.transitionTo('day', record.get('date')) }, cancel() { if (window.history.length > 1) { window.history.back() return } this.transitionTo('index') } } })
import Ember from 'ember' import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin' const { Route, inject } = Ember export default Route.extend(AuthenticatedRouteMixin, { currentUser: inject.service(), model({ id }) { return this.store.findRecord('contribution', id) }, actions: { async save(record) { await record.save() this.transitionTo('day', record.get('date')) }, async delete(record) { await record.destroyRecord() this.transitionTo('day', record.get('date')) }, cancel() { if (window.history.length > 1) { window.history.back() return } this.transitionTo('index') } } })
Fix reload errors with latest tvOS
'use strict'; // socket.io-client requires the window object, and navigator.userAgent to be present. var window = global; window.navigator = {userAgent: 'tvos'}; var io = require('socket.io-client'); function resume(lastLocation) { if (!lastLocation) { return; } } function logDebug(msg) { if (console && console.debug) { console.debug(msg); } } module.exports = { connect: function (connectURL, app, launchOptions) { var socket = io(connectURL); socket.on('connect', function () { logDebug('Live reload: connected'); }); socket.on('compile', function () { logDebug('Live reload: compiling, prepare for reload'); }); // reload app on reload event socket.on('live-reload', function () { app.reload(); }); if (launchOptions && launchOptions.reloadData) { resume(launchOptions.reloadData || {}); } } };
'use strict'; // socket.io-client requires the window object, and navigator.userAgent to be present. var window = {}, navigator = {userAgent: 'tvos'}; var io = require('socket.io-client'); /* import * as router from 'lib/router'; */ function resume(lastLocation) { if (!lastLocation) { return; } //router.goTo(lastLocation); } function logDebug(msg) { if (console && console.debug) { console.debug(msg); } } module.exports = { connect: function (connectURL, app, launchOptions) { var socket = io(connectURL); socket.on('connect', function () { logDebug('Live reload: connected'); }); socket.on('compile', function () { logDebug('Live reload: compiling, prepare for reload'); }); // reload app on reload event socket.on('live-reload', function () { app.reload()//{when: 'now'}, { //lastLocation: router.getLocation() //}); }); if (launchOptions.reloadData) { resume(launchOptions.reloadData || {}); } } };
Check application environment for developing addon state
'use strict'; const mergeTrees = require('broccoli-merge-trees'); const WatchedDir = require('broccoli-source').WatchedDir; const json = require('broccoli-json-module'); module.exports = { name: 'webrtc-troubleshoot', isDevelopingAddon: function () { return this.app && this.app.env === 'development'; }, included: function (app) { this._super.included(app); this.app = app; this.translation = new WatchedDir('translations'); app.import(app.bowerDirectory + '/lodash/lodash.js'); app.import(app.bowerDirectory + '/localmedia/localMedia.bundle.js'); // Fix when https://github.com/webrtc/adapter/issues/206 app.import(app.bowerDirectory + '/webrtc-adapter/adapter-1.0.4.js'); app.import(app.bowerDirectory + '/rtcpeerconnection/rtcpeerconnection.bundle.js'); }, treeForApp: function (tree) { const trees = [tree]; trees.push(json(tree)); return mergeTrees(trees, { overwrite: true }); } };
'use strict'; const mergeTrees = require('broccoli-merge-trees'); const WatchedDir = require('broccoli-source').WatchedDir; const json = require('broccoli-json-module'); module.exports = { name: 'webrtc-troubleshoot', isDevelopingAddon: function () { return true; }, included: function (app) { this._super.included(app); this.translation = new WatchedDir('translations'); app.import(app.bowerDirectory + '/lodash/lodash.js'); app.import(app.bowerDirectory + '/localmedia/localMedia.bundle.js'); // Fix when https://github.com/webrtc/adapter/issues/206 app.import(app.bowerDirectory + '/webrtc-adapter/adapter-1.0.4.js'); app.import(app.bowerDirectory + '/rtcpeerconnection/rtcpeerconnection.bundle.js'); }, treeForApp: function (tree) { const trees = [tree]; trees.push(json(tree)); return mergeTrees(trees, { overwrite: true }); } };
Add ipaddress requirement to python older than 3.3
import sys from setuptools import find_packages from setuptools import setup requirements = ['six'] if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 3): requirements.append('ipaddress') def get_long_description(): with open('README.md') as readme_file: return readme_file.read() setup( name="RouterOS-api", version='0.16.1.dev0', description='Python API to RouterBoard devices produced by MikroTik.', long_description=get_long_description(), long_description_content_type='text/markdown', author='Social WiFi', author_email='it@socialwifi.com', url='https://github.com/socialwifi/RouterOS-api', packages=find_packages(), test_suite="tests", license="MIT", install_requires=requirements, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
from setuptools import find_packages from setuptools import setup def get_long_description(): with open('README.md') as readme_file: return readme_file.read() setup( name="RouterOS-api", version='0.16.1.dev0', description='Python API to RouterBoard devices produced by MikroTik.', long_description=get_long_description(), long_description_content_type='text/markdown', author='Social WiFi', author_email='it@socialwifi.com', url='https://github.com/socialwifi/RouterOS-api', packages=find_packages(), test_suite="tests", license="MIT", install_requires=['six'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
Update the default settings file to include the database threaded option
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=)))', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'threaded': True, }, } } TEMPLATE_DIRS = ( '', ) STATIC_ROOT = '' EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = EMAIL_USE_TLS = True EMAIL_RNACENTRAL_HELPDESK = '' SECRET_KEY = '' ADMINS = ( ('', ''), ) COMPRESS_ENABLED = False DEBUG = False ALLOWED_HOSTS = [] # django-debug-toolbar INTERNAL_IPS = ('127.0.0.1',) # django-maintenance MAINTENANCE_MODE = False
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', 'NAME': '', 'USER': '', 'PASSWORD': '', 'OPTIONS' : { 'init_command' : 'SET storage_engine=MyISAM', }, } } TEMPLATE_DIRS = ( '', ) STATIC_ROOT = '' EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = EMAIL_USE_TLS = True EMAIL_RNACENTRAL_HELPDESK = '' SECRET_KEY = '' ADMINS = ( ('', ''), ) COMPRESS_ENABLED = DEBUG = ALLOWED_HOSTS = [] # django-debug-toolbar INTERNAL_IPS = ('127.0.0.1',)
Load measurements and materials JS after turbolinks page load
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require js-routes //= require jquery //= require jquery_ujs //= require turbolinks //= require blacklight/blacklight //= require jquery.nested-fields //= require sufia //= require_tree . var ready = function() { $('#material-fields').nestedFields(); $('#measurement-fields').nestedFields(); }; $(document).on('turbolinks:load', ready);
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require js-routes //= require jquery //= require jquery_ujs //= require turbolinks //= require blacklight/blacklight //= require jquery.nested-fields //= require sufia //= require_tree . $(document).ready(function(e) { $('#material-fields').nestedFields(); $('#measurement-fields').nestedFields(); });