text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update line end and EOF for build fail
package pro.jtaylor.timetracker.core; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pro.jtaylor.timetracker.core.dao.TimeEntry; import java.util.List; @Component public class Tracker { @Autowired private List<TimeEntry> entries; /** * Add Method * @param int add for entries */ public void add(TimeEntry entry) { entries.add(entry); } /** * Remove Method * @param int remove for entries */ public void remove(TimeEntry entry) { entries.remove(entry); } /** * Size Method * @param int size for entries */ public int size() { return entries.size(); } /** * Get Method * @param TimeEntry get for entries */ public TimeEntry get(int index) { // boolean vaild = false; // if (vaild == true) { // whatever // return entries.get(index); } }
package pro.jtaylor.timetracker.core; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pro.jtaylor.timetracker.core.dao.TimeEntry; import java.util.List; @Component public class Tracker { @Autowired private List<TimeEntry> entries; /** * Add Method * @param int add for entries */ public void add(TimeEntry entry) { entries.add(entry); } /** * Remove Method * @param int remove for entries */ public void remove(TimeEntry entry) { entries.remove(entry); } /** * Size Method * @param int size for entries */ public int size() { return entries.size(); } /** * Get Method * @param TimeEntry get for entries */ public TimeEntry get(int index) { // boolean vaild = false; // if (vaild == true) { // whatever // return entries.get(index); } }
Use default module with a required instead of own subclass, this enables NOT routing / git-svn-id: e77a8db410fc7e53f700994083f7980387c3a882@657 528793b8-127e-4309-9901-b74759c7208d
<?php /** * SURFconext EngineBlock * * LICENSE * * Copyright 2011 SURFnet bv, The Netherlands * * 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. * * @category SURFconext EngineBlock * @package * @copyright Copyright © 2010-2011 SURFnet SURFnet bv, The Netherlands (http://www.surfnet.nl) * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 */ require '../../library/EngineBlock/ApplicationSingleton.php'; $application = EngineBlock_ApplicationSingleton::getInstance(); $application->bootstrap(); $dispatcher = new EngineBlock_Dispatcher(); $profileRouter = new EngineBlock_Router_Default(); $profileRouter->requireModule('authentication'); $dispatcher->setRouters(array( $profileRouter, new EngineBlock_Router_CatchAll('profile', 'index', 'index'), )); $dispatcher->dispatch(); $application->getHttpResponse()->send();
<?php /** * SURFconext EngineBlock * * LICENSE * * Copyright 2011 SURFnet bv, The Netherlands * * 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. * * @category SURFconext EngineBlock * @package * @copyright Copyright © 2010-2011 SURFnet SURFnet bv, The Netherlands (http://www.surfnet.nl) * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 */ require '../../library/EngineBlock/ApplicationSingleton.php'; $application = EngineBlock_ApplicationSingleton::getInstance(); $application->bootstrap(); $dispatcher = new EngineBlock_Dispatcher(); $dispatcher->setRouters(array( new EngineBlock_Router_Profile(), new EngineBlock_Router_CatchAll('profile', 'index', 'index'), )); $dispatcher->dispatch(); $application->getHttpResponse()->send();
Use a zero-arg constructor for our test IntentService See https://github.com/robolectric/robolectric/pull/3090 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=193692162
/* * Copyright (C) 2017 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.android.support.functional; import android.content.Intent; import dagger.android.DaggerIntentService; import java.util.Set; import javax.inject.Inject; public final class TestIntentService extends DaggerIntentService { @Inject Set<Class<?>> componentHierarchy; public TestIntentService() { super("TestIntentService"); } @Override protected void onHandleIntent(Intent intent) {} }
/* * Copyright (C) 2017 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.android.support.functional; import android.content.Intent; import dagger.android.DaggerIntentService; import java.util.Set; import javax.inject.Inject; public final class TestIntentService extends DaggerIntentService { @Inject Set<Class<?>> componentHierarchy; public TestIntentService(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) {} }
Use is_null to check if a state isn't available.
<?php /** * @version $Id: default_filter.php 1696 2011-06-10 16:00:55Z tomjanssens $ * @category Nooku * @package Nooku_Server * @subpackage Banners * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ defined('KOOWA') or die( 'Restricted access' ); ?> <div id="filter" class="group"> <ul> <li class="<?= is_null($state->published) ? 'active' : ''; ?> separator-right"> <a href="<?= @route('published=' ) ?>"> <?= @text('All') ?> </a> </li> <li class="<?= $state->published === true ? 'active' : ''; ?>"> <a href="<?= @route($state->published === true ? 'published=' : 'published=1') ?>"> <?= @text('Published') ?> </a> </li> <li class="<?= $state->published === false ? 'active' : ''; ?>"> <a href="<?= @route($state->published === false ? 'published=' : 'published=0' ) ?>"> <?= @text('Unpublished') ?> </a> </li> </ul> </div>
<?php /** * @version $Id: default_filter.php 1696 2011-06-10 16:00:55Z tomjanssens $ * @category Nooku * @package Nooku_Server * @subpackage Banners * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ defined('KOOWA') or die( 'Restricted access' ); ?> <div id="filter" class="group"> <ul> <li class="<?= !is_bool($state->enabled) ? 'active' : ''; ?> separator-right"> <a href="<?= @route('enabled=' ) ?>"> <?= @text('All') ?> </a> </li> <li class="<?= $state->enabled === true ? 'active' : ''; ?>"> <a href="<?= @route('enabled=1' ) ?>"> <?= @text('Published') ?> </a> </li> <li class="<?= $state->enabled === false ? 'active' : ''; ?>"> <a href="<?= @route('enabled=0' ) ?>"> <?= @text('Unpublished') ?> </a> </li> </ul> </div>
Comment modified (testing github email configuration)
package com.capgemini.resilience.employer.service; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.stereotype.Service; import java.util.Random; @Service public class EmployerServiceTmp { private final Random random = new Random(); private static final double SUCCESS_PROBABILITY = 0.6; /** * "Primary method" with defined fallback method. * * @return Standard answer */ @HystrixCommand(fallbackMethod = "getFallbackEmployer") public String getEmployer() { double randomDouble = random.nextDouble(); if (randomDouble <= SUCCESS_PROBABILITY) { return "Success employer"; } throw new IllegalStateException("Test exception"); } /** * Example fallback method. * @return Fallback answer */ public String getFallbackEmployer() { return "Fallback employer"; } }
package com.capgemini.resilience.employer.service; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.stereotype.Service; import java.util.Random; @Service public class EmployerServiceTmp { private final Random random = new Random(); private static final double SUCCESS_PROBABILITY = 0.6; /** * "Primary method" with defined fallback method. * @return Standard answer */ @HystrixCommand(fallbackMethod = "getFallbackEmployer") public String getEmployer() { double randomDouble = random.nextDouble(); if (randomDouble <= SUCCESS_PROBABILITY) { return "Success employer"; } throw new IllegalStateException("Test exception"); } /** * Example fallback method. * @return Fallback answer */ public String getFallbackEmployer() { return "Fallback employer"; } }
Remove methods left over from previous pipedprovider mechanism
/* * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Transform = require('stream').Transform; var toDelta = require('n2k-signalk').toDelta; require('util').inherits(ToSignalK, Transform); function ToSignalK() { Transform.call(this, { objectMode: true }); } ToSignalK.prototype._transform = function(chunk, encoding, done) { var delta = toDelta(chunk); if (delta && delta.updates[0].values.length > 0) { this.push(delta); } done(); } module.exports = ToSignalK;
/* * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Transform = require('stream').Transform; var toDelta = require('n2k-signalk').toDelta; require('util').inherits(ToSignalK, Transform); function ToSignalK() { Transform.call(this, { objectMode: true }); } ToSignalK.prototype._transform = function(chunk, encoding, done) { var delta = toDelta(chunk); if (delta && delta.updates[0].values.length > 0) { this.push(delta); } done(); } ToSignalK.prototype.start = function() {} ToSignalK.prototype.stop = function() {} module.exports = ToSignalK;
Update ECDC scraper for tweaked page structure
#!/usr/bin/env python import requests import lxml.html import pandas as pd import sys URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx" columns = [ "country", "current_zika_transmission", ] def scrape(): html = requests.get(URL).content dom = lxml.html.fromstring(html) table = dom.cssselect(".ms-rteTable-1")[-1] rows = table.cssselect("tr")[1:] data = [ [ td.text_content().strip() for td in tr.cssselect("td, th") ] for tr in rows ] df = pd.DataFrame(data, columns=columns)[columns] return df if __name__ == "__main__": df = scrape() df.to_csv(sys.stdout, index=False, encoding="utf-8")
#!/usr/bin/env python import requests import lxml.html import pandas as pd import sys URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx" columns = [ "country", "current_zika_transmission", ] def scrape(): html = requests.get(URL).content dom = lxml.html.fromstring(html) table = dom.cssselect(".ms-rteTable-1")[0] rows = table.cssselect("tr")[1:] data = [ [ td.text_content().strip() for td in tr.cssselect("td, th") ] for tr in rows ] df = pd.DataFrame(data, columns=columns)[columns] return df if __name__ == "__main__": df = scrape() df.to_csv(sys.stdout, index=False, encoding="utf-8")
Add a public modifier to an interface method
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Authentication\Provider; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; /** * AuthenticationProviderInterface is the interface for all authentication * providers. * * Concrete implementations processes specific Token instances. * * @author Fabien Potencier <fabien@symfony.com> */ interface AuthenticationProviderInterface extends AuthenticationManagerInterface { /** * Checks whether this provider supports the given token. * * @param TokenInterface $token A TokenInterface instance * * @return Boolean true if the implementation supports the Token, false otherwise */ public function supports(TokenInterface $token); }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Authentication\Provider; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; /** * AuthenticationProviderInterface is the interface for all authentication * providers. * * Concrete implementations processes specific Token instances. * * @author Fabien Potencier <fabien@symfony.com> */ interface AuthenticationProviderInterface extends AuthenticationManagerInterface { /** * Checks whether this provider supports the given token. * * @param TokenInterface $token A TokenInterface instance * * @return Boolean true if the implementation supports the Token, false otherwise */ function supports(TokenInterface $token); }
Fix problem when using the numpad The numpad numbers' code are different from the standard numbers. The code number starts in 96 (number 0) and ends in 105 (number 9). The problem is in the String.fromCharCode function because it doesn't recognize the numpad code numbers. To fix that this commit was made to calculate the 'correct' key code to be used in the String.fromCharCode function. Keyboard keys code: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
/* Character mask for jQuery. https://github.com/sobrinho/jquery.singlemask Copyright (c) 2011-2013 Gabriel Sobrinho (http://gabrielsobrinho.com/). Released under the MIT license */ (function ($) { function getPasteEvent() { var el = document.createElement('input'), name = 'onpaste'; el.setAttribute(name, ''); return (typeof el[name] === 'function') ? 'paste' : 'input'; } var pasteEventName = getPasteEvent(); $.fn.singlemask = function (mask) { $(this).keydown(function (event) { var key = event.keyCode; if (key < 16 || (key > 16 && key < 32) || (key > 32 && key < 41)) { return; } // Numpad key numbers starts on 96 (0) and ends on 105 (9) // Somehow the String.fromCharCode doesn't knows that // Subtracting 48 we have the 'standard' number code if (key >= 96 && key <= 105) { key = key - 48; } return String.fromCharCode(key).match(mask); }).bind(pasteEventName, function () { this.value = $.grep(this.value, function (character) { return character.match(mask); }).join(''); }); } })(jQuery);
/* Character mask for jQuery. https://github.com/sobrinho/jquery.singlemask Copyright (c) 2011-2013 Gabriel Sobrinho (http://gabrielsobrinho.com/). Released under the MIT license */ (function ($) { function getPasteEvent() { var el = document.createElement('input'), name = 'onpaste'; el.setAttribute(name, ''); return (typeof el[name] === 'function') ? 'paste' : 'input'; } var pasteEventName = getPasteEvent(); $.fn.singlemask = function (mask) { $(this).keydown(function (event) { var key = event.keyCode; if (key < 16 || (key > 16 && key < 32) || (key > 32 && key < 41)) { return; } return String.fromCharCode(key).match(mask); }).bind(pasteEventName, function () { this.value = $.grep(this.value, function (character) { return character.match(mask); }).join(''); }); } })(jQuery);
Add Easy Read to the list of education levels [SWIK-2525]
const supportedCodes = { '0' : 'Preschool', '1' : 'Primary education', '2' : 'Lower secondary education', '3' : 'Upper secondary education', '55' : 'Vocational education', '6' : 'Bachelor\'s / undergraduate', '7' : 'Masters / postgraduate', '8' : 'Doctoral', '9' : 'Other', '98' : 'Easy Read', // not part of spec }; export default { educationLevels: supportedCodes, getEducationLevel: function(code) { let levelName = supportedCodes[code]; // if not found try to match against prefix while (code && !levelName) { code = code.slice(0, -1); levelName = supportedCodes[code]; } return levelName || 'Unknown'; }, };
const supportedCodes = { '0' : 'Preschool', '1' : 'Primary education', '2' : 'Lower secondary education', '3' : 'Upper secondary education', '55' : 'Vocational education', '6' : 'Bachelor\'s / undergraduate', '7' : 'Masters / postgraduate', '8' : 'Doctoral', '9' : 'Other', }; export default { educationLevels: supportedCodes, getEducationLevel: function(code) { let levelName = supportedCodes[code]; // if not found try to match against prefix while (code && !levelName) { code = code.slice(0, -1); levelName = supportedCodes[code]; } return levelName || 'Unknown'; }, };
Change version to 1.0.3 (dev)
# -*- coding: utf-8 -*- { "name": "Account Credit Transfer", "version": "1.0.3", "author": "XCG Consulting", "website": "http://www.openerp-experts.com", "category": 'Accounting', "description": """Account Voucher Credit Transfer Payment. You need to set up some things before using it. A credit transfer config link a bank with a parser A credit transfer parser link a parser with a template that you can upload """, "depends": [ 'base', 'account_streamline', ], "data": [ "security/ir.model.access.csv", "views/config.xml", "views/parser.xml", "views/res.bank.xml", ], 'demo_xml': [], 'test': [], 'installable': True, 'active': False, 'external_dependencies': { 'python': ['genshi'] } }
# -*- coding: utf-8 -*- { "name": "Account Credit Transfer", "version": "1.0.2", "author": "XCG Consulting", "website": "http://www.openerp-experts.com", "category": 'Accounting', "description": """Account Voucher Credit Transfer Payment. You need to set up some things before using it. A credit transfer config link a bank with a parser A credit transfer parser link a parser with a template that you can upload """, "depends": [ 'base', 'account_streamline', ], "data": [ "security/ir.model.access.csv", "views/config.xml", "views/parser.xml", "views/res.bank.xml", ], 'demo_xml': [], 'test': [], 'installable': True, 'active': False, 'external_dependencies': { 'python': ['genshi'] } }
Comment out the right things
/** "use strict"; var PID_FILENAME = "ircas.pid"; var fs = require("fs"); var q = require("q"); var logging = require("./logging"); var Validator = require("./config/validator"); var log = logging.get("hotreload"); var reloading = false; var reloadConfig = function() { log.info("Reloading config file...."); var config; try { var configValidator = new Validator(Validator.getFileLocation()); config = configValidator.validate(); } catch (e) { log.error("Failed to load config file: " + e); return q.reject(); } log.info("Loaded config file."); return q(); }; */ module.exports.setup = function() { /* // write out the pid file fs.writeFileSync(PID_FILENAME, "" + process.pid); // SIGUSR1 is reserved by node for debugging process.on("SIGUSR2", function() { log.info("SIGUSR2 received."); if (!reloading) { log.info(" @@@@@@@@@@ HOT RELOAD @@@@@@@@@@ "); reloading = true; reloadConfig().finally(function() { reloading = false; }); } }); */ };
"use strict"; var PID_FILENAME = "ircas.pid"; var fs = require("fs"); var q = require("q"); var logging = require("./logging"); var Validator = require("./config/validator"); var log = logging.get("hotreload"); var reloading = false; var reloadConfig = function() { log.info("Reloading config file...."); var config; try { var configValidator = new Validator(Validator.getFileLocation()); config = configValidator.validate(); } catch (e) { log.error("Failed to load config file: " + e); return q.reject(); } log.info("Loaded config file."); return q(); }; module.exports.setup = function() { // write out the pid file fs.writeFileSync(PID_FILENAME, "" + process.pid); // SIGUSR1 is reserved by node for debugging process.on("SIGUSR2", function() { log.info("SIGUSR2 received."); /* if (!reloading) { log.info(" @@@@@@@@@@ HOT RELOAD @@@@@@@@@@ "); reloading = true; reloadConfig().finally(function() { reloading = false; }); } */ }); };
Fix closing /dev/null when executing in quiet mode
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: result = subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) finally: if quiet: stderr.close() return result
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) except: if quiet: stderr.close() raise
Fix bug in beforeaction method
<?php /** * @author José Lorente <jose.lorente.martin@gmail.com> * @license The MIT License (MIT) * @copyright José Lorente * @version 1.0 */ namespace jlorente\notification\behaviors; use yii\base\ActionFilter; use jlorente\notification\db\Notification; use Yii; class NotificationControl extends ActionFilter { /** * @inheritdoc */ public function beforeAction($action) { if (Yii::$app->user->isGuest === false) { $this->checkNotification(); } return true; } protected function checkNotification() { Notification::deleteAll([ 'user_id' => Yii::$app->user->id, 'path_info' => '/' . Yii::$app->request->getPathInfo() ]); } }
<?php /** * @author José Lorente <jose.lorente.martin@gmail.com> * @license The MIT License (MIT) * @copyright José Lorente * @version 1.0 */ namespace jlorente\notification\behaviors; use yii\base\ActionFilter; use jlorente\notification\db\Notification; use Yii; class NotificationControl extends ActionFilter { /** * @inheritdoc */ public function beforeAction($action) { if (Yii::$app->user->isGuest === false) { $this->checkNotification(); } } protected function checkNotification() { Notification::deleteAll([ 'user_id' => Yii::$app->user->id, 'path_info' => '/' . Yii::$app->request->getPathInfo() ]); } }
Use port from environment define.
var koa = require('koa'); var route = require('koa-route'); var logger = require('koa-logger'); var app = koa(); var debug = require('debug')('index') var intents = require('./controllers/intents'); var adManifest = require('./controllers/ad-manifest'); var sync = require('./controllers/sync'); var PORT = process.env.PORT || 3000; app.use(logger()); app.use(route.get('/', function * () { this.body = 'Welcome to the Vault.'; })); app.use(route.get('/ad-manifest', adManifest.get)); app.use(route.post('/intents', intents.push)); app.use(route.get('/sync/:userId', sync.get)); app.use(route.post('/sync', sync.push)); app.listen(PORT, function() { debug('webserver started on port 3000'); }); app.on('error', function(err){ debug('server error', err); });
var koa = require('koa'); var route = require('koa-route'); var logger = require('koa-logger'); var app = koa(); var debug = require('debug')('index') var intents = require('./controllers/intents'); var adManifest = require('./controllers/ad-manifest'); var sync = require('./controllers/sync'); app.use(logger()); app.use(route.get('/', function * () { this.body = 'Welcome to the Vault.'; })); app.use(route.get('/ad-manifest', adManifest.get)); app.use(route.post('/intents', intents.push)); app.use(route.get('/sync/:userId', sync.get)); app.use(route.post('/sync', sync.push)); app.listen(3000, function() { debug('webserver started at http://localhost:3000'); }); app.on('error', function(err){ debug('server error', err); });
Handle unrecognised CLI commands in a git-like fashion
package main import ( "fmt" "github.com/leocassarani/pew/command" "os" ) func main() { args := os.Args if len(args) < 2 { printUsage(args) os.Exit(1) } cmd := args[1] cmdArgs := args[2:] switch cmd { case "run": err := command.Run(cmdArgs) exit(err) case "help": fallthrough case "--help": printUsage(args) exit(nil) default: err := fmt.Errorf("'%s' is not a command. See '%s --help'.", cmd, args[0]) exit(err) } } func exit(err error) { if err != nil { log(err) os.Exit(1) } os.Exit(0) } func log(err error) { fmt.Fprintf(os.Stderr, "pew: %v\n", err) } func printUsage(args []string) { fmt.Printf("usage: %s <command>\n", args[0]) }
package main import ( "fmt" "github.com/leocassarani/pew/command" "os" ) func main() { args := os.Args if len(args) < 2 { printUsage(args) os.Exit(1) } cmd := args[1] cmdArgs := args[2:] switch cmd { case "run": err := command.Run(cmdArgs) exit(err) case "help": fallthrough case "--help": printUsage(args) os.Exit(0) } } func exit(err error) { if err != nil { log(err) os.Exit(1) } os.Exit(0) } func log(err error) { fmt.Fprintf(os.Stderr, "pew: %v\n", err) } func printUsage(args []string) { fmt.Printf("usage: %s <command>\n", args[0]) }
Change version to something more appropriate.
<?php /** * Application.php * * MIT LICENSE * * LICENSE: This source file is subject to the MIT license. * A copy of the licenses text was distributed alongside this * file (usually the repository or package root). The text can also * be obtained through one of the following sources: * * http://opensource.org/licenses/MIT * * https://github.com/suralc/pvra/blob/master/LICENSE * * @author suralc <thesurwaveing@gmail.com> * @license http://opensource.org/licenses/MIT MIT */ namespace Pvra\Console; use Symfony\Component\Console\Application as BaseApplication; /** * Class Application * * @package Pvra\Console */ class Application extends BaseApplication { const APPLICATION_DEFAULT_VERSION = '0.0.1'; /** * @inheritdoc */ public function __construct($name = 'UNKNOWN', $version = '@package_version@') { if ($version === '@package' . '_version@') { $version = static::APPLICATION_DEFAULT_VERSION; } parent::__construct($name, $version); } }
<?php /** * Application.php * * MIT LICENSE * * LICENSE: This source file is subject to the MIT license. * A copy of the licenses text was distributed alongside this * file (usually the repository or package root). The text can also * be obtained through one of the following sources: * * http://opensource.org/licenses/MIT * * https://github.com/suralc/pvra/blob/master/LICENSE * * @author suralc <thesurwaveing@gmail.com> * @license http://opensource.org/licenses/MIT MIT */ namespace Pvra\Console; use Symfony\Component\Console\Application as BaseApplication; /** * Class Application * * @package Pvra\Console */ class Application extends BaseApplication { const APPLICATION_DEFAULT_VERSION = '0.1.0-dev'; /** * @inheritdoc */ public function __construct($name = 'UNKNOWN', $version = '@package_version@') { if ($version === '@package' . '_version@') { $version = static::APPLICATION_DEFAULT_VERSION; } parent::__construct($name, $version); } }
Add createdAt field to user schema
var Schema = {}; Schema.UserProfile = new SimpleSchema({ name: { type: String }, events: { type: [Object], blackbox: true }, carpool: { type: Number }, meetings: { type: Number }, mic: { type: Number }, points: { type: Number }, strikes: { type: Number }, suggests: { type: Number } }); Schema.User = new SimpleSchema({ _id: { type: String, optional: true }, createdAt: { type: Date, optional: true }, emails: { type: [Object], optional: true }, 'emails.$.address': { type: String, regEx: SimpleSchema.RegEx.Email }, 'emails.$.verified': { type: Boolean }, isAdmin: { type: Boolean, optional: true }, profile: { // public and not editable type: Schema.UserProfile }, services: { type: Object, blackbox: true } }); Meteor.users.attachSchema(Schema.User); Meteor.users.allow({ update: canEditById, remove: canRemoveById }); Meteor.users.deny({ update: function (userId, user, fields) { if (isAdminById(userId)) return false; return _.without(fields, 'password').length > 0; } });
var Schema = {}; Schema.UserProfile = new SimpleSchema({ name: { type: String }, events: { type: [Object], blackbox: true }, carpool: { type: Number }, meetings: { type: Number }, mic: { type: Number }, points: { type: Number }, strikes: { type: Number }, suggests: { type: Number } }); Schema.User = new SimpleSchema({ _id: { type: String, optional: true }, emails: { type: [Object], optional: true }, 'emails.$.address': { type: String, regEx: SimpleSchema.RegEx.Email }, 'emails.$.verified': { type: Boolean }, isAdmin: { type: Boolean, optional: true }, profile: { // public and not editable type: Schema.UserProfile }, services: { type: Object, blackbox: true } }); Meteor.users.attachSchema(Schema.User); Meteor.users.allow({ update: canEditById, remove: canRemoveById }); Meteor.users.deny({ update: function (userId, user, fields) { if (isAdminById(userId)) return false; return _.without(fields, 'password').length > 0; } });
Correct tuple for error message arguments
from . import bluegreen, context_handler # TODO: move as buildercore.concurrency.concurrency_for def concurrency_for(stackname, concurrency_name): """concurrency default is to perform updates one machine at a time. Concurrency can be: - serial: one at a time - parallel: all together - blue-green: 50% at a time""" concurrency_names = ['serial', 'parallel', 'blue-green'] if concurrency_name == 'blue-green': context = context_handler.load_context(stackname) return bluegreen.BlueGreenConcurrency(context['aws']['region']) if concurrency_name == 'serial' or concurrency_name == 'parallel': # maybe return a fabric object in the future return concurrency_name if concurrency_name is None: return 'parallel' raise ValueError("Concurrency %s is not supported. Supported models: %s" % (concurrency_name, concurrency_names))
from . import bluegreen, context_handler # TODO: move as buildercore.concurrency.concurrency_for def concurrency_for(stackname, concurrency_name): """concurrency default is to perform updates one machine at a time. Concurrency can be: - serial: one at a time - parallel: all together - blue-green: 50% at a time""" concurrency_names = ['serial', 'parallel', 'blue-green'] if concurrency_name == 'blue-green': context = context_handler.load_context(stackname) return bluegreen.BlueGreenConcurrency(context['aws']['region']) if concurrency_name == 'serial' or concurrency_name == 'parallel': # maybe return a fabric object in the future return concurrency_name if concurrency_name is None: return 'parallel' raise ValueError("Concurrency %s is not supported. Supported models: %s" % concurrency_name, concurrency_names)
Switch to DNS peer discovery.
package com.msgilligan.peerlist.config; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.net.discovery.PeerDiscovery; import org.bitcoinj.net.discovery.SeedPeers; import org.bitcoinj.params.MainNetParams; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.FileNotFoundException; /** * User: sean * Date: 2/22/14 * Time: 7:56 PM */ @Configuration public class BitcoinConfig { @Bean public NetworkParameters networkParameters() { return MainNetParams.get(); } @Bean public PeerDiscovery peerDiscovery(NetworkParameters params) throws FileNotFoundException { PeerDiscovery pd; pd = new DnsDiscovery(params); // pd = new SeedPeers(params); return pd; } }
package com.msgilligan.peerlist.config; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.net.discovery.PeerDiscovery; import org.bitcoinj.net.discovery.SeedPeers; import org.bitcoinj.params.MainNetParams; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.FileNotFoundException; /** * User: sean * Date: 2/22/14 * Time: 7:56 PM */ @Configuration public class BitcoinConfig { @Bean public NetworkParameters networkParameters() { return MainNetParams.get(); } @Bean public PeerDiscovery peerDiscovery(NetworkParameters params) throws FileNotFoundException { PeerDiscovery pd; // pd = new DnsDiscovery(params); pd = new SeedPeers(params); return pd; } }
Rewrite asyncio test to use futures
# -*- coding: utf-8 -*- import nose.tools as nt from asyncio import Future, gather, get_event_loop, sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ loop = get_event_loop() ee = EventEmitter(loop=loop) future = Future() @ee.on('event') async def event_handler(): future.set_result(True) async def create_timeout(loop=loop): await sleep(1, loop=loop) future.cancel() timeout = create_timeout(loop=loop) @future.add_done_callback def _done(result): nt.assert_true(result) ee.emit('event') loop.run_until_complete(gather(future, timeout))
# -*- coding: utf-8 -*- import nose.tools as nt from asyncio import get_event_loop from asyncio import sleep as async_sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ ee = EventEmitter() loop = get_event_loop() class SenseWasCalled(): def __init__(self): self.was_called = False def am_calling(self): self.was_called = True def assert_was_called(self): nt.assert_true(self.was_called) sensor = SenseWasCalled() @ee.on('event') async def event_handler(): sensor.am_calling() ee.emit('event') loop.run_until_complete(async_sleep(1)) sensor.assert_was_called()
Fix failing test through loading of examples from $PWD.
import pylearn2 from pylearn2.utils.serial import load_train_file import os from pylearn2.testing import no_debug_mode from theano import config @no_debug_mode def test_train_example(): """ tests that the grbm_smd example script runs correctly """ assert config.mode != "DEBUG_MODE" path = pylearn2.__path__[0] train_example_path = os.path.join(path, 'scripts', 'tutorials', 'grbm_smd') cwd = os.getcwd() try: os.chdir(train_example_path) train_yaml_path = os.path.join(train_example_path, 'cifar_grbm_smd.yaml') train_object = load_train_file(train_yaml_path) #make the termination criterion really lax so the test won't run for long train_object.algorithm.termination_criterion.prop_decrease = 0.5 train_object.algorithm.termination_criterion.N = 1 train_object.main_loop() finally: os.chdir(cwd) if __name__ == '__main__': test_train_example()
import pylearn2 from pylearn2.utils.serial import load_train_file import os from pylearn2.testing import no_debug_mode from theano import config @no_debug_mode def test_train_example(): """ tests that the grbm_smd example script runs correctly """ assert config.mode != "DEBUG_MODE" path = pylearn2.__path__[0] train_example_path = os.path.join(path, 'scripts', 'tutorials', 'grbm_smd') train_yaml_path = os.path.join(train_example_path, 'cifar_grbm_smd.yaml') train_object = load_train_file(train_yaml_path) #make the termination criterion really lax so the test won't run for long train_object.algorithm.termination_criterion.prop_decrease = 0.5 train_object.algorithm.termination_criterion.N = 1 train_object.main_loop() if __name__ == '__main__': test_train_example()
Add the lake header back into the rotation, it looks fine. git-svn-id: 71ac0145df79e26b076d62e50011532b62ebd840@97 9841916d-1f77-4d57-ab71-7f08b6dd89e2
<?php $headers = array( array( 'img' => 'images/headers/header_sign.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/4485964682/', 'width' => 950, 'height' => 250, ), array( 'img' => 'images/headers/header_duckies.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/4710923546/', 'width' => 950, 'height' => 250, ), array( 'img' => 'images/headers/header_pier.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/4485317853/', 'width' => 950, 'height' => 250, ), array( 'img' => 'images/headers/header_lake.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/3576628927/', 'width' => 950, 'height' => 250, ), ); // pick a header $header = $headers[ mt_rand( 0, count( $headers ) - 1 ) ]; echo json_encode( $header ); ?>
<?php $headers = array( array( 'img' => 'images/headers/header_sign.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/4485964682/', 'width' => 950, 'height' => 250, ), array( 'img' => 'images/headers/header_duckies.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/4710923546/', 'width' => 950, 'height' => 250, ), array( 'img' => 'images/headers/header_pier.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/4485317853/', 'width' => 950, 'height' => 250, ), /* array( 'img' => 'images/headers/header_lake.jpg', 'flickr' => 'http://www.flickr.com/photos/mellertime/3576628927/', 'width' => 950, 'height' => 250, ), */ ); // pick a header $header = $headers[ mt_rand( 0, count( $headers ) - 1 ) ]; echo json_encode( $header ); ?>
Make splitKeypath() work in old IE
const refPattern = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g; const splitPattern = /([^\\](?:\\\\)*)\./; const escapeKeyPattern = /\\|\./g; const unescapeKeyPattern = /((?:\\)+)\1|\\(\.)/g; export function escapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( escapeKeyPattern, '\\$&' ); } return key; } export function normalise ( ref ) { return ref ? ref.replace( refPattern, '.$1' ) : ''; } export function splitKeypath ( keypath ) { let result = [], match; keypath = normalise( keypath ); while ( match = splitPattern.exec( keypath ) ) { let index = match.index + match[1].length; result.push( keypath.substr( 0, index ) ); keypath = keypath.substr( index + 1 ); } result.push(keypath); return result; } export function unescapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( unescapeKeyPattern, '$1$2' ); } return key; }
const refPattern = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g; const splitPattern = /([^\\](?:\\\\)*)\./; const escapeKeyPattern = /\\|\./g; const unescapeKeyPattern = /((?:\\)+)\1|\\(\.)/g; export function escapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( escapeKeyPattern, '\\$&' ); } return key; } export function normalise ( ref ) { return ref ? ref.replace( refPattern, '.$1' ) : ''; } export function splitKeypath ( keypath ) { let parts = normalise( keypath ).split( splitPattern ), result = []; for ( let i = 0; i < parts.length; i += 2 ) { result.push( parts[i] + ( parts[i + 1] || '' ) ); } return result; } export function unescapeKey ( key ) { if ( typeof key === 'string' ) { return key.replace( unescapeKeyPattern, '$1$2' ); } return key; }
Store and make available the parent object associated with the shadow tile. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@480 542714f4-19e9-0310-aa3c-eee0fc999fb1
// // $Id: ShadowTile.java,v 1.2 2001/10/17 22:22:03 shaper Exp $ package com.threerings.miso.tile; import java.awt.Graphics2D; import java.awt.Shape; /** * The shadow tile extends miso tile to provide an always-impassable * tile that has no display image. Shadow tiles are intended for * placement in the footprint of {@link * com.threerings.media.tile.ObjectTile} objects. */ public class ShadowTile extends MisoTile { /** The scene coordinates of the shadow tile's parent object tile. */ public int ox, oy; /** * Constructs a shadow tile. */ public ShadowTile (int x, int y) { super(SHADOW_TSID, SHADOW_TID); // save the coordinates of our parent object tile ox = x; oy = y; // shadow tiles are always impassable passable = false; } // documentation inherited public void paint (Graphics2D gfx, Shape dest) { // paint nothing as we're naught but a measly shadow of a tile } /** The shadow tile set id. */ protected static final int SHADOW_TSID = -1; /** The shadow tile id. */ protected static final int SHADOW_TID = -1; }
// // $Id: ShadowTile.java,v 1.1 2001/10/13 01:08:59 shaper Exp $ package com.threerings.miso.tile; import java.awt.Graphics2D; import java.awt.Shape; /** * The shadow tile extends miso tile to provide an always-impassable * tile that has no display image. Shadow tiles are intended for * placement in the footprint of {@link ObjectTile} objects. */ public class ShadowTile extends MisoTile { /** Single instantiation of shadow tile for re-use in scenes. */ public static ShadowTile TILE = new ShadowTile(); /** * Constructs a shadow tile. */ public ShadowTile () { super(SHADOW_TSID, SHADOW_TID); // shadow tiles are always impassable passable = false; } // documentation inherited public void paint (Graphics2D gfx, Shape dest) { // paint nothing as we're naught but a measly shadow of a tile } /** The shadow tile set id. */ protected static final int SHADOW_TSID = -1; /** The shadow tile id. */ protected static final int SHADOW_TID = -1; }
Make optional `dependentLocality` and `extraLine`.
<?php namespace SerendipityHQ\Component\ValueObjects\Address\Bridge\Symfony\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CountryType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; /** * @author Adamo Crespi <hello@aerendir.me> */ class AddressType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('countryCode', CountryType::class, ['label' => 'address.form.country_code.label', 'translation_domain' => 'address']) ->add('administrativeArea', TextType::class) ->add('locality', TextType::class) ->add('dependentLocality', TextType::class, ['required' => false]) ->add('postalCode', TextType::class) ->add('street', TextType::class) ->add('extraLine', TextType::class, ['required' => false]); } }
<?php namespace SerendipityHQ\Component\ValueObjects\Address\Bridge\Symfony\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CountryType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; /** * @author Adamo Crespi <hello@aerendir.me> */ class AddressType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('countryCode', CountryType::class, ['label' => 'address.form.country_code.label', 'translation_domain' => 'address']) ->add('administrativeArea', TextType::class) ->add('locality', TextType::class) ->add('dependentLocality', TextType::class) ->add('postalCode', TextType::class) ->add('street', TextType::class) ->add('extraLine', TextType::class); } }
Add scrapi create rename iterable if we want to move to chunks in the fuure
from datetime import datetime import pytz def timestamp(): return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8') def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): for key, val in element.items(): element[key] = copy_to_unicode(val) elif isinstance(element, list): for idx, item in enumerate(element): element[idx] = copy_to_unicode(item) else: try: # A dirty way to convert to unicode in python 2 + 3.3+ element = u''.join(element) except TypeError: pass return element def stamp_from_raw(raw_doc, **kwargs): kwargs['normalizeFinished'] = timestamp() stamps = raw_doc['timestamps'] stamps.update(kwargs) return stamps def format_date_with_slashes(date): return date.strftime('%m/%d/%Y') def create_rename_iterable(documents, source, target, dry): return [(doc, source, target, dry) for doc in documents]
from datetime import datetime import pytz def timestamp(): return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8') def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): for key, val in element.items(): element[key] = copy_to_unicode(val) elif isinstance(element, list): for idx, item in enumerate(element): element[idx] = copy_to_unicode(item) else: try: # A dirty way to convert to unicode in python 2 + 3.3+ element = u''.join(element) except TypeError: pass return element def stamp_from_raw(raw_doc, **kwargs): kwargs['normalizeFinished'] = timestamp() stamps = raw_doc['timestamps'] stamps.update(kwargs) return stamps def format_date_with_slashes(date): return date.strftime('%m/%d/%Y')
Rename short option to avoid conflicts
#!/usr/bin/env node var commander = require('commander'); var proxy = require('./proxy.js'); commander // .version(meta.version) .usage('[options] <endpoint>') .option('-p, --port <n>', 'Local proxy port, default 9200', parseInt) .option('-b, --bindIf <ip>', 'Bind to interface, defaults to 127.0.0.1', /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, '127.0.0.1') .parse(process.argv); if (commander.args.length != 1) { console.error("Missing endpoint parameter"); commander.outputHelp(); process.exit(1); } var endpoint; if (commander.args[0].startsWith('https://')) { endpoint = commander.args[0]; } else { endpoint = 'https://' + commander.args[0]; } var region; try { region = endpoint.match(/\.([^.]+)\.es\.amazonaws\.com\.?$/)[1]; } catch (e) { console.error('Region cannot be parsed from endpoint address'); process.exit(1); } var config = { endpoint: endpoint, region: region, port: commander.port || 9200, bindAddress: commander.bindIf } proxy.run(config);
#!/usr/bin/env node var commander = require('commander'); var proxy = require('./proxy.js'); commander // .version(meta.version) .usage('[options] <endpoint>') .option('-p, --port <n>', 'Local proxy port, default 9200', parseInt) .option('-p, --bindIf <ip>', 'Bind to interface, defaults to 127.0.0.1', /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, '127.0.0.1') .parse(process.argv); if (commander.args.length != 1) { console.error("Missing endpoint parameter"); commander.outputHelp(); process.exit(1); } var endpoint; if (commander.args[0].startsWith('https://')) { endpoint = commander.args[0]; } else { endpoint = 'https://' + commander.args[0]; } var region; try { region = endpoint.match(/\.([^.]+)\.es\.amazonaws\.com\.?$/)[1]; } catch (e) { console.error('Region cannot be parsed from endpoint address'); process.exit(1); } var config = { endpoint: endpoint, region: region, port: commander.port || 9200, bindAddress: commander.bindIf } proxy.run(config);
Remove MP4 from the list of supported filetypes
(function() { "use strict"; function initPage() { var fileTypes = [ "csv", "gif", "htm", "html", "jpeg", "jpg", "mp3", "pdf", "png", "tif", "tiff", "txt", "xml" ]; var list = fileTypes.join(", ").toUpperCase(); var filter = fileTypes.join("|"); // Match any file that doesn't contain the above extensions. var regex = new RegExp("(\.|\/)(" + filter + ")$", "i"); var acceptableFileTypeList = $(".acceptable-file-type-list"); acceptableFileTypeList.text(list); var fileUploadButton = $('#fileupload'); if (fileUploadButton.length > 0) { // If we are on a page with file upload. // Override curation_concern's file filter. We wait until we are sure that the curation_concern has initialized to make sure this gets called last. setTimeout(function() { fileUploadButton.fileupload( 'option', 'acceptFileTypes', regex ); }, 1000); } } $(window).bind('page:change', function() { initPage(); }); })();
(function() { "use strict"; function initPage() { var fileTypes = [ "csv", "gif", "htm", "html", "jpeg", "jpg", "mp3", "mp4", "pdf", "png", "tif", "tiff", "txt", "xml" ]; var list = fileTypes.join(", ").toUpperCase(); var filter = fileTypes.join("|"); // Match any file that doesn't contain the above extensions. var regex = new RegExp("(\.|\/)(" + filter + ")$", "i"); var acceptableFileTypeList = $(".acceptable-file-type-list"); acceptableFileTypeList.text(list); var fileUploadButton = $('#fileupload'); if (fileUploadButton.length > 0) { // If we are on a page with file upload. // Override curation_concern's file filter. We wait until we are sure that the curation_concern has initialized to make sure this gets called last. setTimeout(function() { fileUploadButton.fileupload( 'option', 'acceptFileTypes', regex ); }, 1000); } } $(window).bind('page:change', function() { initPage(); }); })();
Use title property instead of id, since id usually has string constraints (used for URLs). Title is something different that we can make whatever we want
// scripts for header // for capitalizing id String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; // detects scroll for top resizing and lower nav show $(window).scroll(function() { if ($(document).scrollTop() > 50) { $('.main-nav').addClass('shrink'); if ($('#inner-page-links').children().length > 0) { $('.navbar-lower').removeClass('hide-lower'); } } else { $('.main-nav').removeClass('shrink'); $('.navbar-lower').addClass('hide-lower'); } }); // fills in lower nav with inner page links $(document).ready(function(){ $('.accordion-heading').addClass('link'); $('.link').each(function(i, obj) { $("#inner-page-links").append('<li><a href="#" class="scroll-link">'+obj.title.capitalize()+'</a></li>'); }); $(".scroll-link").each(function(i, obj) { $(obj).click(function() { scrollToAnchor(obj.text.toLowerCase()); }); }); if ($('#inner-page-links').children().length < 1) { $('.navbar-lower').addClass('hide-lower'); } }); // for smooth scrolling function scrollToAnchor(aid){ var aTag = $('#'+aid); if(aTag.length){ $('html, body').animate({scrollTop:$(aTag).position().top}, 'slow'); } }
// scripts for header // for capitalizing id String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; // detects scroll for top resizing and lower nav show $(window).scroll(function() { if ($(document).scrollTop() > 50) { $('.main-nav').addClass('shrink'); if ($('#inner-page-links').children().length > 0) { $('.navbar-lower').removeClass('hide-lower'); } } else { $('.main-nav').removeClass('shrink'); $('.navbar-lower').addClass('hide-lower'); } }); // fills in lower nav with inner page links $(document).ready(function(){ $('.accordion-heading').addClass('link'); $('.link').each(function(i, obj) { $("#inner-page-links").append('<li><a href="#" class="scroll-link">'+obj.id.capitalize()+'</a></li>'); }); $(".scroll-link").each(function(i, obj) { $(obj).click(function() { scrollToAnchor(obj.text.toLowerCase()); }); }); if ($('#inner-page-links').children().length < 1) { $('.navbar-lower').addClass('hide-lower'); } }); // for smooth scrolling function scrollToAnchor(aid){ var aTag = $('#'+aid); if(aTag.length){ $('html, body').animate({scrollTop:$(aTag).position().top}, 'slow'); } }
Allow setting of services, mainly for testing purposes.
<?php /** * Encapsulation of model manipulation and business rules */ abstract class Jaded_Service { /** * Singleton instances of services */ protected static $aInstances = array(); //////////////////////////////////////////////////////////////////////////////// // PUBLIC STATIC ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /** * Returns an instance of the requested service * @param string $sType * @return Jaded_Service * @throws Jaded_Service_Exception if the type requested is an invalid service */ public static function instance($sType) { if (empty(self::$aInstances[$sType])) { if (!is_subclass_of($sType, __CLASS__)) { throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType); } self::set($sType, new $sType()); } return self::$aInstances[$sType]; } /** * Set a service instance * @param string $sType * @param Jaded_Service $oService */ public static function set($sType, Jaded_Service $oService) { self::$aInstances[$sType] = $oService; } }
<?php /** * Encapsulation of model manipulation and business rules */ abstract class Jaded_Service { /** * Singleton instances of services */ protected static $aInstances = array(); //////////////////////////////////////////////////////////////////////////////// // PUBLIC STATIC ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /** * Returns an instance of the requested service * @param string $sType * @return Jaded_Service * @throws Jaded_Service_Exception if the type requested is an invalid service */ public static function instance($sType) { if (empty(self::$aInstances[$sType])) { if (!is_subclass_of($sType, __CLASS__)) { throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType); } self::$aInstances[$sType] = new $sType(); } return self::$aInstances[$sType]; } }
Raise error when plugin not configured
# -*- coding: utf8 -*- """Main package for pybossa-z3950.""" from flask import current_app as app from flask.ext.plugins import Plugin from flask.ext.z3950 import Z3950Manager __plugin__ = "PyBossaZ3950" __version__ = "0.0.1" class PyBossaZ3950(Plugin): """A PyBossa plugin for Z39.50 integration.""" def setup(self): """Setup plugin.""" try: if app.config['Z3950_DATABASES']: Z3950Manager.init_app(app) self.setup_blueprint() except Exception as inst: # pragma: no cover print type(inst) print inst.args print inst print "Z39.50 plugin disabled" log_message = 'Z39.50 plugin disabled: %s' % str(inst) app.logger.info(log_message) def setup_blueprint(self): """Setup blueprint.""" from .view import blueprint app.register_blueprint(blueprint, url_prefix="/z3950")
# -*- coding: utf8 -*- """Main package for pybossa-z3950.""" from flask import current_app as app from flask.ext.plugins import Plugin from flask.ext.z3950 import Z3950Manager __plugin__ = "PyBossaZ3950" __version__ = "0.0.1" class PyBossaZ3950(Plugin): """A PyBossa plugin for Z39.50 integration.""" def setup(self): """Setup plugin.""" try: if app.config.get('Z3950_DATABASES'): Z3950Manager.init_app(app) self.setup_blueprint() except Exception as inst: # pragma: no cover print type(inst) print inst.args print inst print "Z39.50 plugin disabled" log_message = 'Z39.50 plugin disabled: %s' % str(inst) app.logger.info(log_message) def setup_blueprint(self): """Setup blueprint.""" from .view import blueprint app.register_blueprint(blueprint, url_prefix="/z3950")
Support CACHE_URL for the Celery broker as well.
import os from datetime import timedelta from cabot.settings_utils import environ_get_list BROKER_URL = environ_get_list(['CELERY_BROKER_URL', 'CACHE_URL']) # Set environment variable if you want to run tests without a redis instance CELERY_ALWAYS_EAGER = os.environ.get('CELERY_ALWAYS_EAGER', False) CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', None) CELERY_IMPORTS = ('cabot.cabotapp.tasks', ) CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml'] CELERYD_TASK_SOFT_TIME_LIMIT = 120 CELERYD_TASK_TIME_LIMIT = 150 CELERYBEAT_SCHEDULE = { 'run-all-checks': { 'task': 'cabot.cabotapp.tasks.run_all_checks', 'schedule': timedelta(seconds=60), }, 'update-shifts': { 'task': 'cabot.cabotapp.tasks.update_shifts', 'schedule': timedelta(seconds=1800), }, 'clean-db': { 'task': 'cabot.cabotapp.tasks.clean_db', 'schedule': timedelta(seconds=60 * 60 * 24), }, } CELERY_TIMEZONE = 'UTC'
import os from datetime import timedelta BROKER_URL = os.environ['CELERY_BROKER_URL'] # Set environment variable if you want to run tests without a redis instance CELERY_ALWAYS_EAGER = os.environ.get('CELERY_ALWAYS_EAGER', False) CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', None) CELERY_IMPORTS = ('cabot.cabotapp.tasks', ) CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERY_TASK_SERIALIZER = "json" CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml'] CELERYD_TASK_SOFT_TIME_LIMIT = 120 CELERYD_TASK_TIME_LIMIT = 150 CELERYBEAT_SCHEDULE = { 'run-all-checks': { 'task': 'cabot.cabotapp.tasks.run_all_checks', 'schedule': timedelta(seconds=60), }, 'update-shifts': { 'task': 'cabot.cabotapp.tasks.update_shifts', 'schedule': timedelta(seconds=1800), }, 'clean-db': { 'task': 'cabot.cabotapp.tasks.clean_db', 'schedule': timedelta(seconds=60 * 60 * 24), }, } CELERY_TIMEZONE = 'UTC'
Fix bug with collector losing last group of input This means the script runner doesn't have to manually finalise the last input, which was always a bit silly. In fact, the whole metaphor is rather silly. I should change it to be "start new group" instead.
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._groups.append(self._current_group) self._current_group.append(new_input) def finalise_group(self): self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._current_group.append(new_input) def finalise_group(self): self._groups.append(self._current_group) self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp
Move Pillow to tests requirements
from setuptools import setup, find_packages import sys install_reqs = [ "decorator>=3.3.2" ] test_reqs = [ "Pillow>=2.5.0" ] if sys.version_info[0] == 2: # simplejson is not python3 compatible install_reqs.append("simplejson>=2.0.9") if [sys.version_info[0], sys.version_info[1]] < [2, 7]: install_reqs.append("argparse>=1.2") setup( name = "dogapi", version = "1.9.1", packages = find_packages("src"), package_dir = {'':'src'}, author = "Datadog, Inc.", author_email = "packages@datadoghq.com", description = "Python bindings to Datadog's API and a user-facing command line tool.", license = "BSD", keywords = "datadog data", url = "http://www.datadoghq.com", install_requires = install_reqs, tests_require = test_reqs, entry_points = { 'console_scripts': [ 'dog = dogshell:main', 'dogwrap = dogshell.wrap:main', ], }, )
from setuptools import setup, find_packages import sys reqs = [ "decorator>=3.3.2", "Pillow>=2.5.0" ] if sys.version_info[0] == 2: # simplejson is not python3 compatible reqs.append("simplejson>=2.0.9") if [sys.version_info[0], sys.version_info[1]] < [2, 7]: reqs.append("argparse>=1.2") setup( name = "dogapi", version = "1.9.1", packages = find_packages("src"), package_dir = {'':'src'}, author = "Datadog, Inc.", author_email = "packages@datadoghq.com", description = "Python bindings to Datadog's API and a user-facing command line tool.", license = "BSD", keywords = "datadog data", url = "http://www.datadoghq.com", install_requires = reqs, entry_points={ 'console_scripts': [ 'dog = dogshell:main', 'dogwrap = dogshell.wrap:main', ], }, )
Add a generic gulp transpile task We can refactor the shared code between different transpilation recipes out into a separate function.
'use strict' var gulp = require('gulp') var del = require('del') var rename = require('gulp-rename') var transpiler = require('./lib/transpilation/transpiler.js') // Config for paths var paths = { assets: 'app/assets/', assets_scss: 'app/assets/scss/', dist: 'dist/', templates: 'app/templates/', npm: 'node_modules/', prototype_scss: 'node_modules/@gemmaleigh/prototype-scss-refactor/**/*.scss' // This can be removed later } var transpileRunner = function (templateLanguage) { return gulp.src(paths.templates + 'govuk_template.html') .pipe(transpiler(templateLanguage)) .pipe(rename({extname: '.html.' + templateLanguage})) .pipe(gulp.dest(paths.dist)) } // Setup tasks // Copy prototype-scss-refactor into app/assets/scss // This step can be removed later once these files exist here gulp.task('copy:prototype-scss-refactor', function () { gulp.src(paths.prototype_scss) .pipe(gulp.dest(paths.assets_scss)) }) gulp.task('clean', function () { return del([paths.dist + '*']) }) gulp.task('transpile', ['transpile:erb', 'transpile:handlebars']) gulp.task('transpile:erb', transpileRunner.bind(null, 'erb')) gulp.task('transpile:handlebars', transpileRunner.bind(null, 'handlebars'))
'use strict' var gulp = require('gulp') var del = require('del') var rename = require('gulp-rename') var transpiler = require('./lib/transpilation/transpiler.js') // Config for paths var paths = { assets: 'app/assets/', assets_scss: 'app/assets/scss/', dist: 'dist/', templates: 'app/templates/', npm: 'node_modules/', prototype_scss: 'node_modules/@gemmaleigh/prototype-scss-refactor/**/*.scss' // This can be removed later } // Setup tasks // Copy prototype-scss-refactor into app/assets/scss // This step can be removed later once these files exist here gulp.task('copy:prototype-scss-refactor', function () { gulp.src(paths.prototype_scss) .pipe(gulp.dest(paths.assets_scss)) }) gulp.task('clean', function () { return del([paths.dist + '*']) }) gulp.task('transpile:erb', function () { var templateLanguage = 'erb' return gulp.src(paths.templates + 'govuk_template.html') .pipe(transpiler(templateLanguage)) .pipe(rename({extname: '.html.' + templateLanguage})) .pipe(gulp.dest(paths.dist)) }) gulp.task('transpile:handlebars', function () { var templateLanguage = 'handlebars' return gulp.src(paths.templates + 'govuk_template.html') .pipe(transpiler(templateLanguage)) .pipe(rename({extname: '.html.' + templateLanguage})) .pipe(gulp.dest(paths.dist)) })
Fix problem with repeating rows. Good data on 3x3.
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 """What is more common: FFFFUUUU, or FFUUUUU, or FFFFFUUU, etc.?""" import pdb from googleapiclient.discovery import build mykey = open('apikey.txt', 'r').read().splitlines()[0] mycx = '001893756405173909803:zmyrda2qwcc' service = build("customsearch", "v1", developerKey=mykey) n = 3 # Max number of Fs or Us. M = [] T = [] for i in range(n): M.append([]) T.append([]) for j in range(n): query = ("f" * (i+1)) + ("u" * (j+1)) res = service.cse().list(q=query, cx=mycx).execute() c = int(res['searchInformation']['totalResults']) M[i].append(c) T[i].append(query) print M print T
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 """What is more common: FFFFUUUU, or FFUUUUU, or FFFFFUUU, etc.?""" import pdb from googleapiclient.discovery import build mykey = open('apikey.txt', 'r').read().splitlines()[0] mycx = '001893756405173909803:zmyrda2qwcc' service = build("customsearch", "v1", developerKey=mykey) n = 3 # Max number of Fs or Us. M = [[None] * (n+1)] * (n+1) for i in range(1, n+1): for j in range(1, n+1): query = ("f" * i) + ("u" * j) res = service.cse().list(q=query, cx=mycx).execute() c = int(res['searchInformation']['totalResults']) M[i][j] = c print M
Build - Pass the major/minor/patch value as an option of the build command
'use strict'; var gulp = require('gulp'); var moment = require('moment'); var fs = require('fs'); var simpleGit = require('simple-git')(); var semver = require('semver'); gulp.task('build', function () { var numberToIncrement = 'patch'; if (process.argv && process.argv[3]) { var option = process.argv[3].replace('--', ''); if (['major', 'minor', 'patch'].indexOf(option) !== -1) { numberToIncrement = option; } } // VERSION var versionFile = fs.readFileSync('package.json').toString().split('\n'); var version = versionFile[3].match(/\w*"version": "(.*)",/)[1]; version = semver.inc(version, numberToIncrement); versionFile[3] = ' "version": "' + version + '",'; fs.writeFileSync('package.json', versionFile.join('\n')); // CHANGELOG var data = fs.readFileSync('CHANGELOG.md').toString().split('\n'); var today = moment().format('YYYY-MM-DD'); data.splice(3, 0, '\n## RELEASE ' + version + ' - ' + today); var text = data.join('\n'); fs.writeFileSync('CHANGELOG.md', text); // COMMIT simpleGit.add(['CHANGELOG.md', 'package.json'], function () { simpleGit.commit('Release ' + version); }); });
'use strict'; var gulp = require('gulp'); var moment = require('moment'); var fs = require('fs'); var simpleGit = require('simple-git')(); var semver = require('semver'); gulp.task('build', function () { // VERSION var versionFile = fs.readFileSync('package.json').toString().split('\n'); var version = versionFile[3].match(/\w*"version": "(.*)",/)[1]; version = semver.inc(version, 'patch'); versionFile[3] = ' "version": "' + version + '",'; fs.writeFileSync('package.json', versionFile.join('\n')); // CHANGELOG var data = fs.readFileSync('CHANGELOG.md').toString().split('\n'); var today = moment().format('YYYY-MM-DD'); data.splice(3, 0, '\n## RELEASE ' + version + ' - ' + today); var text = data.join('\n'); fs.writeFileSync('CHANGELOG.md', text); // COMMIT simpleGit.add(['CHANGELOG.md', 'package.json'], function () { simpleGit.commit('Release ' + version); }); });
Switch .attr() to .prop() for disabling form els Fixes #54 Fixes #56
//= require admin/spree_backend SpreePaypalExpress = { hideSettings: function(paymentMethod) { if (SpreePaypalExpress.paymentMethodID && paymentMethod.val() == SpreePaypalExpress.paymentMethodID) { $('.payment-method-settings').children().hide(); $('#payment_amount').prop('disabled', 'disabled'); $('button[type="submit"]').prop('disabled', 'disabled'); $('#paypal-warning').show(); } else if (SpreePaypalExpress.paymentMethodID) { $('.payment-method-settings').children().show(); $('button[type=submit]').prop('disabled', ''); $('#payment_amount').prop('disabled', '') $('#paypal-warning').hide(); } } } $(document).ready(function() { checkedPaymentMethod = $('#payment-methods input[type="radio"]:checked'); SpreePaypalExpress.hideSettings(checkedPaymentMethod); paymentMethods = $('#payment-methods input[type="radio"]').click(function (e) { SpreePaypalExpress.hideSettings($(e.target)); }); })
//= require admin/spree_backend SpreePaypalExpress = { hideSettings: function(paymentMethod) { if (SpreePaypalExpress.paymentMethodID && paymentMethod.val() == SpreePaypalExpress.paymentMethodID) { $('.payment-method-settings').children().hide(); $('#payment_amount').attr('disabled', 'disabled'); $('button[type="submit"]').attr('disabled', 'disabled'); $('#paypal-warning').show(); } else if (SpreePaypalExpress.paymentMethodID) { $('.payment-method-settings').children().show(); $('button[type=submit]').attr('disabled', ''); $('#payment_amount').attr('disabled', '') $('#paypal-warning').hide(); } } } $(document).ready(function() { checkedPaymentMethod = $('#payment-methods input[type="radio"]:checked'); SpreePaypalExpress.hideSettings(checkedPaymentMethod); paymentMethods = $('#payment-methods input[type="radio"]').click(function (e) { SpreePaypalExpress.hideSettings($(e.target)); }); })
Update to the latest spy API
package org.realityforge.arez.extras.spy; import java.util.Collections; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.arez.spy.ComponentInfo; import org.realityforge.arez.spy.ComputedValueInfo; import org.realityforge.arez.spy.ObservableInfo; import org.realityforge.arez.spy.ObserverInfo; import org.realityforge.guiceyloops.shared.ValueUtil; final class NullObserverInfo implements ObserverInfo { @Override public boolean isRunning() { return false; } @Override public boolean isScheduled() { return false; } @Override public boolean isComputedValue() { return false; } @Override public boolean isReadOnly() { return false; } @Override public ComputedValueInfo asComputedValue() { return null; } @Nonnull @Override public List<ObservableInfo> getDependencies() { return Collections.emptyList(); } @Nullable @Override public ComponentInfo getComponent() { return null; } @Nonnull @Override public String getName() { return ValueUtil.randomString(); } @Override public boolean isDisposed() { return false; } }
package org.realityforge.arez.extras.spy; import java.util.Collections; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.arez.ComputedValue; import org.realityforge.arez.Observable; import org.realityforge.arez.spy.ComponentInfo; import org.realityforge.arez.spy.ObserverInfo; import org.realityforge.guiceyloops.shared.ValueUtil; final class NullObserverInfo implements ObserverInfo { @Override public boolean isRunning() { return false; } @Override public boolean isScheduled() { return false; } @Override public boolean isComputedValue() { return false; } @Override public boolean isReadOnly() { return false; } @Override public ComputedValue<?> asComputedValue() { return null; } @Nonnull @Override public List<Observable<?>> getDependencies() { return Collections.emptyList(); } @Nullable @Override public ComponentInfo getComponent() { return null; } @Nonnull @Override public String getName() { return ValueUtil.randomString(); } @Override public boolean isDisposed() { return false; } }
Add some more props to whitelist
const whitelist = [ 'style', 'className', 'role', 'id', 'autocomplete', 'size', 'tabIndex', 'maxLength', 'name' ]; const whitelistRegex = [/^aria-/, /^data-/, /^on[A-Z]\w+/] export function pick(props, componentClass) { let keys = Object.keys(componentClass.propTypes); let result = {}; Object.keys(props).forEach(key => { if (keys.indexOf(key) === -1) return result[key] = props[key]; }) return result } export function pickElementProps(component) { const props = omitOwn(component); const result = {}; Object.keys(props).forEach(key => { if ( whitelist.indexOf(key) !== -1 || whitelistRegex.some(r => !!key.match(r)) ) result[key] = props[key]; }) return result; } export function omitOwn(component, ...others) { let initial = Object.keys(component.constructor.propTypes); let keys = others.reduce((arr, compClass) => [ ...arr, ...Object.keys(compClass.propTypes)], initial ); let result = {}; Object.keys(component.props).forEach(key => { if (keys.indexOf(key) !== -1) return result[key] = component.props[key]; }) return result }
const whitelist = [ 'style', 'className', 'role', 'id', 'autocomplete', 'size', ]; const whitelistRegex = [/^aria-/, /^data-/, /^on[A-Z]\w+/] export function pick(props, componentClass) { let keys = Object.keys(componentClass.propTypes); let result = {}; Object.keys(props).forEach(key => { if (keys.indexOf(key) === -1) return result[key] = props[key]; }) return result } export function pickElementProps(component) { const props = omitOwn(component); const result = {}; Object.keys(props).forEach(key => { if ( whitelist.indexOf(key) !== -1 || whitelistRegex.some(r => !!key.match(r)) ) result[key] = props[key]; }) return result; } export function omitOwn(component, ...others) { let initial = Object.keys(component.constructor.propTypes); let keys = others.reduce((arr, compClass) => [ ...arr, ...Object.keys(compClass.propTypes)], initial ); let result = {}; Object.keys(component.props).forEach(key => { if (keys.indexOf(key) !== -1) return result[key] = component.props[key]; }) return result }
Fix js error after update
angular.module("protonet.platform").controller("InstallUpdateCtrl", function($scope, $state, $timeout, API, Notification) { function toggleDetailedUpdateStatus() { $scope.showDetailedUpdateStatus = !$scope.showDetailedUpdateStatus; } $scope.toggleDetailedUpdateStatus = toggleDetailedUpdateStatus; function updateDetailedStatus(images) { $scope.status = {}; for (var property in images) { if (images.hasOwnProperty(property)) { var image = images[property]; $scope.status[property] = { local: image.local, remote: image.remote, upToDate: image.local === image.remote } } } $scope.statusAvailable = !$.isEmptyObject($scope.status); } function check() { $timeout(function() { API.get("/admin/api/system/update").then(function(data) { if (data.up_to_date) { Notification.success("Update successfully installed"); $state.go("dashboard.index"); } else { updateDetailedStatus(data.images); check(); } }).catch(check); }, 10000); } check(); });
angular.module("protonet.platform").controller("InstallUpdateCtrl", function($scope, $state, $timeout, API, Notification) { function toggleDetailedUpdateStatus() { $scope.showDetailedUpdateStatus = !$scope.showDetailedUpdateStatus; } $scope.toggleDetailedUpdateStatus = toggleDetailedUpdateStatus; function updateDetailedStatus(images) { $scope.status = {}; for (var property in images) { if (images.hasOwnProperty(property)) { var image = images[property]; $scope.status[property] = { local: image.local, remote: image.remote, upToDate: image.local === image.remote } } } $scope.statusAvailable = !$.isEmptyObject($scope.status); } function check() { $timeout(function() { API.get("/admin/api/system/update").then(function(data) { if (data.up_to_date) { Notification.notice("Update successfully installed"); $state.go("dashboard.index"); } else { updateDetailedStatus(data.images); check(); } }).catch(check); }, 10000); } check(); });
Include pip as required install
# -*- coding: utf-8 -*- """setup.py: setuptools control.""" import re from setuptools import setup, find_packages import pip version = re.search( '^__version__\s*=\s*"(.*)"', open('src/bslint.py').read(), re.M ).group(1) with open("README.rst", "rb") as f: long_descr = f.read().decode("utf-8") pip.main(['install', 'pyenchant']) setup( name = "bslint", packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), package_dir={'src': 'src'}, package_data={'src': ['config/*.json']}, entry_points = { "console_scripts": ['bslint = src.bslint:main']}, version = version, description = "A linter tool for the BrightScript language.", long_description = long_descr, author = "BSLint", author_email = "zachary.robinson@sky.uk", url = "https://github.com/sky-uk/roku-linter", download_url = 'https://github.com/sky-uk/bslint/archive/0.2.2.tar.gz', install_requires=['pip'] )
# -*- coding: utf-8 -*- """setup.py: setuptools control.""" import re from setuptools import setup, find_packages import pip version = re.search( '^__version__\s*=\s*"(.*)"', open('src/bslint.py').read(), re.M ).group(1) with open("README.rst", "rb") as f: long_descr = f.read().decode("utf-8") pip.main(['install', 'pyenchant']) setup( name = "bslint", packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), package_dir={'src': 'src'}, package_data={'src': ['config/*.json']}, entry_points = { "console_scripts": ['bslint = src.bslint:main']}, version = version, description = "A linter tool for the BrightScript language.", long_description = long_descr, author = "BSLint", author_email = "zachary.robinson@sky.uk", url = "https://github.com/sky-uk/roku-linter", download_url = 'https://github.com/sky-uk/bslint/archive/0.2.2.tar.gz', )
Add pytest-watch to console scripts to match the name.
import os from setuptools import setup, find_packages def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() setup( name='pytest-watch', version='3.1.0', description='Local continuous test runner with pytest and watchdog.', long_description=read('README.md'), author='Joe Esposito', author_email='joe@joeyespo.com', url='http://github.com/joeyespo/pytest-watch', license='MIT', platforms='any', packages=find_packages(), install_requires=read('requirements.txt').splitlines(), entry_points={ 'console_scripts': [ 'py.test.watch = pytest_watch.command:main', 'pytest-watch = pytest_watch.command:main', 'ptw = pytest_watch.command:main', ] }, )
import os from setuptools import setup, find_packages def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() setup( name='pytest-watch', version='3.1.0', description='Local continuous test runner with pytest and watchdog.', long_description=read('README.md'), author='Joe Esposito', author_email='joe@joeyespo.com', url='http://github.com/joeyespo/pytest-watch', license='MIT', platforms='any', packages=find_packages(), install_requires=read('requirements.txt').splitlines(), entry_points={ 'console_scripts': [ 'py.test.watch = pytest_watch.command:main', 'ptw = pytest_watch.command:main', ] }, )
Tweak hamming test suite in Go
package hamming import ( "testing" ) var testCases = []struct { expected int strandA, strandB string description string }{ {0, "", "", "no difference between empty strands"}, {2, "AG", "CT", "complete hamming distance for small strands"}, {0, "A", "A", "no difference between identical strands"}, {1, "A", "G", "complete distance for single nucleotide strands"}, {1, "AT", "CT", "small hamming distance"}, {1, "GGACG", "GGTCG", "small hamming distance in longer strands"}, {0, "AAAG", "AAA", "ignores extra length on first strand when longer"}, {0, "AAA", "AAAG", "ignores extra length on second strand when longer"}, {4, "GATACA", "GCATAA", "large hamming distance"}, {9, "GGACGGATTCTG", "AGGACGGATTCT", "hamming distance in very long strands"}, } func TestHamming(t *testing.T) { for _, tc := range testCases { observed := Distance(tc.strandA, tc.strandB) if tc.expected != observed { t.Fatalf(`%s: {%v,%v} expected: %v observed: %v`, tc.description, tc.strandA, tc.strandB, tc.expected, observed, ) } } }
package hamming import ( "testing" ) var testCases = []struct { expected int strandA, strandB string description string }{ {0, "", "", "no difference between empty strands"}, {2, "AG", "CT", "complete hamming distance for small strand"}, {0, "A", "A", "no difference between identical strands"}, {1, "A", "G", "complete distance for single nucleotide strand"}, {1, "AT", "CT", "small hamming distance"}, {1, "GGACG", "GGTCG", "small hamming distance in longer strand"}, {0, "AAAG", "AAA", "ignores extra length on first strand when longer"}, {0, "AAA", "AAAG", "ignores extra length on second strand when longer"}, {4, "GATACA", "GCATAA", "large hamming distance"}, {9, "GGACGGATTCTG", "AGGACGGATTCT", "hamming distance in very long strand"}, } func TestHamming(t *testing.T) { for _, tc := range testCases { observed := Distance(tc.strandA, tc.strandB) if tc.expected != observed { t.Fatalf(`%s: expected: %v observed: %v`, tc.description, tc.expected, observed, ) } } }
Remove comment because environment variable should be applied.
"use strict"; var fs = require("fs"); var path = require("path"); var Sequelize = require("sequelize"); var env = process.env.NODE_ENV || "production"; var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env]; var sequelize = new Sequelize(config.database, config.username, config.password, config); var db = {}; fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf(".") !== 0) && (file !== "index.js"); }) .forEach(function(file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if ("associate" in db[modelName]) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db; /* play.js "use strict"; module.exports = function(sequelize, DataTypes) { var Play = sequelize.define("Play", { }, { comment : "Play table connect user A and room B so it means A joined B.", classMethods: { associate: function(models) { Play.belongsTo(models.User, {foreignkey: 'username'}); Play.belongsTo(models.Room, {foreignkey: 'roomid'}); } } }); return Play; }; */
"use strict"; var fs = require("fs"); var path = require("path"); var Sequelize = require("sequelize"); var env = /*process.env.NODE_ENV || */"production"; var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env]; var sequelize = new Sequelize(config.database, config.username, config.password, config); var db = {}; fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf(".") !== 0) && (file !== "index.js"); }) .forEach(function(file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if ("associate" in db[modelName]) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db; /* play.js "use strict"; module.exports = function(sequelize, DataTypes) { var Play = sequelize.define("Play", { }, { comment : "Play table connect user A and room B so it means A joined B.", classMethods: { associate: function(models) { Play.belongsTo(models.User, {foreignkey: 'username'}); Play.belongsTo(models.Room, {foreignkey: 'roomid'}); } } }); return Play; }; */
Revert "Temp debugging for weird provider bug" This reverts commit 328ce1303977ea296157995b14298e084ac5f6f8.
"use strict"; var restify = require('restify'); var async = require('async'); var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { if(!req.query.context) { return next(new restify.ConflictError("Missing query parameter")); } async.waterfall([ function getDocuments(cb) { var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments({ search: req.query.context, render_templates: true, sort: "-modificationDate" }, cb); }, function remapDocuments(documentsRes, cb) { res.send(200, documentsRes.body.data.map(function mapDocuments(document) { return { type: document.document_type.name, provider: document.provider.client.name, documentId: document.id, date: document.modification_date, snippet: document.rendered_snippet, title: document.rendered_title }; })); cb(); } ], next); };
"use strict"; var restify = require('restify'); var async = require('async'); var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { if(!req.query.context) { return next(new restify.ConflictError("Missing query parameter")); } async.waterfall([ function getDocuments(cb) { var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments({ search: req.query.context, render_templates: true, sort: "-modificationDate" }, cb); }, function remapDocuments(documentsRes, cb) { var documents = documentsRes.body.data.map(function mapDocuments(document) { return { type: document.document_type.name, provider: document.provider.client.name, documentId: document.id, date: document.modification_date, snippet: document.rendered_snippet, title: document.rendered_title }; }); console.log(JSON.stringify(documents, null, 2)); res.send(200, documents); cb(); } ], next); };
Check if epages6 settings are configured
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jonas Gratz # Copyright (c) 2015 Jonas Gratz # # License: MIT # """This module exports the Tlec plugin class.""" import sublime from SublimeLinter.lint import Linter, util class Tlec(Linter): """Provides an interface to tlec.""" def cmd(self): if self.view.settings().get('ep6vm'): return [self.executable_path, sublime.packages_path() + '/Epages6/ep6-tools.py', '--vm', self.view.settings().get('ep6vm')['vm'], '--lint', '--file', self.view.file_name(), '--user', 'root', '--password', 'qwert6', '--ignore-me', '@']; else: return [] executable = 'python3' syntax = ('html', 'tle') regex = r'(?P<message>.+?) at line (?P<line>\d+)(, near (?P<near>.+?))?' error_stream = util.STREAM_BOTH tempfile_suffix = 'html'
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jonas Gratz # Copyright (c) 2015 Jonas Gratz # # License: MIT # """This module exports the Tlec plugin class.""" import sublime from SublimeLinter.lint import Linter, util class Tlec(Linter): """Provides an interface to tlec.""" def cmd(self): return [self.executable_path, sublime.packages_path() + '/Epages6/ep6-tools.py', '--vm', self.view.settings().get('ep6vm')['vm'], '--lint', '--file', self.view.file_name(), '--user', 'root', '--password', 'qwert6', '--ignore-me', '@']; executable = 'python3' syntax = ('html', 'tle') regex = r'(?P<message>.+?) at line (?P<line>\d+)(, near (?P<near>.+?))?' error_stream = util.STREAM_BOTH tempfile_suffix = 'html'
Make serializable the named beans
package org.ligoj.bootstrap.core; import java.io.Serializable; /** * A named and identified bean * * @param <K> * The type of the identifier */ public interface INamableBean<K extends Serializable> extends Comparable<INamableBean<K>>, Serializable { /** * Bean name. * * @return human readable name. */ String getName(); /** * Bean identifier. * * @return identifier. */ K getId(); /** * Set the bean name. * * @param name * The new name. */ void setName(String name); /** * Set the bean identifier. * * @param id * The new identifier. */ void setId(K id); @Override default int compareTo(final INamableBean<K> o) { return getName().compareToIgnoreCase(o.getName()); } }
package org.ligoj.bootstrap.core; import java.io.Serializable; /** * A named and identified bean * * @param <K> * The type of the identifier */ public interface INamableBean<K extends Serializable> extends Comparable<INamableBean<K>> { /** * Bean name. * * @return human readable name. */ String getName(); /** * Bean identifier. * * @return identifier. */ K getId(); /** * Set the bean name. * * @param name * The new name. */ void setName(String name); /** * Set the bean identifier. * * @param id * The new identifier. */ void setId(K id); @Override default int compareTo(final INamableBean<K> o) { return getName().compareToIgnoreCase(o.getName()); } }
Switch logic of if statement
<?php namespace Distil; use Distil\Exceptions\CannotCreateCriterion; final class CriterionFactory { /** * @var array */ private $criteriaResolvers; public function __construct(array $criteriaResolvers = []) { $this->criteriaResolvers = $criteriaResolvers; } public function createByName(string $name, ...$arguments): Criterion { $criterion = $this->resolver($name); if (is_callable($criterion)) { return call_user_func_array($criterion, $arguments); } return new $criterion(...$arguments); } private function resolver(string $name): string { if (! array_key_exists($name, $this->criteriaResolvers)) { throw CannotCreateCriterion::missingResolver($name, array_keys($this->criteriaResolvers)); } return $this->criteriaResolvers[$name]; } }
<?php namespace Distil; use Distil\Exceptions\CannotCreateCriterion; final class CriterionFactory { /** * @var array */ private $criteriaResolvers; public function __construct(array $criteriaResolvers = []) { $this->criteriaResolvers = $criteriaResolvers; } public function createByName(string $name, ...$arguments): Criterion { $criterion = $this->resolver($name); if (is_callable($criterion)) { return call_user_func_array($criterion, $arguments); } return new $criterion(...$arguments); } private function resolver(string $name): string { if (array_key_exists($name, $this->criteriaResolvers)) { return $this->criteriaResolvers[$name]; } throw CannotCreateCriterion::missingResolver($name, array_keys($this->criteriaResolvers)); } }
Clean up. Comments for running in prod and dev
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import { LeaderBoard } from './components/LeaderBoard'; // import registerServiceWorker from './registerServiceWorker'; // Uncomment this to build for production export default { DEConfig: null, config: (config) => { this.DEConfig = config; }, components: { leaderboard: { new: (config) => { return { render: (args) => { ReactDOM.render( <LeaderBoard selector={config.selector || this.DEConfig.selector} />, document.querySelector(config.selector) ) } } } } // Add another component here } } // Uncomment this to run locally // ReactDOM.render(<LeaderBoard />, document.getElementById('root')); // registerServiceWorker();
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import { LeaderBoard } from './components/LeaderBoard'; // import registerServiceWorker from './registerServiceWorker'; export default { DEConfig: null, config: (config) => { this.DEConfig = config; }, components: { leaderboard: { new: (config) => { return { render: (args) => { ReactDOM.render( <LeaderBoard selector={config.selector || this.DEConfig.selector} />, document.querySelector(config.selector) ) } } } } } } // ReactDOM.render(<LeaderBoard />, document.getElementById('root')); // registerServiceWorker();
Replace maps with fors to improve performance.
'use strict' const crypto = require('crypto') // Delimeter to separate object items form each other // when stringifying const DELIM = '|' /** * Stringifies a JSON object (not any randon JS object). * * It should be noted that JS objects can have members of * specific type (e.g. function), that are not supported * by JSON. * * @param {Object} obj JSON object * @returns {String} stringified JSON object. */ function stringify (obj) { if (Array.isArray(obj)) { let stringifiedArr = [] for (let i = 0; i < obj.length; i++) { stringifiedArr[i] = stringify(obj[i]) } return JSON.stringify(stringifiedArr) } else if (typeof obj === 'object' && obj !== null) { let acc = [] let sortedKeys = Object.keys(obj).sort() for (let i = 0; i < sortedKeys.length; i++) { let k = sortedKeys[i] acc[i] = `${k}:${stringify(obj[k])}` } return acc.join(DELIM) } return obj } /** * Creates hash of given JSON object. * * @param {Object} obj JSON object * @param {String} hashAlgorithm hash algorithm (e.g. SHA256) * @param {String} encoding hash encoding (e.g. base64) or none for buffer * @see #stringify */ function digest (obj, hashAlgorithm, encoding) { let hash = crypto.createHash(hashAlgorithm) return hash.update(stringify(obj)).digest(encoding) } module.exports = { stringify: stringify, digest: digest }
'use strict' const crypto = require('crypto') // Delimeter to separate object items form each other // when stringifying const DELIM = '|' /** * Stringifies a JSON object (not any randon JS object). * * It should be noted that JS objects can have members of * specific type (e.g. function), that are not supported * by JSON. * * @param {Object} obj JSON object * @returns {String} stringified JSON object. */ function stringify (obj) { if (Array.isArray(obj)) { return JSON.stringify(obj.map(i => stringify(i))) } else if (typeof obj === 'object' && obj !== null) { return Object.keys(obj) .sort() .map(k => `${k}:${stringify(obj[k])}`) .join(DELIM) } return obj } /** * Creates hash of given JSON object. * * @param {Object} obj JSON object * @param {String} hashAlgorithm hash algorithm (e.g. SHA256) * @param {String} encoding hash encoding (e.g. base64) or none for buffer * @see #stringify */ function digest (obj, hashAlgorithm, encoding) { let hash = crypto.createHash(hashAlgorithm) return hash.update(stringify(obj)).digest(encoding) } module.exports = { stringify: stringify, digest: digest }
Add debug for curl response
<?php /* * This file is part of the yandex-pdd-api project. * * (c) AmaxLab 2017 <http://www.amaxlab.ru> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace AmaxLab\YandexPddApi\Curl; /** * @author Egor Zyuskin <ezyuskin@amaxlab.ru> */ class CurlResponse { const STATUS_CODE_OK = 200; /** * @var string */ private $content; /** * @var int */ private $statusCode; /** * @param int $statusCode * @param string $content */ public function __construct($statusCode, $content) { //print $content; $this->statusCode = $statusCode; $this->content = $content; } /** * @return string */ public function getContent() { return $this->content; } /** * @return int */ public function getStatusCode() { return $this->statusCode; } /** * @return object */ public function getJson() { return json_decode($this->getContent()); } }
<?php /* * This file is part of the yandex-pdd-api project. * * (c) AmaxLab 2017 <http://www.amaxlab.ru> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace AmaxLab\YandexPddApi\Curl; /** * @author Egor Zyuskin <ezyuskin@amaxlab.ru> */ class CurlResponse { const STATUS_CODE_OK = 200; /** * @var string */ private $content; /** * @var int */ private $statusCode; /** * @param int $statusCode * @param string $content */ public function __construct($statusCode, $content) { $this->statusCode = $statusCode; $this->content = $content; } /** * @return string */ public function getContent() { return $this->content; } /** * @return int */ public function getStatusCode() { return $this->statusCode; } /** * @return object */ public function getJson() { return json_decode($this->getContent()); } }
Update deployed settings to access mysql.
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' with open(os.path.join(BASE_DIR, 'secrets/database_password.txt')) as f: DB_PASSWORD = f.read().strip() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'osler', 'USER': 'django', 'PASSWORD': DB_PASSWORD, 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } }
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
Rearrange synchronized, try-catch and while-loop blocks
package ru.nsu.ccfit.bogush.factory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SimplePeriodical implements Periodical { private long period; private static final String LOGGER_NAME = "SimplePeriodical"; private static final Logger logger = LogManager.getLogger(LOGGER_NAME); public SimplePeriodical(long period) { this.period = period; } private final Object lock = new Object(); @Override public void setPeriod(long period) { logger.trace("set period " + period + " milliseconds"); if (period < 0) { logger.error("period < 0"); throw new IllegalArgumentException("period must be greater than or equal to 0"); } this.period = period; lock.notifyAll(); } @Override public void waitPeriod() { long timeToWait = period; while (timeToWait > 0) { long time = System.currentTimeMillis(); try { synchronized (lock) { lock.wait(timeToWait); timeToWait -= System.currentTimeMillis() - time; } } catch (InterruptedException e) { e.printStackTrace(); logger.error(e); System.exit(1); } } } @Override public long getPeriod() { return period; } }
package ru.nsu.ccfit.bogush.factory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SimplePeriodical implements Periodical { private long period; private static final String LOGGER_NAME = "SimplePeriodical"; private static final Logger logger = LogManager.getLogger(LOGGER_NAME); public SimplePeriodical(long period) { this.period = period; } private final Object lock = new Object(); @Override public void setPeriod(long period) { logger.trace("set period " + period + " milliseconds"); if (period < 0) { logger.error("period < 0"); throw new IllegalArgumentException("period must be greater than or equal to 0"); } this.period = period; lock.notifyAll(); } @Override public void waitPeriod() { long timeToWait = period; long time = System.currentTimeMillis(); try { synchronized (lock) { while (timeToWait > 0) { lock.wait(timeToWait); long newTime = System.currentTimeMillis(); timeToWait -= newTime - time; time = newTime; } } } catch (InterruptedException e) { e.printStackTrace(); logger.error(e); System.exit(1); } } @Override public long getPeriod() { return period; } }
Refactor tests to (hopefully) pass the build on 0.10
import React from 'react'; import TestUtils from 'react/lib/ReactTestUtils'; import Animator from '../Animator.jsx'; const animate = new Animator(); const SimpleComponent = React.createClass({ render: function(){ return ( <div></div> ); } }); describe('Animator', function() { describe('animate()', function() { it('should successfully create a renderable component', function() { let component = null; after(function() { React.unmountComponentAtNode(React.findDOMNode(component).parentNode); }); expect(() => { const AnimatedSimpleComponent = animate(SimpleComponent, () => {}); component = TestUtils.renderIntoDocument(<AnimatedSimpleComponent />); }).to.not.throw(); }); }); });
import React from 'react/addons'; import Animator from '../Animator.jsx'; const TestUtils = React.addons.TestUtils; const animate = new Animator(); const SimpleComponent = React.createClass({ render: function(){ return ( <div></div> ); } }); describe('Animator', function() { describe('animate()', function() { it('should successfully create a renderable component', function() { let component = null; after(function() { React.unmountComponentAtNode(React.findDOMNode(component).parentNode); }); expect(() => { const AnimatedSimpleComponent = animate(SimpleComponent, () => {}); component = TestUtils.renderIntoDocument(<AnimatedSimpleComponent />); }).to.not.throw(); }); }); });
Use this.import instead of app.import
/* jshint node: true */ // jscs: disable 'use strict'; module.exports = { name: 'ember-l10n', isDevelopingAddon: function() { // @see: https://ember-cli.com/extending/#link-to-addon-while-developing return false; // Set this to true for local development }, includedCommands: function() { return { 'l10n:install': require('./lib/commands/install'), 'l10n:extract': require('./lib/commands/extract'), 'l10n:convert': require('./lib/commands/convert'), 'l10n:sync': require('./lib/commands/sync') }; }, included: function(app) { this._super.included(app); var bowerDirectory = app.bowerDirectory || 'bower_components'; this.import(bowerDirectory + '/gettext.js/dist/gettext.min.js', { exports: { 'i18n': [ 'default' ] } }); } };
/* jshint node: true */ // jscs: disable 'use strict'; module.exports = { name: 'ember-l10n', isDevelopingAddon: function() { // @see: https://ember-cli.com/extending/#link-to-addon-while-developing return false; // Set this to true for local development }, includedCommands: function() { return { 'l10n:install': require('./lib/commands/install'), 'l10n:extract': require('./lib/commands/extract'), 'l10n:convert': require('./lib/commands/convert'), 'l10n:sync': require('./lib/commands/sync') }; }, included: function(app) { this._super.included(app); // Fix for loading it in addons/engines if (typeof app.import !== 'function' && app.app) { app = app.app; } app.import(app.bowerDirectory + '/gettext.js/dist/gettext.min.js', { exports: { 'i18n': [ 'default' ] } }); } };
Fix image model in migration
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-24 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion from wapps.utils import get_image_model class Migration(migrations.Migration): dependencies = [ ('wapps', '0015_identitysettings_amp_logo'), ] operations = [ migrations.AlterField( model_name='identitysettings', name='amp_logo', field=models.ForeignKey(blank=True, help_text='An mobile optimized logo that must be 600x60', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=get_image_model(), verbose_name='Mobile Logo'), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-24 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wapps', '0015_identitysettings_amp_logo'), ] operations = [ migrations.AlterField( model_name='identitysettings', name='amp_logo', field=models.ForeignKey(blank=True, help_text='An mobile optimized logo that must be 600x60', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wapps.WappsImage', verbose_name='Mobile Logo'), ), ]
Set audio quality default value
import {merge, pick} from 'lodash' const kStorageKey = 'wukong' export function open(state = {}) { try { return merge({ user: { preferences: { listenOnly: false, connection: 0, audioQuality: 2, theme: 0 } } }, JSON.parse(localStorage.getItem(kStorageKey)), state) } catch (error) { return state } } export function save(state = {}) { try { localStorage.setItem(kStorageKey, JSON.stringify(pick(state, [ 'user.preferences', 'song.playlist', 'player.volume' ]))) } catch (error) { localStorage.removeItem(kStorageKey) } }
import {merge, pick} from 'lodash' const kStorageKey = 'wukong' export function open(state = {}) { try { return merge({ user: { preferences: { listenOnly: false, connection: 0, audioQuality: 0, theme: 0 } } }, JSON.parse(localStorage.getItem(kStorageKey)), state) } catch (error) { return state } } export function save(state = {}) { try { localStorage.setItem(kStorageKey, JSON.stringify(pick(state, [ 'user.preferences', 'song.playlist', 'player.volume' ]))) } catch (error) { localStorage.removeItem(kStorageKey) } }
Use 2to3 for Python 3
#!/usr/bin/env python from distutils.core import setup setup(name='natural', version='0.1.4', description='Convert data to their natural (human-readable) format', long_description=''' Example Usage ============= Basic usage:: >>> from natural.file import accessed >>> print accessed(__file__) just now We speak your language (with `your support`_):: >>> import locale >>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL') >>> print accessed(__file__) zojuist Bugs/Features ============= You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues Documentation ============= The project documentation can be found at http://natural.rtfd.org/ .. _your support: http://natural.readthedocs.org/en/latest/locales.html ''', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', license='MIT', keywords='natural data date file number size', url='https://github.com/tehmaze/natural', packages=['natural'], package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']}, use_2to3=True, )
#!/usr/bin/env python from distutils.core import setup setup(name='natural', version='0.1.4', description='Convert data to their natural (human-readable) format', long_description=''' Example Usage ============= Basic usage:: >>> from natural.file import accessed >>> print accessed(__file__) just now We speak your language (with `your support`_):: >>> import locale >>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL') >>> print accessed(__file__) zojuist Bugs/Features ============= You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues Documentation ============= The project documentation can be found at http://natural.rtfd.org/ .. _your support: http://natural.readthedocs.org/en/latest/locales.html ''', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', license='MIT', keywords='natural data date file number size', url='https://github.com/tehmaze/natural', packages=['natural'], package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']}, )
Add missing use statement for SoftDeletes
<?php namespace RadDB; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class MachineSurveyData extends Model { use SoftDeletes; /** * The table associated with the model. * * @var string */ protected $table = 'machine_surveydata'; /** * Attributes that are mass assignable. * * @var array */ protected $fillable = [ 'machine_id', 'survey_id', 'gendata', 'collimatordata', 'radoutputdata', 'radsurveydata', 'hvldata', 'fluorodata', 'maxfluorodata', 'receptorentrance', ]; /** * Attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'deleted_at', 'created_at', 'updated_at', ]; /** * Relationships */ public function machine() { return $this->belongsTo('RadDB\Machine'); } public function survey() { return $this->belongsTo('RadDB\TestDate'); } }
<?php namespace RadDB; use Illuminate\Database\Eloquent\Model; class MachineSurveyData extends Model { use SoftDeletes; /** * The table associated with the model. * * @var string */ protected $table = 'machine_surveydata'; /** * Attributes that are mass assignable. * * @var array */ protected $fillable = [ 'machine_id', 'survey_id', 'gendata', 'collimatordata', 'radoutputdata', 'radsurveydata', 'hvldata', 'fluorodata', 'maxfluorodata', 'receptorentrance', ]; /** * Attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'deleted_at', 'created_at', 'updated_at', ]; /** * Relationships */ public function machine() { return $this->belongsTo('RadDB\Machine'); } public function survey() { return $this->belongsTo('RadDB\TestDate'); } }
Fix issue of login button leading to unwanted website
import React from 'react'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import SVGNavMenu from 'material-ui/svg-icons/navigation/menu'; import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import Avatar from 'material-ui/Avatar'; import ListItem from 'material-ui/List/ListItem'; const Navigation = props => { const RightArea = !props.userData ? <FlatButton label="Login to Chat" secondary={true} icon={<FontIcon className="fa fa-twitch" />} /> : <ListItem disabled={true} leftAvatar={ <Avatar src={props.userData.image} /> } > {props.userData.name} </ListItem>; return ( <AppBar title={props.title} onLeftIconButtonTouchTap={props.onLeftIconClicked} onRightIconButtonTouchTap={props.onRightIconClicked} iconElementLeft={<IconButton><SVGNavMenu /></IconButton>} iconElementRight={RightArea} /> ); }; export default Navigation;
import React from 'react'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import SVGNavMenu from 'material-ui/svg-icons/navigation/menu'; import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import Avatar from 'material-ui/Avatar'; import ListItem from 'material-ui/List/ListItem'; const Navigation = props => { const RightArea = !props.userData ? <FlatButton href="https://github.com/callemall/material-ui" target="_blank" label="Login to Chat" secondary={true} icon={<FontIcon className="fa fa-twitch" />} /> : <ListItem disabled={true} leftAvatar={ <Avatar src={props.userData.image} /> } > {props.userData.name} </ListItem>; return ( <AppBar title={props.title} onLeftIconButtonTouchTap={props.onLeftIconClicked} onRightIconButtonTouchTap={props.onRightIconClicked} iconElementLeft={<IconButton><SVGNavMenu /></IconButton>} iconElementRight={RightArea} /> ); }; export default Navigation;
Fix potential null pointer exception on runtimes without name
/* * Copyright 2020 Martin Winandy * * 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.tinylog.core.runtime; /** * Provider for acquiring the appropriate {@link RuntimeFlavor} for the actual virtual machine. */ public final class RuntimeProvider { /** */ public RuntimeProvider() { } /** * Provides the appropriate {@link RuntimeFlavor} for the actual virtual machine. * * @return An appropriate runtime instance */ public RuntimeFlavor getRuntime() { if ("Android Runtime".equals(System.getProperty("java.runtime.name"))) { return new AndroidRuntime(); } else { return new JavaRuntime(); } } }
/* * Copyright 2020 Martin Winandy * * 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.tinylog.core.runtime; /** * Provider for acquiring the appropriate {@link RuntimeFlavor} for the actual virtual machine. */ public final class RuntimeProvider { /** */ public RuntimeProvider() { } /** * Provides the appropriate {@link RuntimeFlavor} for the actual virtual machine. * * @return An appropriate runtime instance */ public RuntimeFlavor getRuntime() { if (System.getProperty("java.runtime.name").equals("Android Runtime")) { return new AndroidRuntime(); } else { return new JavaRuntime(); } } }
Add new serializer for StatAdd that doesn't have activity
# from django.contrib.auth.models import User from rest_framework import serializers from .models import Activity, Stat class StatAddSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Stat fields = ('id', 'reps', 'date') class StatSerializer(StatAddSerializer): class Meta: model = Stat fields = tuple(list(StatAddSerializer.Meta.fields) + ['activity']) def create(self, validated_data): validated_data['activity'] = self.context['activity'] stat = Stat.objects.create(**validated_data) return stat class ActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Activity fields = ('id', 'full_description', 'units', 'url') class ActivityListSerializer(ActivitySerializer): stats = StatSerializer(many=True, read_only=True) class Meta: model = Activity fields = tuple(list(ActivitySerializer.Meta.fields) + ['stats']) # class UserSerializer(serializers.HyperlinkedModelSerializer): # # class Meta: # model = User # fields = ('id', 'username', 'email', 'activities')
# from django.contrib.auth.models import User from rest_framework import serializers from .models import Activity, Stat class StatSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Stat fields = ('id', 'activity', 'reps', 'date') def create(self, validated_data): validated_data['activity'] = self.context['activity'] stat = Stat.objects.create(**validated_data) return stat class ActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Activity fields = ('id', 'full_description', 'units', 'url') class ActivityListSerializer(ActivitySerializer): stats = StatSerializer(many=True, read_only=True) class Meta: model = Activity fields = tuple(list(ActivitySerializer.Meta.fields) + ['stats']) # class UserSerializer(serializers.HyperlinkedModelSerializer): # # class Meta: # model = User # fields = ('id', 'username', 'email', 'activities')
Add automatic test for utils
'use strict'; var should = require('should'); var utils = require('./utilsCtrl.js'); describe('utils module tests', function() { it('should find list with some id', function(done) { var lists = { listContainer1: [ {id: 'idlist1'}, {id: 'idlist2'}, {id: 'idlist3'} ], listContainer2: [ {id: 'idlist4'}, {id: 'idlist5'}, {id: 'idlist6'} ], listContainer3: [ {id: 'idlist7'}, {id: 'idlist8'}, {id: 'idlist9'} ] }; var successSearch = utils.searchList('idlist8', lists); var falseSearch = utils.searchList('idlist10', lists); should(successSearch).be.ok(); should(falseSearch).not.be.ok(); done(); }); it('should get diff of dates', function(done) { var dateDiff = utils.getDateDiff('2016-01-08', '2016-01-10'); should(dateDiff).be.eql(172800000); done(); }); it('should convert unix date to human readable date', function(done) { var unixDate = 172800000; var humanReadable = utils.getHumanReadableTime(unixDate); should(humanReadable).have.property('time'); should(humanReadable).have.property('format'); should(humanReadable.time).be.eql(2); should(humanReadable.format).be.eql('days'); done(); }); });
'use strict'; var should = require('should'); var utils = require('./utilsCtrl.js'); describe('utilsCtrl tests', function() { it('should find list with some id', function(done) { var lists = { listContainer1: [ {id: 'idlist1'}, {id: 'idlist2'}, {id: 'idlist3'} ], listContainer2: [ {id: 'idlist4'}, {id: 'idlist5'}, {id: 'idlist6'} ], listContainer3: [ {id: 'idlist7'}, {id: 'idlist8'}, {id: 'idlist9'} ] }; var successSearch = utils.searchList('idlist8', lists); var falseSearch = utils.searchList('idlist10', lists); should(successSearch).be.ok(); should(falseSearch).not.be.ok(); done(); }); it('should get diff of dates', function(done) { var dateDiff = utils.getDateDiff('2016-01-08', '2016-01-10'); should(dateDiff).be.eql(172800000); done(); }); });
Add asciidoc as markup grammar
/* @flow */ import { Disposable } from 'atom'; import ReactDOM from 'react-dom'; import store from './store'; export function reactFactory( reactElement: React$Element<any>, domElement: HTMLElement, additionalTeardown: Function = () => {}, disposer: atom$CompositeDisposable = store.subscriptions, ) { ReactDOM.render(reactElement, domElement); const disposable = new Disposable(() => { ReactDOM.unmountComponentAtNode(domElement); additionalTeardown(); }); disposer.add(disposable); } export function grammarToLanguage(grammar: ?atom$Grammar) { return (grammar) ? grammar.name.toLowerCase() : null; } const markupGrammars = new Set(['source.gfm', 'source.asciidoc']); export function isMultilanguageGrammar(grammar: atom$Grammar) { return markupGrammars.has(grammar.scopeName); } /* eslint-disable no-console */ export function log(...message: Array<any>) { if (atom.inDevMode() || atom.config.get('Hydrogen.debug')) { console.debug('Hydrogen:', ...message); } }
/* @flow */ import { Disposable } from 'atom'; import ReactDOM from 'react-dom'; import store from './store'; export function reactFactory( reactElement: React$Element<any>, domElement: HTMLElement, additionalTeardown: Function = () => {}, disposer: atom$CompositeDisposable = store.subscriptions, ) { ReactDOM.render(reactElement, domElement); const disposable = new Disposable(() => { ReactDOM.unmountComponentAtNode(domElement); additionalTeardown(); }); disposer.add(disposable); } export function grammarToLanguage(grammar: ?atom$Grammar) { return (grammar) ? grammar.name.toLowerCase() : null; } const markupGrammars = new Set(['source.gfm']); export function isMultilanguageGrammar(grammar: atom$Grammar) { return markupGrammars.has(grammar.scopeName); } /* eslint-disable no-console */ export function log(...message: Array<any>) { if (atom.inDevMode() || atom.config.get('Hydrogen.debug')) { console.debug('Hydrogen:', ...message); } }
Remove unused get_labels function and commented code
class PseudoData(dict): def __init__(self, name_func_dict, sweep): super(PseudoData, self).__init__() self.name_func_dict = name_func_dict self.sweep = sweep def __getitem__(self, key): if key in self.keys(): return dict.__getitem__(self, key) elif key in self.name_func_dict: func = self.name_func_dict[key]['func'] pcol = func(self.sweep.data, self.sweep.pdata, self.sweep.meta) self.__setitem__(key, pcol) return pcol else: return dict.__getitem__(self, key) def get_names(self): names = [k for k, v in self.name_func_dict.items() if 'func' in v] names.sort() return names
class PseudoData(dict): def __init__(self, name_func_dict, sweep): super(PseudoData, self).__init__() self.name_func_dict = name_func_dict self.sweep = sweep def __getitem__(self, key): if key in self.keys(): return dict.__getitem__(self, key) elif key in self.name_func_dict: func = self.name_func_dict[key]['func'] pcol = func(self.sweep.data, self.sweep.pdata, self.sweep.meta) self.__setitem__(key, pcol) return pcol else: return dict.__getitem__(self, key) def get_names(self): names = [k for k, v in self.name_func_dict.items() if 'func' in v] names.sort() return names def get_labels(self): labels = [key['label'] for key in self.name_func_dict.keys()] return labels # class PseudoFunction(object): # def __init__(self, name, label, active): # self.name = name # self.label = label # self.active = active # def __call__(self): # return 10
Use mutex instead of RWMutex in language
package server import ( "sync" "time" ) type LanguagePool struct { mutex sync.Mutex languages map[string]*Language } func NewLanguagePool() *LanguagePool { p := new(LanguagePool) p.languages = make(map[string]*Language) return p } func (lp *LanguagePool) Remove(l *Language) { lp.mutex.Lock() defer lp.mutex.Unlock() delete(lp.languages, l.Name) } func (lp *LanguagePool) Get(name string) *Language { lp.mutex.Lock() defer lp.mutex.Unlock() language, ok := lp.languages[name] if !ok { language = NewLanguage(name) lp.languages[language.Name] = language } return language } func (lp *LanguagePool) Broadcast(sender *Client, message []byte) { lp.mutex.Lock() defer lp.mutex.Unlock() now := time.Now() for _, language := range lp.languages { language.Send(sender, now, message) } }
package server import ( "errors" "sync" "time" ) type LanguagePool struct { mutex sync.RWMutex languages map[string]*Language } func NewLanguagePool() *LanguagePool { p := new(LanguagePool) p.languages = make(map[string]*Language) return p } func (lp *LanguagePool) Add(l *Language) error { lp.mutex.Lock() defer lp.mutex.Unlock() if _, ok := lp.languages[l.Name]; ok { return errors.New("Language with this name already exists") } lp.languages[l.Name] = l return nil } func (lp *LanguagePool) Remove(l *Language) { lp.mutex.Lock() defer lp.mutex.Unlock() delete(lp.languages, l.Name) } func (lp *LanguagePool) Get(name string) *Language { language, ok := lp.languages[name] if !ok { language = NewLanguage(name) languages.Add(language) } return language } func (lp *LanguagePool) Broadcast(sender *Client, message []byte) { now := time.Now() for _, language := range lp.languages { language.Send(sender, now, message) } }
Support apps in organisations for Application.get
var _ = require("lodash"); var Bacon = require("baconjs"); var Logger = require("../logger.js"); var Application = module.exports; Application.getInstanceType = function(api, type) { var s_types = api.products.instances.get().send(); return s_types.flatMapLatest(function(types) { var instanceType = _.find(types, function(instanceType) { return instanceType.type == type; }); return instanceType ? Bacon.once(instanceType) : new Bacon.Error(type + " type does not exist."); }); }; Application.create = function(api, name, instanceType, region) { Logger.debug("Create the application…"); return api.owner().applications.post().send(JSON.stringify({ "deploy": "git", "description": name, "instanceType": instanceType.type, "instanceVersion": instanceType.version, "maxFlavor": "S", "maxInstances": 1, "minFlavor": "S", "minInstances": 1, "name": name, "zone": region })); }; Application.get = function(api, appId, orgaId) { Logger.debug("Get information for the app: " + appId); if(orgaId) { return api.organisations._.get().withParams([orgaId]).send() .map(function(organisation) { return _.find(organisation.apps, function(app) { return app.id === appId; }); }); } else { return api.owner().applications._.get().withParams([appId]).send(); } };
var _ = require("lodash"); var Bacon = require("baconjs"); var Logger = require("../logger.js"); var Application = module.exports; Application.getInstanceType = function(api, type) { var s_types = api.products.instances.get().send(); return s_types.flatMapLatest(function(types) { var instanceType = _.find(types, function(instanceType) { return instanceType.type == type; }); return instanceType ? Bacon.once(instanceType) : new Bacon.Error(type + " type does not exist."); }); }; Application.create = function(api, name, instanceType, region) { Logger.debug("Create the application…"); return api.owner().applications.post().send(JSON.stringify({ "deploy": "git", "description": name, "instanceType": instanceType.type, "instanceVersion": instanceType.version, "maxFlavor": "S", "maxInstances": 1, "minFlavor": "S", "minInstances": 1, "name": name, "zone": region })); }; Application.get = function(api, appId) { Logger.debug("Get information for the app: " + appId); return api.owner().applications._.get().withParams([appId]).send(); };
Fix thread interruption. Wrong thread was interrupted.
package de.mklinger.commons.exec; public class PingRunnable extends ErrorHandlingRunnable { private Thread runningThread; private final Pingable pingable; public PingRunnable(final Pingable pingable) { this.pingable = pingable; } @Override public void doRun() { runningThread = Thread.currentThread(); while (true) { if (Thread.currentThread().isInterrupted()) { return; } pingable.ping(); if (Thread.currentThread().isInterrupted()) { return; } try { Thread.sleep(500); } catch (final InterruptedException e) { // we expect to be interrupted when done. Thread.currentThread().interrupt(); return; } } } public void interrupt() { runningThread.interrupt(); } }
package de.mklinger.commons.exec; public class PingRunnable extends ErrorHandlingRunnable { private final Pingable pingable; public PingRunnable(final Pingable pingable) { this.pingable = pingable; } @Override public void doRun() { while (true) { if (Thread.currentThread().isInterrupted()) { return; } pingable.ping(); if (Thread.currentThread().isInterrupted()) { return; } try { Thread.sleep(500); } catch (final InterruptedException e) { // we expect to be interrupted when done. Thread.currentThread().interrupt(); return; } } } public void interrupt() { Thread.currentThread().interrupt(); } }
Fix title parser to fix certain missing laws
# -*- coding: utf-8 -* import re def normalize_correction_title_dashes(raw_title): """returns s with normalized spaces before and after the dash""" if not raw_title: return None m = re.match(r'(תיקון)( ?)(-)( ?)(.*)'.decode('utf8'), raw_title) if not m: return raw_title return ' '.join(m.groups()[0:5:2]) def parse_title(unparsed_title): return re.match(u'הצע[תה] ([^\(,]*)(.*?\((.*?)\))?(.*?\((.*?)\))?(.*?,(.*))?', unparsed_title) def clean_line(a_line_str): return a_line_str.strip().replace('\n', '').replace('&nbsp;', ' ')
# -*- coding: utf-8 -* import re def normalize_correction_title_dashes(raw_title): """returns s with normalized spaces before and after the dash""" if not raw_title: return None m = re.match(r'(תיקון)( ?)(-)( ?)(.*)'.decode('utf8'), raw_title) if not m: return raw_title return ' '.join(m.groups()[0:5:2]) def parse_title(unparsed_title): return re.match(u'הצעת ([^\(,]*)(.*?\((.*?)\))?(.*?\((.*?)\))?(.*?,(.*))?', unparsed_title) def clean_line(a_line_str): return a_line_str.strip().replace('\n', '').replace('&nbsp;', ' ')
Add debounceTimeout when applying changes to URL
import shallowEqual from 'fbjs/lib/shallowEqual'; import {restoreLocation} from './actions'; import {stringify} from 'qs'; const updated = callback => { let lastQuery; let lastPathname; return ({pathname, query, hash}) => { if (shallowEqual(lastQuery, query) && lastPathname === pathname) { return; } const search = stringify(query, {strictNullHandling: true}); lastQuery = query; lastPathname = pathname; callback({pathname, search: search.length > 0 ? `?${search}` : '', hash}); }; }; const push = history => updated(location => history.push(location)); export const location = (createHistory, type) => ({ store, namespace = 'componentRouter', debounceTimeout = 50 }) => { const history = createHistory(); const historyPush = push(history); let timer; const batchedHistoryPush = (...args) => { clearTimeout(timer); timer = setTimeout(() => historyPush(...args), debounceTimeout); }; const getState = () => store.getState()[namespace]; const historyUnsubscribe = history.listen(({pathname, search, hash}) => store.dispatch(restoreLocation({pathname, search, hash}, type))); const storeUnsubscribe = store.subscribe(() => batchedHistoryPush({ pathname: getState().pathname, query: getState().cleanQuery, hash: getState().hash })); return () => { historyUnsubscribe(); storeUnsubscribe(); }; };
import shallowEqual from 'fbjs/lib/shallowEqual'; import {restoreLocation} from './actions'; import {stringify} from 'qs'; const updated = callback => { let lastQuery; let lastPathname; return ({pathname, query, hash}) => { if (shallowEqual(lastQuery, query) && lastPathname === pathname) { return; } const search = stringify(query, {strictNullHandling: true}); lastQuery = query; lastPathname = pathname; callback({pathname, search: search.length > 0 ? `?${search}` : '', hash}); }; }; const push = history => updated(location => history.push(location)); export const location = (createHistory, type) => ({store, namespace = 'componentRouter'}) => { const history = createHistory(); const historyPush = push(history); let timer; const batchedHistoryPush = (...args) => { clearTimeout(timer); timer = setTimeout(() => historyPush(...args), 0); }; const getState = () => store.getState()[namespace]; const historyUnsubscribe = history.listen(({pathname, search, hash}) => store.dispatch(restoreLocation({pathname, search, hash}, type))); const storeUnsubscribe = store.subscribe(() => batchedHistoryPush({ pathname: getState().pathname, query: getState().cleanQuery, hash: getState().hash })); return () => { historyUnsubscribe(); storeUnsubscribe(); }; };
Add unit test for missing country mapping
const Promise = require('bluebird') const chai = require('chai') chai.use(require('chai-as-promised')) const expect = chai.expect const rewire = require('rewire') const fetchCountryMapping = rewire('../../lib/fetchCountryMapping') describe('Country mapping', () => { it('should be the body of the HTTP response if the given input is a URL', () => { fetchCountryMapping.__set__({ request () { return Promise.resolve(` ctf: countryMapping: scoreBoardChallenge: name: Canada code: CA `) } }) return expect(fetchCountryMapping('http://localhorst:3000')).to.eventually.deep.equal({ scoreBoardChallenge: { name: 'Canada', code: 'CA' } }) }) it('should be undefined if no map file URL is given', () => { return expect(fetchCountryMapping()).to.eventually.equal(undefined) }) })
const Promise = require('bluebird') const chai = require('chai') chai.use(require('chai-as-promised')) const expect = chai.expect const rewire = require('rewire') const fetchCountryMapping = rewire('../../lib/fetchCountryMapping') describe('Country mapping', () => { it('should be the body of the HTTP response if the given input is a URL', () => { fetchCountryMapping.__set__({ request () { return Promise.resolve(` ctf: countryMapping: scoreBoardChallenge: name: Canada code: CA `) } }) return expect(fetchCountryMapping('http://localhorst:3000')).to.eventually.deep.equal({ scoreBoardChallenge: { name: 'Canada', code: 'CA' } }) }) })
Fix MathJAX on dynamic pages
// CRITICAL TODO: Namespace var ${ id }contents=["", %for t in items: ${t[1]['content']} , %endfor "" ]; var ${ id }functions=["", %for t in items: function(){ ${t[1]['init_js']} }, %endfor ""]; var ${ id }loc; function ${ id }goto(i) { $('#content').html(${ id }contents[i]); ${ id }functions[i]() ${ id }loc=i; MathJax.Hub.Queue(["Typeset",MathJax.Hub]); } function ${ id }setup_click(i) { $('#tt_'+i).click(function(eo) { ${ id }goto(i);}); } function ${ id }next() { ${ id }loc=${ id }loc+1; if(${ id }loc> ${ len(items) } ) ${ id }loc=${ len(items) }; ${ id }goto(${ id }loc); } function ${ id }prev() { ${ id }loc=${ id }loc-1; if(${ id }loc<1) ${ id }loc=1; ${ id }goto(${ id }loc); } $(function() { var i; for(i=1; i<11; i++) { ${ id }setup_click(i); } $('#${ id }next').click(function(eo) { ${ id }next();}); $('#${ id }prev').click(function(eo) { ${ id }prev();}); ${ id }goto(1); });
// CRITICAL TODO: Namespace var ${ id }contents=["", %for t in items: ${t[1]['content']} , %endfor "" ]; var ${ id }functions=["", %for t in items: function(){ ${t[1]['init_js']} }, %endfor ""]; var ${ id }loc; function ${ id }goto(i) { $('#content').html(${ id }contents[i]); ${ id }functions[i]() ${ id }loc=i; } function ${ id }setup_click(i) { $('#tt_'+i).click(function(eo) { ${ id }goto(i);}); } function ${ id }next() { ${ id }loc=${ id }loc+1; if(${ id }loc> ${ len(items) } ) ${ id }loc=${ len(items) }; ${ id }goto(${ id }loc); } function ${ id }prev() { ${ id }loc=${ id }loc-1; if(${ id }loc<1) ${ id }loc=1; ${ id }goto(${ id }loc); } $(function() { var i; for(i=1; i<11; i++) { ${ id }setup_click(i); } $('#${ id }next').click(function(eo) { ${ id }next();}); $('#${ id }prev').click(function(eo) { ${ id }prev();}); ${ id }goto(1); });
Disable bulk send action when a bulk send conversation has no suitable channels attached.
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class BulkSendAction(ConversationAction): action_name = 'bulk_send' action_display_name = 'Send Bulk Message' needs_confirmation = True needs_group = True needs_running = True def check_disabled(self): channels = self._conv.get_channels() for channel in channels: if channel.supports_generic_sends(): return None return ("This action needs channels capable of sending" " messages attached to this conversation.") def perform_action(self, action_data): return self.send_command( 'bulk_send', batch_id=self._conv.get_latest_batch_key(), msg_options={}, content=action_data['message'], delivery_class=self._conv.delivery_class, dedupe=action_data['dedupe']) class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'bulk_message' actions = (BulkSendAction,)
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class BulkSendAction(ConversationAction): action_name = 'bulk_send' action_display_name = 'Send Bulk Message' needs_confirmation = True needs_group = True needs_running = True def perform_action(self, action_data): return self.send_command( 'bulk_send', batch_id=self._conv.get_latest_batch_key(), msg_options={}, content=action_data['message'], delivery_class=self._conv.delivery_class, dedupe=action_data['dedupe']) class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'bulk_message' actions = (BulkSendAction,)
Simplify and optimize getItemOffsets() logic
package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.graphics.Rect; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; public class MarginItemDecoration extends RecyclerView.ItemDecoration { private final int margin; public MarginItemDecoration(@Px final int margin) { this.margin = margin; } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams(); final int position = params.getViewLayoutPosition(); final int marginTop = position == 0 ? margin : 0; outRect.set(margin, marginTop, margin, margin); } }
package com.veyndan.redditclient.ui.recyclerview.itemdecoration; import android.graphics.Rect; import android.support.annotation.Px; import android.support.v7.widget.RecyclerView; import android.view.View; public class MarginItemDecoration extends RecyclerView.ItemDecoration { private final int margin; public MarginItemDecoration(@Px final int margin) { this.margin = margin; } @Override public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.bottom = margin; outRect.left = margin; outRect.right = margin; if (parent.getChildAdapterPosition(view) == 0) { outRect.top = margin; } } }
Put back code to default to first tab
// hqDefine intentionally not used // Modified from // http://stackoverflow.com/questions/10523433/how-do-i-keep-the-current-tab-active-with-twitter-bootstrap-after-a-page-reload $(function() { // Save latest tab when switching tabs $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function(e){ var href = $(e.target).attr('href'); if (href.startsWith("#")) { // App manager does complex things with tabs. // Ignore those, only deal with simple tabs. $.cookie('last_tab', href); } }); // Activate latest (or first) tab on document ready var lastTab = $.cookie('last_tab'); if (lastTab) { $('a[href="' + lastTab + '"]').tab('show'); } else { $('a[data-toggle="tab"]:first').tab('show'); } });
// hqDefine intentionally not used // Modified from // http://stackoverflow.com/questions/10523433/how-do-i-keep-the-current-tab-active-with-twitter-bootstrap-after-a-page-reload $(function() { // Save latest tab when switching tabs $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function(e){ var href = $(e.target).attr('href'); if (href.startsWith("#")) { // App manager does complex things with tabs. // Ignore those, only deal with simple tabs. $.cookie('last_tab', href); } }); // Activate latest tab on document ready var lastTab = $.cookie('last_tab'); if (lastTab) { $('a[href="' + lastTab + '"]').tab('show'); } });
Add API_FIELDS so we can pass a Ticket as an event.
from elixir import ManyToOne, Entity from elixir.events import after_insert import json from astral.models.base import BaseEntityMixin from astral.models.event import Event class Ticket(BaseEntityMixin, Entity): source = ManyToOne('Node') destination = ManyToOne('Node') stream = ManyToOne('Stream') API_FIELDS = ['id', 'source_id', 'destination_id', 'stream_id'] def absolute_url(self): return '/stream/%s/ticket/%s' % (self.stream.id, self.destination.uuid) @after_insert def emit_new_node_event(self): Event(message=json.dumps({'type': "ticket", 'data': self.to_dict()})) def __repr__(self): return u'<Ticket %s: %s from %s to %s>' % ( self.id, self.stream, self.source, self.destination)
from elixir import ManyToOne, Entity from elixir.events import after_insert import json from astral.models.base import BaseEntityMixin from astral.models.event import Event class Ticket(BaseEntityMixin, Entity): source = ManyToOne('Node') destination = ManyToOne('Node') stream = ManyToOne('Stream') def absolute_url(self): return '/stream/%s/ticket/%s' % (self.stream.id, self.destination.uuid) @after_insert def emit_new_node_event(self): Event(message=json.dumps({'type': "ticket", 'data': self.to_dict()})) def __repr__(self): return u'<Ticket %s: %s from %s to %s>' % ( self.id, self.stream, self.source, self.destination)
events: Fix broken JSON path for member events.
exports.run = async function(payload) { const claimEnabled = this.cfg.issues.commands.assign.claim.length; if (payload.action !== "added" || !claimEnabled) return; const newMember = payload.member.login; const invite = this.invites.get(newMember); if (!invite) return; const repo = payload.repository; const repoFullName = invite.split("#")[0]; if (repoFullName !== repo.full_name) return; const number = invite.split("#")[1]; const repoOwner = repoFullName.split("/")[0]; const repoName = repoFullName.split("/")[1]; const response = await this.issues.addAssigneesToIssue({ owner: repoOwner, repo: repoName, number: number, assignees: [newMember] }); if (response.data.assignees.length) return; const error = "**ERROR:** Issue claiming failed (no assignee was added)."; this.issues.createComment({ owner: repoOwner, repo: repoName, number: number, body: error }); }; exports.events = ["member"];
exports.run = async function(payload) { const claimEnabled = this.cfg.issues.commands.assign.claim.aliases.length; if (payload.action !== "added" || !claimEnabled) return; const newMember = payload.member.login; const invite = this.invites.get(newMember); if (!invite) return; const repo = payload.repository; const repoFullName = invite.split("#")[0]; if (repoFullName !== repo.full_name) return; const number = invite.split("#")[1]; const repoOwner = repoFullName.split("/")[0]; const repoName = repoFullName.split("/")[1]; const response = await this.issues.addAssigneesToIssue({ owner: repoOwner, repo: repoName, number: number, assignees: [newMember] }); if (response.data.assignees.length) return; const error = "**ERROR:** Issue claiming failed (no assignee was added)."; this.issues.createComment({ owner: repoOwner, repo: repoName, number: number, body: error }); }; exports.events = ["member"];
Set profile to load before post is rendered.
define(function (require) { 'use strict'; var $ = require('jquery'), Backbone = require('backbone'), ProfileModel = require('./models/profile'), PostModel = require('./models/post'), PostView = require('./views/post'); var Router = Backbone.Router.extend({ routes: { 'post/new/': null, 'post/(:name/):id/': 'post' }, post: function (postName, postId) { var profile = new ProfileModel(), model = new PostModel({ id: postId }), view = new PostView({ model: model }); $.when( profile.fetch(), model.fetch() ).done(view.render); } }); var App = new Router(); Backbone.history.start({ pushState: true }); return App; });
define(function (require) { 'use strict'; var $ = require('jquery'), Backbone = require('backbone'), PostView = require('views/post'), PostModel = require('models/post'); var Router = Backbone.Router.extend({ routes: { 'post/new/': null, 'post/(:name/):id/': 'post' }, post: function (postName, postId) { var model = new PostModel({ id: postId }), view = new PostView({ model: model }); $.when( model.fetch() ).done(view.render); } }); var App = new Router(); Backbone.history.start({ pushState: true }); return App; });
Add explicit call to deprecate.log
const assert = require('assert') const deprecations = require('electron').deprecations describe('deprecations', function () { beforeEach(function () { deprecations.setHandler(null) process.throwDeprecation = true }) it('allows a deprecation handler function to be specified', function () { var messages = [] deprecations.setHandler(function (message) { messages.push(message) }) require('electron').deprecate.log('this is deprecated') assert.deepEqual(messages, ['this is deprecated']) }) it('throws an exception if no deprecation handler is specified', function () { assert.throws(function () { require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme') }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.') }) })
const assert = require('assert') const deprecations = require('electron').deprecations describe('deprecations', function () { beforeEach(function () { deprecations.setHandler(null) process.throwDeprecation = true }) it('allows a deprecation handler function to be specified', function () { var messages = [] deprecations.setHandler(function (message) { messages.push(message) }) require('electron').webFrame.registerUrlSchemeAsSecure('some-scheme') assert.deepEqual(messages, ['registerUrlSchemeAsSecure is deprecated. Use registerURLSchemeAsSecure instead.']) }) it('throws an exception if no deprecation handler is specified', function () { assert.throws(function () { require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme') }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.') }) })
Remove test data folder with contents
import logging import unittest import os import shutil from sqlalchemy import create_engine from rtrss import config, database logging.disable(logging.ERROR) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, echo=False, client_encoding='utf8') # Reconfigure session factory to use our test schema database.Session.configure(bind=engine) class AttrDict(dict): """Class to make mock objects""" def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self class RTRSSTestCase(unittest.TestCase): @classmethod def setUpClass(cls): if os.path.isdir(config.DATA_DIR): os.rmdir(config.DATA_DIR) os.makedirs(config.DATA_DIR) @classmethod def tearDownClass(cls): shutil.rmtree(config.DATA_DIR) class RTRSSDataBaseTestCase(RTRSSTestCase): def setUp(self): database.clear(engine) database.init(engine) self.db = database.Session() def tearDown(self): database.clear(engine) self.db.close()
import logging import unittest import os from sqlalchemy import create_engine from rtrss import config, database logging.disable(logging.ERROR) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, echo=False, client_encoding='utf8') # Reconfigure session factory to use our test schema database.Session.configure(bind=engine) class AttrDict(dict): """Class to make mock objects""" def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self class RTRSSTestCase(unittest.TestCase): @classmethod def setUpClass(cls): if os.path.isdir(config.DATA_DIR): os.rmdir(config.DATA_DIR) os.makedirs(config.DATA_DIR) @classmethod def tearDownClass(cls): os.rmdir(config.DATA_DIR) class RTRSSDataBaseTestCase(RTRSSTestCase): def setUp(self): database.clear(engine) database.init(engine) self.db = database.Session() def tearDown(self): database.clear(engine) self.db.close()
:wrench: Remove unnecessary minified ES module
const merge = require('webpack-merge'); const webpack = require('webpack'); const baseConfig = require('./webpack.base.config'); const prodConfig = merge(baseConfig, { devtool: 'source-map', stats: { modules: false }, externals: { 'highlight.js': { root: 'hljs', commonjs: 'highlight.js', commonjs2: 'highlight.js', amd: 'highlight.js' } } }); const prodMinConfig = merge(prodConfig, { plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true }) ] }); module.exports = [ // CommonJS merge(prodConfig, { output: { filename: 'vue-highlight.js', libraryExport: 'default' } }), merge(prodMinConfig, { output: { filename: 'vue-highlight.min.js', libraryExport: 'default' } }), // ES Module merge(prodConfig, { output: { filename: 'vue-highlight.esm.js' } }) ];
const merge = require('webpack-merge'); const webpack = require('webpack'); const baseConfig = require('./webpack.base.config'); const prodConfig = merge(baseConfig, { devtool: 'source-map', stats: { modules: false }, externals: { 'highlight.js': { root: 'hljs', commonjs: 'highlight.js', commonjs2: 'highlight.js', amd: 'highlight.js' } } }); const prodMinConfig = merge(prodConfig, { plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true }) ] }); module.exports = [ // CommonJS merge(prodConfig, { output: { filename: 'vue-highlight.js', libraryExport: 'default' } }), merge(prodMinConfig, { output: { filename: 'vue-highlight.min.js', libraryExport: 'default' } }), // ES Module merge(prodConfig, { output: { filename: 'vue-highlight.esm.js' } }), merge(prodMinConfig, { output: { filename: 'vue-highlight.esm.min.js' } }) ];
Change slides variable to collection
import { Kefir as K } from "kefir"; const NEVER = K.never(); const ZERO = K.constant(0); const ADD1 = (x) => x + 1; const SUBTRACT1 = (x) => x - 1; const ALWAYS = (x) => () => x; const delay = (n, s) => s.slidingWindow(n + 1, 2).map(([i, _]) => i); function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, collection) { const length = collection.length; const nextT = advance.map(() => ADD1); const previousT = recede.map(() => SUBTRACT1); const indexT = index.map(ALWAYS); const transformations = K.merge([ nextT, previousT, indexT ]); const currentIndex = transformations .scan((i, transform) => transform(i), 0) .map((i) => (i + length) % length); const current = currentIndex.map((i) => collection[i]); const previousIndex = delay(1, currentIndex); const previous = delay(1, current); return { current, currentIndex, previous, previousIndex } } module.exports = galvo;
import { Kefir as K } from "kefir"; const NEVER = K.never(); const ZERO = K.constant(0); const ADD1 = (x) => x + 1; const SUBTRACT1 = (x) => x - 1; const ALWAYS = (x) => () => x; const delay = (n, s) => s.slidingWindow(n + 1, 2).map(([i, _]) => i); function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, slides) { const length = slides.length; const nextT = advance.map(() => ADD1); const previousT = recede.map(() => SUBTRACT1); const indexT = index.map(ALWAYS); const transformations = K.merge([ nextT, previousT, indexT ]); const currentIndex = transformations .scan((i, transform) => transform(i), 0) .map((i) => (i + length) % length); const current = currentIndex.map((i) => slides[i]); const previousIndex = delay(1, currentIndex); const previous = delay(1, current); return { current, currentIndex, previous, previousIndex } } module.exports = galvo;
Initialize the customizer AFTER including lessphp & image_resize
<?php /** * Roots includes */ require_once locate_template('/lib/utils.php'); // Utility functions require_once locate_template('/lib/init.php'); // Initial theme setup and constants require_once locate_template('/lib/sidebar.php'); // Sidebar class require_once locate_template('/lib/config.php'); // Configuration require_once locate_template('/lib/activation.php'); // Theme activation require_once locate_template('/lib/cleanup.php'); // Cleanup require_once locate_template('/lib/nav.php'); // Custom nav modifications require_once locate_template('/lib/comments.php'); // Custom comments modifications require_once locate_template('/lib/rewrites.php'); // URL rewriting for assets require_once locate_template('/lib/widgets.php'); // Sidebars and widgets require_once locate_template('/lib/scripts.php'); // Scripts and stylesheets require_once locate_template('/lib/custom.php'); // Custom functions require_once locate_template('/lib/lessphp/lessc.inc.php'); // Include the less compiler require_once locate_template('/lib/image_resize/resize.php'); // Include the Image Resizer require_once locate_template('/lib/customizer/init.php'); // Initialize the Customizer
<?php /** * Roots includes */ require_once locate_template('/lib/utils.php'); // Utility functions require_once locate_template('/lib/init.php'); // Initial theme setup and constants require_once locate_template('/lib/sidebar.php'); // Sidebar class require_once locate_template('/lib/config.php'); // Configuration require_once locate_template('/lib/activation.php'); // Theme activation require_once locate_template('/lib/cleanup.php'); // Cleanup require_once locate_template('/lib/nav.php'); // Custom nav modifications require_once locate_template('/lib/comments.php'); // Custom comments modifications require_once locate_template('/lib/rewrites.php'); // URL rewriting for assets require_once locate_template('/lib/widgets.php'); // Sidebars and widgets require_once locate_template('/lib/scripts.php'); // Scripts and stylesheets require_once locate_template('/lib/custom.php'); // Custom functions require_once locate_template('/lib/customizer/init.php'); // Initialize the Customizer require_once locate_template('/lib/lessphp/lessc.inc.php'); // Include the less compiler require_once locate_template('/lib/image_resize/resize.php'); // Include the Image Resizer
Refactor away unnecessary multiple return None
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): if request.user.is_authenticated() or utils.is_view_func_public(view_func) \ or self.is_public_url(request.path_info): return None return login_required(view_func)(request, *view_args, **view_kwargs) def is_public_url(self, url): return any(public_url.match(url) for public_url in self.public_view_urls)
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): # if request is authenticated, dont process it if request.user.is_authenticated(): return None # if its a public view, don't process it if utils.is_view_func_public(view_func): return None # if this view matches a whitelisted regex, don't process it if any(view_url.match(request.path_info) for view_url in self.public_view_urls): return None return login_required(view_func)(request, *view_args, **view_kwargs)
Add classification to base instance object
<?php /** * Class definition for DTS_Instance. * * @package DTS * @author Eric Bollens * @copyright Copyright (c) 2012 UC Regents * @license BSD * @version 20120131 */ /** * A class that encapsulates the instance of DTS in js.php and passthru.php. * * @package DTS * @see /www/js.php * @see /www/passthru.php */ class DTS_Instance { public static function render() { $dts = new DTS(); $dts->add('capability.js'); $dts->add('classification.js'); $dts->add('browser.js'); $dts->add('useragent.js'); $dts->add('screen.js'); $dts->add('server.js'); $dts->add('server/screen.js'); $dts->add('server/useragent.js'); return $dts->render(); } }
<?php /** * Class definition for DTS_Instance. * * @package DTS * @author Eric Bollens * @copyright Copyright (c) 2012 UC Regents * @license BSD * @version 20120131 */ /** * A class that encapsulates the instance of DTS in js.php and passthru.php. * * @package DTS * @see /www/js.php * @see /www/passthru.php */ class DTS_Instance { public static function render() { $dts = new DTS(); $dts->add('capability.js'); $dts->add('browser.js'); $dts->add('useragent.js'); $dts->add('screen.js'); $dts->add('server.js'); $dts->add('server/screen.js'); $dts->add('server/useragent.js'); return $dts->render(); } }
Add pyuniotest class for unittest, but still lake mock server for test.
import json import unittest from pyunio import pyunio pyunio.use('httpbin') params = { 'body': { 'name': 'James Bond' } } class pyuniotTest(unittest.TestCase): def test_get(self): response = json.loads(pyunio.get('get', params).text) self.assertEqual(response['args']['name'], 'James Bond') def test_post(self): response = json.loads(pyunio.post('post', params).text) self.assertEqual(response['args']['name'], 'James Bond') def test_put(self): response = json.loads(pyunio.put('put', params).text) self.assertEqual(response['args']['name'], 'James Bond') def test_delete(self): response = json.loads(pyunio.delete('delete', params).text) self.assertEqual(response['args']['name'], 'James Bond') if __name__ == '__main__': unittest.main()
import json import unittest from pyunio import pyunio pyunio.use('httpbin') params = { 'body': { 'name': 'James Bond' } } def test_get(): response = json.loads(pyunio.get('get', params).text) assert(response['args']['name'] == 'James Bond') def test_post(): response = json.loads(pyunio.post('post', params).text) assert(response['args']['name'] == 'James Bond') def test_put(): response = json.loads(pyunio.put('put', params).text) assert(response['args']['name'] == 'James Bond') def test_delete(): response = json.loads(pyunio.delete('delete', params).text) assert(response['args']['name'] == 'James Bond')
Make sure tests are updated.
'use strict' var test = require('tape') test('NGN.ref', function (t) { var p = document.createElement('span') var hr = document.createElement('hr') var sel = '#test2' hr.setAttribute('id', 'test2') p.appendChild(hr) document.body.appendChild(p) NGN.ref.create('test', sel) t.ok(NGN.ref.test !== undefined, 'NGN.ref.create() returns an HTMLElement.') t.ok(typeof NGN.ref.test.on === 'function', 'NGN.ref.<name>.on aliases addEventListener.') NGN.ref.test.on('click', function () { t.pass('NGN.ref.<name>.on alias successfully relays events.') t.ok(document.body.querySelector('#test2') !== null, '#test2 should exist') // remove the reference t.doesNotThrow(function () { NGN.ref.remove('test') t.ok(document.body.querySelector('#test2') !== null, '#test2 element should not be removed after removal of reference.') // TODO: Uncomment the line below once the test above passes (the reference should need to be recreated) NGN.ref.create('test', sel) t.ok(document.body.querySelector('#test2') !== null, '#test2 element should exist after creation.') t.end() }, 'NGN.ref.remove("test") should not throw an error') }) document.querySelector(sel).click() })
'use strict' var test = require('tape') test('NGN.ref', function (t) { var p = document.createElement('span') var hr = document.createElement('hr') // var sel = 'body > span:first-of-type > hr:first-of-type' var sel = '#test2' hr.setAttribute('id', 'test2') p.appendChild(hr) document.body.appendChild(p) NGN.ref.create('test', sel) t.ok(NGN.ref.test !== undefined, 'NGN.ref.create() returns an HTMLElement.') t.ok(typeof NGN.ref.test.on === 'function', 'NGN.ref.<name>.on aliases addEventListener.') NGN.ref.test.on('click', function () { t.pass('NGN.ref.<name>.on alias successfully relays events.') t.ok(document.body.querySelector('#test2') !== null, '#test2 should exist') // remove the reference t.doesNotThrow(function () { NGN.ref.remove('test') t.ok(document.body.querySelector('#test2') !== null, '#test2 element should not be removed after removal of reference.') // TODO: Uncomment the line below once the test above passes (the reference should need to be recreated) NGN.ref.create('test', sel) t.ok(document.body.querySelector('#test2') !== null, '#test2 element should exist after creation.') t.end() }, 'NGN.ref.remove("test") should not throw an error') }) document.querySelector(sel).click() })
Fix PHP 8.1.2 compatibility in DatabaseException > Cannot access protected property PDOException::$code
<?php namespace wcf\system\database\exception; /** * Denotes an database related error. * * @author Tim Duesterhus * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Database\Exception * @since 3.0 */ class DatabaseException extends \wcf\system\database\DatabaseException { /** @noinspection PhpMissingParentConstructorInspection */ /** * @inheritDoc */ public function __construct($message, ?\PDOException $previous = null) { \Exception::__construct($message, 0, $previous); // we cannot use the constructor's parameter, because of (http://php.net/manual/en/exception.getcode.php): // > Returns the exception code as integer in Exception but possibly as other type in Exception // descendants (for example as string in PDOException). if ($previous) { $this->code = $previous->getCode(); } } }
<?php namespace wcf\system\database\exception; /** * Denotes an database related error. * * @author Tim Duesterhus * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Database\Exception * @since 3.0 */ class DatabaseException extends \wcf\system\database\DatabaseException { /** @noinspection PhpMissingParentConstructorInspection */ /** * @inheritDoc */ public function __construct($message, ?\PDOException $previous = null) { \Exception::__construct($message, 0, $previous); // we cannot use the constructor's parameter, because of (http://php.net/manual/en/exception.getcode.php): // > Returns the exception code as integer in Exception but possibly as other type in Exception // descendants (for example as string in PDOException). if ($previous) { $this->code = $previous->code; } } }
Add flag for output file
package main import ( "fmt" "os" "github.com/jutkko/mindown/input" "github.com/jutkko/mindown/output" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "mindown" app.Usage = "convert mind to files" app.Flags = []cli.Flag{ cli.StringFlag{ Name: "input-file", Value: "input.txt", Usage: "input file name", }, cli.StringFlag{ Name: "output-file", Value: "output.txt", Usage: "output file name", }, } app.Action = func(c *cli.Context) error { fmt.Printf("Input file name: %s\n", c.String("input-file")) fmt.Printf("Input file name: %s\n", c.String("output-file")) graph, err := input.ParseOpml(c.String("input-file")) if err != nil { panic(err.Error()) } err = output.WriteMarkdown(c.String("output-file"), graph) if err != nil { panic(err.Error()) } return nil } app.Run(os.Args) }
package main import ( "fmt" "os" "github.com/jutkko/mindown/input" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "mindown" app.Usage = "convert mind to files" app.Flags = []cli.Flag{ cli.StringFlag{ Name: "input-file", Value: "input.txt", Usage: "input file name", }, } app.Action = func(c *cli.Context) error { fmt.Printf("Input file name: %s\n", c.String("input-file")) graph, err := input.ParseOpml(c.String("input-file")) if err != nil { panic(err.Error()) } if err != nil { panic(err.Error()) } return nil } app.Run(os.Args) }
Step_5: Add fixtures to cattery tests Add a fixture to remove initialisation of the cattery in every test. Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com>
import pytest from catinabox import cattery ########################################################################### # fixtures ########################################################################### @pytest.fixture def c(): return cattery.Cattery() ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(c): c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(c): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(c): with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(c): c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
import pytest from catinabox import cattery ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(): c = cattery.Cattery() with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(): c = cattery.Cattery() c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
Make click-to-hide-notices feature more obvious
(function ($) { /* * * Fades flash notices out after they are shown * */ $.fn.flashNotice = function () { $(this).fadeIn(); if (!$(this).hasClass('alert')) { var element = $(this); var timeout = setTimeout(function () { element.fadeOut(); }, 3000); } $(this).css('cursor', 'pointer').click(function () { if (timeout) { clearTimeout(timeout); } $(this).fadeOut(); }); } $.fn.showNotice = function (message) { $(this).html("<p class='flash notice'>"+message+"</p>") $(".notice", this).flashNotice(); } $.fn.showAlert = function (message) { $(this).html("<p class='flash alert'>"+message+"</p>") $(".alert", this).flashNotice(); } })(jQuery);
(function ($) { /* * * Fades flash notices out after they are shown * */ $.fn.flashNotice = function () { $(this).fadeIn(); if (!$(this).hasClass('alert')) { var element = $(this); var timeout = setTimeout(function () { element.fadeOut(); }, 3000); } $(this).click(function () { if (timeout) { clearTimeout(timeout); } $(this).fadeOut(); }); } $.fn.showNotice = function (message) { $(this).html("<p class='flash notice'>"+message+"</p>") $(".notice", this).flashNotice(); } $.fn.showAlert = function (message) { $(this).html("<p class='flash alert'>"+message+"</p>") $(".alert", this).flashNotice(); } })(jQuery);
Update tests now that ShellHelper throws a generic exception.
<?php namespace CommerceGuys\Platform\Cli\Tests; use CommerceGuys\Platform\Cli\Helper\ShellHelper; class ShellHelperTest extends \PHPUnit_Framework_TestCase { /** * Test ShellHelper::execute(). */ public function testExecute() { $shellHelper = new ShellHelper(); // Find a command that will work on all platforms. $workingCommand = strpos(PHP_OS, 'WIN') !== false ? 'help' : 'pwd'; // With $mustRun disabled. $this->assertNotEmpty($shellHelper->execute(array($workingCommand))); $this->assertFalse($shellHelper->execute(array('which', 'nonexistent'))); // With $mustRun enabled. $this->assertNotEmpty($shellHelper->execute(array($workingCommand), null, true)); $this->setExpectedException('Exception'); $shellHelper->execute(array('which', 'nonexistent'), null, true); } }
<?php namespace CommerceGuys\Platform\Cli\Tests; use CommerceGuys\Platform\Cli\Helper\ShellHelper; class ShellHelperTest extends \PHPUnit_Framework_TestCase { /** * Test ShellHelper::execute(). */ public function testExecute() { $shellHelper = new ShellHelper(); // Find a command that will work on all platforms. $workingCommand = strpos(PHP_OS, 'WIN') !== false ? 'help' : 'pwd'; // With $mustRun disabled. $this->assertNotEmpty($shellHelper->execute(array($workingCommand))); $this->assertFalse($shellHelper->execute(array('which', 'nonexistent'))); // With $mustRun enabled. $this->assertNotEmpty($shellHelper->execute(array($workingCommand), null, true)); $this->setExpectedException('Symfony\\Component\\Process\\Exception\\ProcessFailedException'); $shellHelper->execute(array('which', 'nonexistent'), null, true); } }
Adjust default parameters for xor classifier.
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Example using the theanets package for learning the XOR relation.''' import climate import numpy as np import theanets climate.enable_default_logging() X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]) Y = np.array([0, 1, 1, 0, ]) Xi = np.random.randint(0, 2, size=(256, 2)) train = [ (Xi + 0.1 * np.random.randn(*Xi.shape)).astype('f'), (Xi[:, 0] ^ Xi[:, 1]).astype('f')[:, None], ] e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1), learning_rate=0.1, momentum=0.5, patience=300, num_updates=500) e.run(train, train) print "Input:" print X print "XOR output" print Y print "NN XOR predictions" print e.network(X.astype('f'))
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Example using the theanets package for learning the XOR relation.''' import climate import numpy as np import theanets climate.enable_default_logging() X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]) Y = np.array([0, 1, 1, 0, ]) Xi = np.random.randint(0, 2, size=(256, 2)) train = [ (Xi + 0.1 * np.random.randn(*Xi.shape)).astype('f'), (Xi[:, 0] ^ Xi[:, 1]).astype('f')[:, None], ] e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1), learning_rate=0.1, learning_rate_decay=0, momentum=0.5, patience=300, num_updates=5000) e.run(train, train) print "Input:" print X print "XOR output" print Y print "NN XOR predictions" print e.network(X.astype('f'))
Move component_unittest to android main waterfall and cq These are existing tests that moved to the component_unittest target. They have been running on the FYI bots for a few days without issue. BUG= Android bot script change. Ran through android trybots. NOTRY=true Review URL: https://chromiumcodereview.appspot.com/12092027 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@179263 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2013 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. """Configuration file for android gtest suites.""" # Add new suites here before upgrading them to the stable list below. EXPERIMENTAL_TEST_SUITES = [ 'TestWebKitAPI', 'sandbox_linux_unittests', 'webkit_unit_tests', ] # Do not modify this list without approval of an android owner. # This list determines which suites are run by default, both for local # testing and on android trybots running on commit-queue. STABLE_TEST_SUITES = [ 'android_webview_unittests', 'base_unittests', 'cc_unittests', 'components_unittests', 'content_unittests', 'gpu_unittests', 'ipc_tests', 'media_unittests', 'net_unittests', 'sql_unittests', 'sync_unit_tests', 'ui_unittests', 'unit_tests', 'webkit_compositor_bindings_unittests', ]
# Copyright (c) 2013 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. """Configuration file for android gtest suites.""" # Add new suites here before upgrading them to the stable list below. EXPERIMENTAL_TEST_SUITES = [ 'TestWebKitAPI', 'components_unittests', 'sandbox_linux_unittests', 'webkit_unit_tests', ] # Do not modify this list without approval of an android owner. # This list determines which suites are run by default, both for local # testing and on android trybots running on commit-queue. STABLE_TEST_SUITES = [ 'android_webview_unittests', 'base_unittests', 'cc_unittests', 'content_unittests', 'gpu_unittests', 'ipc_tests', 'media_unittests', 'net_unittests', 'sql_unittests', 'sync_unit_tests', 'ui_unittests', 'unit_tests', 'webkit_compositor_bindings_unittests', ]
Check if classes are derived from object This makes sure we don't regress to old style classes
#!/usr/bin/python import libvirt globals = dir(libvirt) # Sanity test that the generator hasn't gone wrong # Look for core classes for clsname in ["virConnect", "virDomain", "virDomainSnapshot", "virInterface", "virNWFilter", "virNodeDevice", "virNetwork", "virSecret", "virStoragePool", "virStorageVol", "virStream", ]: assert(clsname in globals) assert(object in getattr(libvirt, clsname).__bases__) # Constants assert("VIR_CONNECT_RO" in globals) # Error related bits assert("libvirtError" in globals) assert("VIR_ERR_AUTH_FAILED" in globals) assert("virGetLastError" in globals) # Some misc methods assert("virInitialize" in globals) assert("virEventAddHandle" in globals) assert("virEventRegisterDefaultImpl" in globals)
#!/usr/bin/python import libvirt globals = dir(libvirt) # Sanity test that the generator hasn't gone wrong # Look for core classes assert("virConnect" in globals) assert("virDomain" in globals) assert("virDomainSnapshot" in globals) assert("virInterface" in globals) assert("virNWFilter" in globals) assert("virNodeDevice" in globals) assert("virNetwork" in globals) assert("virSecret" in globals) assert("virStoragePool" in globals) assert("virStorageVol" in globals) assert("virStream" in globals) assert("VIR_CONNECT_RO" in globals) # Error related bits assert("libvirtError" in globals) assert("VIR_ERR_AUTH_FAILED" in globals) assert("virGetLastError" in globals) # Some misc methods assert("virInitialize" in globals) assert("virEventAddHandle" in globals) assert("virEventRegisterDefaultImpl" in globals)
Support setting alpha in colors
# Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides convenience methods for styling text.""" BOLD = 1 UNDERLINE = 2 ITALIC = 4 def color_for_rgba_float(red, green, blue, alpha=1): if any(map(lambda x: x < 0 or x > 1, (red, green, blue, alpha))): raise ValueError("Values must be in the range 0..1 (inclusive)") red, green, blue, alpha = map(lambda c: int(0xFF * c), (red, green, blue, alpha)) return (alpha << 24) | (red << 16) | (green << 8) | blue
# Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides convenience methods for styling text.""" BOLD = 1 UNDERLINE = 2 ITALIC = 4 def color_for_rgb_float(red, green, blue): if any(map(lambda x: x < 0 or x > 1, (red, green, blue))): raise ValueError("Values must be in the range 0..1 (inclusive)") red, green, blue = map(lambda c: int(0xFF * c), (red, green, blue)) return (0xFF << 24) | (red << 16) | (green << 8) | blue
Add remove done staged rules
from __future__ import absolute_import, unicode_literals from atlas.celerybackend.celery import app from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed, delete_done_staging_rules from atlas.prodtask.hashtag import hashtag_request_to_tasks from atlas.prodtask.mcevgen import sync_cvmfs_db from atlas.prodtask.open_ended import check_open_ended from atlas.prodtask.task_views import sync_old_tasks import logging _logger = logging.getLogger('prodtaskwebui') @app.task def test_celery(): _logger.info('test celery') return 2 @app.task(ignore_result=True) def sync_tasks(): sync_old_tasks(-1) return None @app.task(ignore_result=True) def step_actions(): find_action_to_execute() return None @app.task(ignore_result=True) def data_carousel(): submit_all_tapes_processed() return None @app.task(ignore_result=True) def open_ended(): check_open_ended() return None @app.task(ignore_result=True) def request_hashtags(): hashtag_request_to_tasks() return None @app.task(ignore_result=True) def sync_evgen_jo(): sync_cvmfs_db() return None @app.task(ignore_result=True) def remove_done_staging(production_requests): delete_done_staging_rules(production_requests) return None
from __future__ import absolute_import, unicode_literals from atlas.celerybackend.celery import app from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed from atlas.prodtask.hashtag import hashtag_request_to_tasks from atlas.prodtask.mcevgen import sync_cvmfs_db from atlas.prodtask.open_ended import check_open_ended from atlas.prodtask.task_views import sync_old_tasks import logging _logger = logging.getLogger('prodtaskwebui') @app.task def test_celery(): _logger.info('test celery') return 2 @app.task(ignore_result=True) def sync_tasks(): sync_old_tasks(-1) return None @app.task(ignore_result=True) def step_actions(): find_action_to_execute() return None @app.task(ignore_result=True) def data_carousel(): submit_all_tapes_processed() return None @app.task(ignore_result=True) def open_ended(): check_open_ended() return None @app.task(ignore_result=True) def request_hashtags(): hashtag_request_to_tasks() return None @app.task(ignore_result=True) def sync_evgen_jo(): sync_cvmfs_db() return None
Fix css minification for prod
const {inspect} = require('util'); const getLoader = function(rules, matcher) { let loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || (Array.isArray(rule.loader) && rule.loader) || [], matcher); }); return loader; }; const cssLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf(`css-loader`) != -1; }; module.exports = function override(config, env) { let l = getLoader(config.module.rules, cssLoaderMatcher); l.options = Object.assign({}, l.options, { modules: true, localIdentName: 'production' === env ? '__[hash:base64:8]' : '[name]__[local]___[hash:base64:5]', }); return config; };
const {inspect} = require('util'); const getLoader = function(rules, matcher) { let loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || (Array.isArray(rule.loader) && rule.loader) || [], matcher); }); return loader; }; const cssLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf(`css-loader`) != -1; }; module.exports = function override(config, env) { let l = getLoader(config.module.rules, cssLoaderMatcher); l.options = { modules: true, importLoaders: 1, localIdentName: 'production' === env ? '__[hash:base64:8]' : '[name]__[local]___[hash:base64:5]', sourceMap: 'development' === env, }; return config; };