text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Increase prepare timeout to 300 seconds.
<?php namespace BestIt\Mage\Tasks\Release; use Mage\Task\BuiltIn\Deploy\Release\PrepareTask as MagePrepareTask; /** * Class PrepareTask * * @author Ahmad El-Bardan <ahmad.el-bardan@bestit-online.de> * @package BestIt\Mage\Tasks\Release */ class PrepareTask extends MagePrepareTask { /** * Executes the task. * * @return bool */ public function execute() { $hostPath = rtrim($this->runtime->getEnvOption('host_path'), '/'); $releaseId = $this->runtime->getReleaseId(); $cmdMakeDir = sprintf( 'cp -rp %s/current/ %s/releases/%s', $hostPath, $hostPath, $releaseId ); $process = $this->runtime->runRemoteCommand($cmdMakeDir, false, 300); return $process->isSuccessful(); } }
<?php namespace BestIt\Mage\Tasks\Release; use Mage\Task\BuiltIn\Deploy\Release\PrepareTask as MagePrepareTask; /** * Class PrepareTask * * @author Ahmad El-Bardan <ahmad.el-bardan@bestit-online.de> * @package BestIt\Mage\Tasks\Release */ class PrepareTask extends MagePrepareTask { /** * Executes the task. * * @return bool */ public function execute() { $hostPath = rtrim($this->runtime->getEnvOption('host_path'), '/'); $releaseId = $this->runtime->getReleaseId(); $cmdMakeDir = sprintf( 'cp -rp %s/current/ %s/releases/%s', $hostPath, $hostPath, $releaseId ); $process = $this->runtime->runRemoteCommand($cmdMakeDir, false); return $process->isSuccessful(); } }
Return a promise in the searchModel method
// Ember! import Ember from 'ember'; import SearchRoute from 'yebo-ember-storefront/mixins/search-route'; /** * Taxons show page * This page shows products related to the current taxon */ export default Ember.Route.extend(SearchRoute, { /** * Define the search rules */ searchRules(query, params) { // Create a new taxonomy rule let rule = new YeboSDK.Products.Rules.taxonomy([]); // Set its values rule.values = [params.taxon]; // Set it into the query query.and(rule); }, // Change the current controller setupController: function(controller, model) { // This is indispensable, if out, the model won't be passed to the view controller.set('model', model); // the component that requires current taxon and taxonomies is in application let appController = this.controllerFor('application'); // Define some values let taxon = model.taxon; let taxonomies = model.taxonomies; // Set the values to the application controller appController.set('currentTaxonomy', taxon.get('taxonomy')); appController.set('taxonomies', taxonomies); }, /** * This values will be returned into the route (with the route model) */ searchModel(params) { // Search all the taxonomies and the current taxon return Ember.RSVP.hash({ taxonomies: this.yebo.store.findAll('taxonomy'), taxon: this.yebo.store.find('taxon', params.taxon), }); } });
// Ember! import Ember from 'ember'; import SearchRoute from 'yebo-ember-storefront/mixins/search-route'; /** * Taxons show page * This page shows products related to the current taxon */ export default Ember.Route.extend(SearchRoute, { /** * Define the search rules */ searchRules(query, params) { // Create a new taxonomy rule let rule = new YeboSDK.Products.Rules.taxonomy([]); // Set its values rule.values = [params.taxon]; // Set it into the query query.and(rule); }, // Change the current controller setupController: function(controller, model) { // This is indispensable, if out, the model won't be passed to the view controller.set('model', model); // the component that requires current taxon and taxonomies is in application let appController = this.controllerFor('application'); // Define some values let taxon = model.taxon; let taxonomies = model.taxonomies; // Set the values to the application controller appController.set('currentTaxonomy', taxon.get('taxonomy')); appController.set('taxonomies', taxonomies); }, /** * This values will be returned into the route (with the route model) */ searchModel(params) { // Search all the taxonomies and the current taxon return { taxonomies: this.yebo.store.findAll('taxonomy'), taxon: this.yebo.store.find('taxon', params.taxon), }; } });
Handle improperly installed xgboost. Fixes GH-162.
# -*- coding: utf-8 -*- from __future__ import absolute_import __version__ = '0.4.1' from .formatters import format_as_html, format_html_styles, format_as_text from .explain import explain_weights, explain_prediction from .sklearn import explain_weights_sklearn, explain_prediction_sklearn try: from .ipython import show_weights, show_prediction except ImportError: pass # IPython is not installed try: from .lightning import ( explain_prediction_lightning, explain_weights_lightning ) except ImportError as e: # lightning is not available pass try: from .sklearn_crfsuite import ( explain_weights_sklearn_crfsuite ) except ImportError as e: # sklearn-crfsuite is not available pass try: from .xgboost import explain_weights_xgboost except ImportError: # xgboost is not available pass except Exception as e: if e.__class__.__name__ == 'XGBoostLibraryNotFound': # improperly installed xgboost pass else: raise
# -*- coding: utf-8 -*- from __future__ import absolute_import __version__ = '0.4.1' from .formatters import format_as_html, format_html_styles, format_as_text from .explain import explain_weights, explain_prediction from .sklearn import explain_weights_sklearn, explain_prediction_sklearn try: from .ipython import show_weights, show_prediction except ImportError: pass # IPython is not installed try: from .lightning import ( explain_prediction_lightning, explain_weights_lightning ) except ImportError as e: # lightning is not available pass try: from .sklearn_crfsuite import ( explain_weights_sklearn_crfsuite ) except ImportError as e: # sklearn-crfsuite is not available pass try: from .xgboost import explain_weights_xgboost except ImportError: # xgboost is not available pass
OHM-301: Make changes to footer directive html
'use strict'; /* global isCoreVersionCompatible:false */ // Common directive for Footer Version angular.module('openhimConsoleApp') .directive('footerVersion', function(Api, config) { return { template:'<span ng-class="{ \'version-incompatible\': footerVersionsCompatible == false }" ng-if="footerConsoleVersion && footerCoreVersion">' + '(Console <strong>v{{ footerConsoleVersion }}</strong> | Core <strong>v{{ footerCoreVersion }}</strong>)' + '</span>', scope: false, link: function(scope) { var success = function(result) { scope.footerCoreVersion = result.currentCoreVersion; scope.footerConsoleVersion = config.version; scope.footerVersionsCompatible = isCoreVersionCompatible(config.minimumCoreVersion, scope.footerCoreVersion); }; scope.$root.$watch('sessionUser', function(newVal) { if(newVal) { Api.About.query(success); } else { scope.footerCoreVersion = null; scope.footerConsoleVersion = null; } }); } }; });
'use strict'; /* global isCoreVersionCompatible:false */ // Common directive for Footer Version angular.module('openhimConsoleApp') .directive('footerVersion', function(Api, config) { return { template:'<span ng-class="footerVersionsCompatible ? \'\' : \'version-incompatible\'" ng-if="footerConsoleVersion && footerCoreVersion">' + '(Console v{{ footerConsoleVersion }}, Core v{{ footerCoreVersion }})' + '</span>', scope: false, link: function(scope) { var success = function(result) { scope.footerCoreVersion = result.currentCoreVersion; scope.footerConsoleVersion = config.version; scope.footerVersionsCompatible = isCoreVersionCompatible(config.minimumCoreVersion, scope.footerCoreVersion); }; scope.$root.$watch('sessionUser', function(newVal) { if(newVal) { Api.About.query(success); } else { scope.footerCoreVersion = null; scope.footerConsoleVersion = null; } }); } }; });
Add some headers in osu! direct download
from helpers import requestHelper import requests import glob # Exception tracking import tornado.web import tornado.gen import sys import traceback from raven.contrib.tornado import SentryMixin MODULE_NAME = "direct_download" class handler(SentryMixin, requestHelper.asyncRequestHandler): """ Handler for /d/ """ @tornado.web.asynchronous @tornado.gen.engine def asyncGet(self, bid): try: self.set_status(302, "Moved Temporarily") url = "http://m.zxq.co/{}.osz".format(bid) self.add_header("Location", url) self.add_header("Cache-Control", "no-cache") self.add_header("Pragma", "no-cache") print(url) #f = requests.get(url) #self.write(str(f)) except: log.error("Unknown error in {}!\n```{}\n{}```".format(MODULE_NAME, sys.exc_info(), traceback.format_exc())) if glob.sentry: yield tornado.gen.Task(self.captureException, exc_info=True) #finally: # self.finish()
from helpers import requestHelper import requests import glob # Exception tracking import tornado.web import tornado.gen import sys import traceback from raven.contrib.tornado import SentryMixin MODULE_NAME = "direct_download" class handler(SentryMixin, requestHelper.asyncRequestHandler): """ Handler for /d/ """ @tornado.web.asynchronous @tornado.gen.engine def asyncGet(self, bid): try: self.set_status(302) url = "http://m.zxq.co/{}.osz".format(bid) #url = "https://bloodcat.com/osu/s/{}".format(bid) self.add_header("location", url) print(url) #f = requests.get(url) #self.write(str(f)) except: log.error("Unknown error in {}!\n```{}\n{}```".format(MODULE_NAME, sys.exc_info(), traceback.format_exc())) if glob.sentry: yield tornado.gen.Task(self.captureException, exc_info=True) #finally: # self.finish()
Allow user to input "0" as value
import sys import os from workflow import Workflow def main(wf): user_input = wf.args[0] if user_input != '': try: if int(user_input) <= 100 and int(user_input) >= 0: wf.add_item('%s%%' % user_input, arg='%s' % (int(user_input) / 100.0), valid=True) else: wf.add_item('Enter value between 0 and 100') except ValueError: wf.add_item('Enter value between 0 and 100') for i in range(0,120, 20): wf.add_item('%s%%' % i, arg='%s' % (i / 100.0), valid=True) try: current_value = os.popen('./brightness').readline() wf.add_item('Current brightness: %s%%' % int(100 * float(current_value)), valid=False) except ValueError: wf.add_item('Cannot get current brightness') wf.send_feedback() if __name__ == '__main__': wf = Workflow() sys.exit(wf.run(main))
import sys import os from workflow import Workflow def main(wf): user_input = wf.args[0] if user_input != '': try: if int(user_input) <= 100 and int(user_input) > 0: wf.add_item('%s%%' % user_input, arg='%s' % (int(user_input) / 100.0), valid=True) else: wf.add_item('Enter value between 0 and 100') except ValueError: wf.add_item('Enter value between 0 and 100') for i in range(0,120, 20): wf.add_item('%s%%' % i, arg='%s' % (i / 100.0), valid=True) try: current_value = os.popen('./brightness').readline() wf.add_item('Current brightness: %s%%' % int(100 * float(current_value)), valid=False) except ValueError: wf.add_item('Cannot get current brightness') wf.send_feedback() if __name__ == '__main__': wf = Workflow() sys.exit(wf.run(main))
Make sure the weight column is specific.
<?php namespace AbleCore; class TaxonomyTerm extends EntityExtension { /** * Gets the entity type of the current class. * * @return string The entity type. */ static function getEntityType() { return 'taxonomy_term'; } /** * By Vocabulary * * Gets all taxonomy terms by the specified vocabulary. * * @param string $vocabulary_machine_name The machine name of the vocabulary. * * @return array An array of TaxonomyTerm items. */ public static function byVocabulary($vocabulary_machine_name) { $query = db_select('taxonomy_term_data', 'td'); $query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid'); $query->condition('tv.machine_name', $vocabulary_machine_name); $query->addField('td', 'tid'); $query->orderBy('td.weight'); return static::mapQuery($query); } }
<?php namespace AbleCore; class TaxonomyTerm extends EntityExtension { /** * Gets the entity type of the current class. * * @return string The entity type. */ static function getEntityType() { return 'taxonomy_term'; } /** * By Vocabulary * * Gets all taxonomy terms by the specified vocabulary. * * @param string $vocabulary_machine_name The machine name of the vocabulary. * * @return array An array of TaxonomyTerm items. */ public static function byVocabulary($vocabulary_machine_name) { $query = db_select('taxonomy_term_data', 'td'); $query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid'); $query->condition('tv.machine_name', $vocabulary_machine_name); $query->addField('td', 'tid'); $query->orderBy('weight'); return static::mapQuery($query); } }
Move views folder into src
<?php require_once __DIR__.'/../vendor/autoload.php'; require __DIR__.'/config.php'; $app = new Silex\Application(); // use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder; $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider()); $app->register(new Silex\Provider\FormServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); // register providers $app->register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../src/views', 'twig.class_path' => __DIR__.'/../vendor/twig/lib', 'twig.cache' => (!DEBUG_APP), // disble caching when debugging )); $app['debug'] = DEBUG_APP; return $app;
<?php // require 'autoload.php'; require_once __DIR__.'/../vendor/autoload.php'; require __DIR__.'/config.php'; $app = new Silex\Application(); // use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder; $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider()); $app->register(new Silex\Provider\FormServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); // register providers $app->register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../views', 'twig.class_path' => __DIR__.'/../vendor/twig/lib', 'twig.cache' => (!DEBUG_APP), // disble caching when debugging )); $app['debug'] = DEBUG_APP; return $app;
Add comments & cleanup formatting.
var noop = function noop () {}; // HOF Wraps the native Promise API // to add take a shouldCancel promise and add // an onCancel() callback. var speculation = function speculation (fn) { // Don't cancel by default var cancel = ( arguments.length > 1 && arguments[1] !== undefined ) ? arguments[1] : Promise.reject(); return new Promise(function (resolve, reject) { var onCancel = function onCancel (handleCancel) { return cancel.then( handleCancel, // Ignore expected cancel rejections: noop ) // handle onCancel errors .catch(function (e) { return reject(e); }); }; fn(resolve, reject, onCancel); }); }; module.exports = speculation;
var speculation = function speculation (fn) { // Don't cancel by default: var cancel = ( arguments.length > 1 && arguments[1] !== undefined ) ? arguments[1] : Promise.reject(); return new Promise(function (resolve, reject) { var noop = function noop () {}; var onCancel = function onCancel (handleCancel) { return cancel.then( handleCancel, // Filter out the expected "not cancelled" rejection: noop ).catch(function (e) { // Reject the speculation if there's a an error in // onCancel: return reject(e); }); }; return fn(resolve, reject, onCancel); }); }; module.exports = speculation;
Remove altruja script from page.
<?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--[if lt IE 7]><div class="alert">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</div><![endif]--> <div class="wrap" role="document"> <?php get_template_part('templates/header'); ?> <div class="content container-fluid row"> <?php get_template_part('templates/social_media_icons'); ?> <div class="main" role="main"> <?php include roots_template_path(); ?> </div><!-- /.main --> </div><!-- /.content --> <?php get_template_part('templates/footer'); ?> </div><!-- /.wrap --> </body> </html>
<?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--<script src="https://www.altruja.de/i/lcov"></script><span id="ef-bl-x7jn2nd9j">Ein <a href="http://www.altruja.de/spendenformular.html" title="Spendenformular online">Spendenformular</a> von Altruja.</span>--> <!--[if lt IE 7]><div class="alert">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</div><![endif]--> <div class="wrap" role="document"> <?php get_template_part('templates/header'); ?> <div class="content container-fluid row"> <?php get_template_part('templates/social_media_icons'); ?> <div class="main" role="main"> <?php include roots_template_path(); ?> </div><!-- /.main --> </div><!-- /.content --> <?php get_template_part('templates/footer'); ?> </div><!-- /.wrap --> </body> </html>
Make a read-only node table check it is used read-only. git-svn-id: bc509ec38c1227b3e85ea1246fda136342965d36@1348166 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.hpl.jena.tdb.nodetable; import com.hp.hpl.jena.graph.Node ; import com.hp.hpl.jena.tdb.TDBException ; import com.hp.hpl.jena.tdb.store.NodeId ; public class NodeTableReadonly extends NodeTableWrapper { public NodeTableReadonly(NodeTable nodeTable) { super(nodeTable) ; } @Override public NodeId getAllocateNodeId(Node node) { NodeId nodeId = getNodeIdForNode(node) ; if ( NodeId.isDoesNotExist(nodeId) ) throw new TDBException("Allocation attempt on NodeTableReadonly") ; return nodeId ; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.hpl.jena.tdb.nodetable; public class NodeTableReadonly extends NodeTableWrapper { public NodeTableReadonly(NodeTable nodeTable) { super(nodeTable) ; } }
Add an explicit related name
from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) user = models.ForeignKey( 'auth.User', related_name='django_split_experiment_groups', ) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), )
from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) user = models.ForeignKey('auth.User', related_name=None) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), )
Use array key lookup to check action method
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Middleware; class VerifyUserAlways extends VerifyUser { const GET_ACTION_METHODS = [ 'GET' => true, 'HEAD' => true, 'OPTIONS' => true, ]; public static function isRequired($user) { return $user !== null && ($user->isPrivileged() || $user->isInactive()); } public function requiresVerification($request) { if ($this->user === null) { return false; } $method = $request->getMethod(); $isPostAction = config('osu.user.post_action_verification') ? !isset(static::GET_ACTION_METHODS[$method]) : false; $isRequired = $isPostAction || $method === 'DELETE' || session()->get('requires_verification'); return $isRequired; } }
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Middleware; class VerifyUserAlways extends VerifyUser { public static function isRequired($user) { return $user !== null && ($user->isPrivileged() || $user->isInactive()); } public function requiresVerification($request) { if ($this->user === null) { return false; } $method = $request->getMethod(); $isPostAction = config('osu.user.post_action_verification') ? !in_array($method, ['GET', 'HEAD', 'OPTIONS'], true) : false; $isRequired = $isPostAction || $method === 'DELETE' || session()->get('requires_verification'); return $isRequired; } }
Remove faulty dependency on magicwright repo Fixes #37
package main import ( "time" "github.com/didip/tollbooth" "github.com/didip/tollbooth/thirdparty/tollbooth_fasthttp" "github.com/valyala/fasthttp" ) func main() { requestHandler := func(ctx *fasthttp.RequestCtx) { switch string(ctx.Path()) { case "/hello": helloHandler(ctx) default: ctx.Error("Unsupporterd path", fasthttp.StatusNotFound) } } // Create a limiter struct. limiter := tollbooth.NewLimiter(1, time.Second) fasthttp.ListenAndServe(":4444", tollbooth_fasthttp.LimitHandler(requestHandler, limiter)) } func helloHandler(ctx *fasthttp.RequestCtx) { ctx.SetStatusCode(fasthttp.StatusOK) ctx.SetBody([]byte("Hello, World!")) }
package main import ( "time" "github.com/didip/tollbooth" "github.com/magicwrighter/tollbooth/thirdparty/tollbooth_fasthttp" "github.com/valyala/fasthttp" ) func main() { requestHandler := func(ctx *fasthttp.RequestCtx) { switch string(ctx.Path()) { case "/hello": helloHandler(ctx) default: ctx.Error("Unsupporterd path", fasthttp.StatusNotFound) } } // Create a limiter struct. limiter := tollbooth.NewLimiter(1, time.Second) fasthttp.ListenAndServe(":4444", tollbooth_fasthttp.LimitHandler(requestHandler, limiter)) } func helloHandler(ctx *fasthttp.RequestCtx) { ctx.SetStatusCode(fasthttp.StatusOK) ctx.SetBody([]byte("Hello, World!")) }
Add raw request field to request
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/does-python-have-a-module-for-parsing-http-requests-and-responses print request.command # "GET" print request.path # "/who/ken/trust.html" print request.request_version # "HTTP/1.1" print len(request.headers) # 3 print request.headers.keys() # ['accept-charset', 'host', 'accept'] print request.headers['host'] # "cm.bell-labs.com" """ def __init__(self, request_text): self.rfile = StringIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request() self.data = request_text def send_error(self, code, message): self.error_code = code self.error_message = message
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/does-python-have-a-module-for-parsing-http-requests-and-responses print request.command # "GET" print request.path # "/who/ken/trust.html" print request.request_version # "HTTP/1.1" print len(request.headers) # 3 print request.headers.keys() # ['accept-charset', 'host', 'accept'] print request.headers['host'] # "cm.bell-labs.com" """ def __init__(self, request_text): self.rfile = StringIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request() def send_error(self, code, message): self.error_code = code self.error_message = message
Update contexts to be correct for test.
package api_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "../go-webservice" "net/http" "net/http/httptest" ) var _ = Describe("Web", func() { var ( page *Page ) BeforeEach(func() { page = &Page{Title: "foo", Body: []byte("Example body")} page.Save() }) Describe("Fetching a page", func() { Context("by ID", func() { It("it has a JSON representation", func() { request, _ := http.NewRequest("GET", "/pages/foo", nil) response := httptest.NewRecorder() ViewHandler(response, request, "foo") expectedJSON := `{"title":"foo","body":"Example body"}` Expect(response.Body.String()).To(Equal(expectedJSON)) }) }) }) })
package api_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "../go-webservice" "net/http" "net/http/httptest" ) var _ = Describe("Web", func() { var ( page *Page ) BeforeEach(func() { page = &Page{Title: "foo", Body: []byte("Example body")} page.Save() }) Describe("Categorizing book length", func() { Context("With more than 300 pages", func() { It("should be a novel", func() { request, _ := http.NewRequest("GET", "/pages/foo", nil) response := httptest.NewRecorder() ViewHandler(response, request, "foo") expectedJSON := `{"title":"foo","body":"Example body"}` Expect(response.Body.String()).To(Equal(expectedJSON)) }) }) }) })
Add sigma0 and alpha AMR parameters to the function.
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = -df.grad(u) costheta = df.dot(m, E) sigma = s0/(1 + alpha*costheta**2) F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive()
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = df.grad(u) costheta = df.dot(m, E) sigma = 1/(1 + costheta**2) F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive()
Remove unnecessary coerce to int Since Django commit https://github.com/django/django/commit/190d2ff4a7a392adfe0b12552bd71871791d87aa HttpResponse.status_code is always an int.
from django.template.response import SimpleTemplateResponse from django.utils.translation import gettext_lazy as _ from debug_toolbar.panels import Panel class RedirectsPanel(Panel): """ Panel that intercepts redirects and displays a page with debug info. """ has_content = False nav_title = _("Intercept redirects") def process_request(self, request): response = super().process_request(request) if 300 <= response.status_code < 400: redirect_to = response.get("Location", None) if redirect_to: status_line = "{} {}".format( response.status_code, response.reason_phrase ) cookies = response.cookies context = {"redirect_to": redirect_to, "status_line": status_line} # Using SimpleTemplateResponse avoids running global context processors. response = SimpleTemplateResponse( "debug_toolbar/redirect.html", context ) response.cookies = cookies response.render() return response
from django.template.response import SimpleTemplateResponse from django.utils.translation import gettext_lazy as _ from debug_toolbar.panels import Panel class RedirectsPanel(Panel): """ Panel that intercepts redirects and displays a page with debug info. """ has_content = False nav_title = _("Intercept redirects") def process_request(self, request): response = super().process_request(request) if 300 <= int(response.status_code) < 400: redirect_to = response.get("Location", None) if redirect_to: status_line = "{} {}".format( response.status_code, response.reason_phrase ) cookies = response.cookies context = {"redirect_to": redirect_to, "status_line": status_line} # Using SimpleTemplateResponse avoids running global context processors. response = SimpleTemplateResponse( "debug_toolbar/redirect.html", context ) response.cookies = cookies response.render() return response
chore(release): Update artifact tagging script to widen @uirouter/core dependency before pushing
#!env node "use strict"; let pkg = require('../package.json'); let version = pkg.version; require('shelljs/global'); let readlineSync = require('readline-sync'); let fs = require('fs'); let path = require('path'); let util = require('./util'); let _exec = util._exec; cd(path.join(__dirname, '..')); var widen = false; var coreDep = pkg.dependencies['@uirouter/core']; var isNarrow = /^[[=~]?(\d.*)/.exec(coreDep); var widenedDep = isNarrow && '^' + isNarrow[1]; if (isNarrow && readlineSync.keyInYN('Widen @uirouter/core dependency from ' + coreDep + ' to ' + widenedDep + '?')) { widen = false; } if (!readlineSync.keyInYN('Ready to publish to ' + version + '-artifacts tag?')) { process.exit(1); } util.ensureCleanMaster('master'); // then tag and push tag _exec(`git checkout -b ${version}-artifacts-prep`); pkg.dependencies['@uirouter/core'] = widenedDep; fs.writeFileSync("package.json", JSON.stringify(pkg, undefined, 2)); _exec('git commit -m "Widening @uirouter/core dependency range to ' + widenedDep + '" package.json'); _exec('npm run package'); _exec(`git add --force lib _bundles`); _exec(`git commit -m 'chore(*): commiting build files'`); _exec(`git tag ${version}-artifacts`); _exec(`git push -u origin ${version}-artifacts`); _exec(`git checkout master`); _exec(`git branch -D ${version}-artifacts-prep`);
#!env node "use strict"; let version = require('../package.json').version; require('shelljs/global'); let readlineSync = require('readline-sync'); let fs = require('fs'); let path = require('path'); let util = require('./util'); let _exec = util._exec; cd(path.join(__dirname, '..')); if (!readlineSync.keyInYN('Ready to publish to ' + version + '-artifacts tag?')) { process.exit(1); } util.ensureCleanMaster('master'); _exec('npm run package'); // then tag and push tag _exec(`git checkout -b ${version}-artifacts-prep`); _exec(`git add --force lib _bundles`); _exec(`git commit -m 'chore(*): commiting build files'`); _exec(`git tag ${version}-artifacts`); _exec(`git push -u origin ${version}-artifacts`); _exec(`git checkout master`); _exec(`git branch -D ${version}-artifacts-prep`);
Update test for new interface.
package converter; import processors.XmlToJsonConverter; import org.junit.Test; import static org.junit.Assert.assertTrue; public class XmlToJsonConverterTest { /** * Test conversion from xml to json. */ @Test public void convertXmlToJsonTest() { String xmlString = "<note>\n" + "<to>Tove</to>\n" + "<from>Jani</from>\n" + "<heading>Reminder</heading>\n" + "<body>Don't forget me this weekend!</body>\n" + "</note>"; String jsonString = null; try { jsonString = new XmlToJsonConverter().process(xmlString, null); } catch (Throwable throwable) { throwable.printStackTrace(); } String expectedJsonResult = "{\"note\":{\"heading\":\"Reminder\",\"from\":\"Jani\",\"to\":\"Tove\",\"body\":\"Don't forget me this weekend!\"}}"; assertTrue(expectedJsonResult.equals(expectedJsonResult)); } }
package converter; import converters.XmlToJsonConverter; import org.junit.Test; import static org.junit.Assert.assertTrue; public class XmlToJsonConverterTest { /** * Test conversion from xml to json. */ @Test public void convertXmlToJsonTest() { String xmlString = "<note>\n" + "<to>Tove</to>\n" + "<from>Jani</from>\n" + "<heading>Reminder</heading>\n" + "<body>Don't forget me this weekend!</body>\n" + "</note>"; String jsonString = XmlToJsonConverter.convertXmlToJson(xmlString); String expectedJsonResult = "{\"note\":{\"heading\":\"Reminder\",\"from\":\"Jani\",\"to\":\"Tove\",\"body\":\"Don't forget me this weekend!\"}}"; assertTrue(expectedJsonResult.equals(expectedJsonResult)); } }
Update the initial admin creation object when executing the environment for the first time with no User models. This update keeps the model consistent with the changes made to the User model.
/** * This script automatically creates a default Admin user when an * empty database is used for the first time. You can use this * technique to insert data into any List you have defined. * * Alternatively, you can export a custom function for the update: * module.exports = function(done) { ... } */ exports.create = { User: [{ userType: 'Administrator', name: { first: 'Admin', last: 'User' }, email: 'admin@keystonejs.com', password: 'admin' }] }; /* // This is the long-hand version of the functionality above: var keystone = require('keystone'), async = require('async'), User = keystone.list('User'); var admins = [ { email: 'user@keystonejs.com', password: 'admin', name: { first: 'Admin', last: 'User' } } ]; function createAdmin(admin, done) { var newAdmin = new User.model(admin); newAdmin.isAdmin = true; newAdmin.save(function(err) { if (err) { console.error("Error adding admin " + admin.email + " to the database:"); console.error(err); } else { console.log("Added admin " + admin.email + " to the database."); } done(err); }); } exports = module.exports = function(done) { async.forEach(admins, createAdmin, done); }; */
/** * This script automatically creates a default Admin user when an * empty database is used for the first time. You can use this * technique to insert data into any List you have defined. * * Alternatively, you can export a custom function for the update: * module.exports = function(done) { ... } */ exports.create = { User: [ { 'name.first': 'Admin', 'name.last': 'User', email: 'admin@keystonejs.com', password: 'admin', isAdmin: true } ] }; /* // This is the long-hand version of the functionality above: var keystone = require('keystone'), async = require('async'), User = keystone.list('User'); var admins = [ { email: 'user@keystonejs.com', password: 'admin', name: { first: 'Admin', last: 'User' } } ]; function createAdmin(admin, done) { var newAdmin = new User.model(admin); newAdmin.isAdmin = true; newAdmin.save(function(err) { if (err) { console.error("Error adding admin " + admin.email + " to the database:"); console.error(err); } else { console.log("Added admin " + admin.email + " to the database."); } done(err); }); } exports = module.exports = function(done) { async.forEach(admins, createAdmin, done); }; */
Revert "force a build failure through jshint" This reverts commit b956ecf5a9c62053a60f210b3ef0ba4b9ff0a8eb.
import Ember from 'ember'; const get = Ember.get; const { guidFor } = Ember; function updateTitle(tokens) { document.title = tokens.toString(); } export default Ember.Helper.extend({ pageTitleList: Ember.inject.service(), init() { this._super(); let tokens = get(this, 'pageTitleList'); tokens.push({ id: guidFor(this) }); }, compute(params, hash) { let tokens = get(this, 'pageTitleList'); hash.id = guidFor(this); hash.title = params.join(''); tokens.push(hash); Ember.run.scheduleOnce('afterRender', null, updateTitle, tokens); return ''; }, destroy() { let tokens = get(this, 'pageTitleList'); let id = guidFor(this); tokens.remove(id); Ember.run.scheduleOnce('afterRender', null, updateTitle, tokens); } });
import Ember from 'ember'; const get = Ember.get; const { guidFor } = Ember function updateTitle(tokens) { document.title = tokens.toString(); } export default Ember.Helper.extend({ pageTitleList: Ember.inject.service(), init() { this._super(); let tokens = get(this, 'pageTitleList'); tokens.push({ id: guidFor(this) }); }, compute(params, hash) { let tokens = get(this, 'pageTitleList'); hash.id = guidFor(this); hash.title = params.join(''); tokens.push(hash); Ember.run.scheduleOnce('afterRender', null, updateTitle, tokens); return ''; }, destroy() { let tokens = get(this, 'pageTitleList'); let id = guidFor(this); tokens.remove(id); Ember.run.scheduleOnce('afterRender', null, updateTitle, tokens); } });
Replace console log with proper logging and trim output
// install: npm install // run: gulp var gulp = require('gulp'); var watch = require('gulp-watch'); var exec = require('child_process').exec; var log = require('gulplog'); gulp.task('default', function () { // Generate current version log.info('Generating...'); exec('vendor/bin/statie generate source', function (err, stdout, stderr) { stdout ? log.info(stdout.trim()) : null; stderr ? log.error("Error:\n" + stderr.trim()) : null; }); // Run local server, open localhost:8000 in your browser // needs to listen on 0.0.0.0 to work in Docker on windows exec('php -S 0.0.0.0:8000 -t output'); console.log('Local PHP server started at "http://localhost:8000", open browser to see it.'); // For the second arg see: https://github.com/floatdrop/gulp-watch/issues/242#issuecomment-230209702 return watch(['source/**/*', '!**/*___jb_tmp___'], function () { log.info('Regenerating...'); exec('vendor/bin/statie generate source', function (err, stdout, stderr) { stdout ? log.info(stdout.trim()) : null; stderr ? log.error("Error:\n" + stderr.trim()) : null; }); }); });
// install: npm install // run: gulp var gulp = require('gulp'); var watch = require('gulp-watch'); var exec = require('child_process').exec; var log = require('gulplog'); gulp.task('default', function () { // Generate current version log.info('Generating...'); exec('vendor/bin/statie generate source', function (err, stdout, stderr) { console.log(stdout); console.error(stderr); }); // Run local server, open localhost:8000 in your browser // needs to listen on 0.0.0.0 to work in Docker on windows exec('php -S 0.0.0.0:8000 -t output'); console.log('Local PHP server started at "http://localhost:8000", open browser to see it.'); // For the second arg see: https://github.com/floatdrop/gulp-watch/issues/242#issuecomment-230209702 return watch(['source/**/*', '!**/*___jb_tmp___'], function () { log.info('Regenerating...'); exec('vendor/bin/statie generate source', function (err, stdout, stderr) { console.log(stdout); console.error(stderr); }); }); });
Fix keep turning spinner when error occurred
import sys import traceback from bush import option from bush.spinner import Spinner from bush.aws.ec2 import EC2 from bush.aws.iam import IAM def run(): (options, args) = option.parse_args("bush") output = '' spinner = Spinner() spinner.start() try: output = run_aws(options, args) except: spinner.stop() traceback.print_exc() sys.exit(2) spinner.stop() if output: print("\n".join(output)) def run_aws(options, args): if args[0] == 'ec2': ec2 = EC2(options) if args[1] == 'ls': output = ec2.ls() elif args[1] == "images": output = ec2.images() if args[0] == 'iam': iam = IAM(options) if args[1] == 'users': output = iam.list_users() if args[1] == 'keys': output = iam.list_access_keys() return output
from bush import option from bush.spinner import Spinner from bush.aws.ec2 import EC2 from bush.aws.iam import IAM def run(): (options, args) = option.parse_args("bush") output = '' spinner = Spinner() spinner.start() if args[0] == 'ec2': ec2 = EC2(options) if args[1] == 'ls': output = ec2.ls() elif args[1] == "images": output = ec2.images() if args[0] == 'iam': iam = IAM(options) if args[1] == 'users': output = iam.list_users() if args[1] == 'keys': output = iam.list_access_keys() spinner.stop() if output: print("\n".join(output))
Add tests to main testacular test file rherlitz/GooEngine#52
require.config({ paths: { "goo": "src/goo", "test": "test" }, waitSeconds: 5 }); require([ // Require does not allow us to add dependencies with wildcards... 'test/math/MathUtils', 'test/math/Matrix', 'test/math/Matrix2x2', 'test/math/Matrix3x3', 'test/math/Matrix4x4', 'test/math/Plane', 'test/math/Quaternion', 'test/math/Ray', 'test/math/Transform', 'test/math/Vector', 'test/math/Vector2', 'test/math/Vector3', 'test/math/Vector4', 'test/math/Versor', 'test/shapesTest', 'test/entities/entitiesTest' ], function(mathTest) { window.__testacular__.start(); });
require.config({ paths: { "goo": "src/goo", "test": "test" }, waitSeconds: 5 }); require([ // Require does not allow us to add dependencies with wildcards... 'test/math/MathUtils', 'test/math/Matrix', 'test/math/Matrix2x2', 'test/math/Matrix3x3', 'test/math/Matrix4x4', 'test/math/Quaternion', 'test/math/Transform', 'test/math/Vector', 'test/math/Vector2', 'test/math/Vector3', 'test/math/Vector4', 'test/shapesTest', 'test/entities/entitiesTest' ], function(mathTest) { window.__testacular__.start(); });
Fix typo in observable name.
(function () { 'use strict'; define( [ 'lodash', 'knockout' ], function (_, ko) { var AVAILABLE_MODES = [ 'List', 'Thumbnails', 'Table' ]; return function (mode) { this.mode = ko.observable(mode || AVAILABLE_MODES[0]); this.availableModes = ko.pureComputed(function () { return AVAILABLE_MODES; }); this.resultsContainerClassName = ko.pureComputed(function () { return 'results-container-' + this.mode().toLowerCase(); }.bind(this)); }; } ); }());
(function () { 'use strict'; define( [ 'lodash', 'knockout' ], function (_, ko) { var AVAILABLE_MODES = [ 'List', 'Thumbnails', 'Table' ]; return function (mode) { this.mode = ko.observable(mode || AVAILABLE_MODES[0]); this.availableModes = ko.pureComputed(function () { return AVAILABLE_MODES; }); this.resultsContainerClassName = ko.pureComputed(function () { return 'results-container-' + this.resultsMode().toLowerCase(); }.bind(this)); }; } ); }());
Add license type and fix typo
import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='timeflow', packages=['timeflow'], version='0.2', description='Small CLI time logger', author='Justas Trimailovas', author_email='j.trimailovas@gmail.com', url='https://github.com/trimailov/timeflow', license='MIT', keywords=['timelogger', 'logging', 'timetracker', 'tracker'], long_description=read('README.rst'), entry_points=''' [console_scripts] timeflow=timeflow.main:main tf=timeflow.main:main ''', )
import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='timeflow', packages=['timeflow'], version='0.2', description='Small CLI time logger', author='Justas Trimailovas', author_email='j.trimailvoas@gmail.com', url='https://github.com/trimailov/timeflow', keywords=['timelogger', 'logging', 'timetracker', 'tracker'], long_description=read('README.rst'), entry_points=''' [console_scripts] timeflow=timeflow.main:main tf=timeflow.main:main ''', )
Implement the job better - minor bugfix
<?php /** * Composer Update checker job. Runs the check as a queuedjob. * * @author Peter Thaleikis * @license MIT */ class CheckComposerUpdatesJob extends AbstractQueuedJob implements QueuedJob { /** * The task to run * * @var BuildTask */ protected $task; /** * define the title * * @return string */ public function getTitle() { return _t( 'ComposerUpdateChecker.Title', 'Check if composer updates are available' ); } /** * define the type. */ public function getJobType() { $this->totalSteps = 1; return QueuedJob::QUEUED; } /** * init */ public function setup() { // create the instance of the task $this->task = new CheckComposerUpdatesTask(); } /** * processes the task as a job */ public function process() { // run the task $this->task->run(new SS_HTTPRequest()); // mark job as completed $this->isComplete = true; } }
<?php /** * Composer Update checker job. Runs the check as a queuedjob. * * @author Peter Thaleikis * @license MIT */ class CheckComposerUpdatesJob extends AbstractQueuedJob implements QueuedJob { /** * The task to run * * @var BuildTask */ protected $task; /** * define the title * * @return string */ public function getTitle() { return _t( 'ComposerUpdateChecker.Title', 'Check if composer updates are available' ); } /** * define the type. */ public function getJobType() { $this->totalSteps = 1; return QueuedJob::QUEUED; } /** * init */ public function setup() { // create the instance of the task $this->task = new CheckComposerUpdatesTask(); } /** * process the */ public function process() { $this->task->run(new SS_HTTPRequest()); } }
Add confirm on end game door
import NormalDoor from 'entities/Door'; import state from 'state'; import finish from 'finish'; import action from 'action'; import { changeScene } from 'currentScene'; import entrance from 'scenes/circleBurger/entrance'; export default class Door extends NormalDoor { actions() { return [ action(this.actionName, () => { changeScene(this.destination); state.currentTime.add(Math.floor((Math.random() * 5) + 1), 'minutes'); }), action("Lock the door. (This ends the game. You can't go back.)", () => { if(confirm("Closing the Circle Burger ends the day.\n\nAre you sure you've done enough to keep your job?")) { state.doorLocked = true; if (this.destination === entrance) { state.lockedIn = true; } if (state.currentTime.isBefore(state.closingTime.clone().subtract(5, 'minutes'))) { state.closedEarly = true; } if (state.currentTime.isAfter( state.closingTime.clone().add(1, 'hour') )) { state.closedLate = true; } finish(); } }) ]; } };
import NormalDoor from 'entities/Door'; import state from 'state'; import finish from 'finish'; import action from 'action'; import { changeScene } from 'currentScene'; import entrance from 'scenes/circleBurger/entrance'; export default class Door extends NormalDoor { actions() { return [ action(this.actionName, () => { changeScene(this.destination); state.currentTime.add(Math.floor((Math.random() * 5) + 1), 'minutes'); }), action("Lock the door. (This ends the game. You can't go back.)", () => { state.doorLocked = true; if (this.destination === entrance) { state.lockedIn = true; } if (state.currentTime.isBefore(state.closingTime.clone().subtract(5, 'minutes'))) { state.closedEarly = true; } if (state.currentTime.isAfter( state.closingTime.clone().add(1, 'hour') )) { state.closedLate = true; } finish(); }) ]; } };
Make Stack server example better.
var FC = require('modbus-stack').FUNCTION_CODES; require('modbus-stack/server').createServer( require('stack')( // Handle "Read Coils" (well, we just call `next()`...) functionCode(FC.READ_COILS, function(req, res, next) { console.log('Got request for "Read Coils", but passing it on...'); next(); }), // Handle "Read Input Registers" functionCode(FC.READ_INPUT_REGISTERS, function(req, res, next) { console.log('Got "Read Input Registers" request [ ' + req.startAddress + "-" + req.quantity + ' ]'); var resp = new Array(req.quantity); for (var i=0; i < req.quantity; i++) { resp[i] = req.startAddress + i; } res.writeResponse(resp); }), // If all else fails, respond with "Illegal Function" illegalFunction ) ).listen(502); function functionCode(fc, callback) { return function(req, res, next) { req.functionCode === fc ? callback.apply(this, arguments) : next(); } } function illegalFunction(request, response, err) { var errCode = err && err.errno ? err.errno : 1; console.log("responding with exception: " + errCode); response.writeException(errCode); }
require('modbus-stack'); require('modbus-stack/server').createServer( require('stack')( // Handle "Read Coils" (well, we just call `next()`...) functionCode(1, function(req, res, next) { console.log("Got request for '1', but passing it on..."); next(); }), // Handle "Read Input Registers" functionCode(4, function(req, res, next) { var resp = new Array(req.quantity); for (var i=0; i < req.quantity; i++) { resp[i] = req.startAddress + i; } res.writeResponse(resp); }), // If all else fails, call our "Illegal Function" response. illegalFunction ) ).listen(502); function functionCode(fc, callback) { return function(req, res, next) { if (req.functionCode === fc) { callback.apply(this, arguments); } else { next(); } } } function illegalFunction(request, response, err) { var errCode = err && err.errno ? err.errno : 1; console.log("responding with exception: " + errCode); response.writeException(errCode); }
Fix so that application is due to 24:00 the 2.
from django.shortcuts import render from applications.forms import ApplicationForm from datetime import datetime from django.views.generic.edit import FormView APPLICATION_START_DATE = datetime(2018, 8, 13) APPLICATION_END_DATE = datetime(2018, 9, 3) class ApplicationView(FormView): template_name = 'applications/application_form.html' form_class = ApplicationForm success_url = '/opptak/success' def form_valid(self, form): form.send_email() form.save() return super(ApplicationView, self).form_valid(form) def dispatch(self, request, *args, **kwargs): current_date = datetime.now() if current_date < APPLICATION_START_DATE: return render(request, 'applications/application_too_early.html') elif current_date > APPLICATION_END_DATE: return render(request, 'applications/application_too_late.html') else: return super(ApplicationView, self).dispatch(request, *args, **kwargs)
from django.shortcuts import render from applications.forms import ApplicationForm from datetime import datetime from django.views.generic.edit import FormView APPLICATION_START_DATE = datetime(2018, 8, 13) APPLICATION_END_DATE = datetime(2018, 9, 2, 1, 0, 0) class ApplicationView(FormView): template_name = 'applications/application_form.html' form_class = ApplicationForm success_url = '/opptak/success' def form_valid(self, form): form.send_email() form.save() return super(ApplicationView, self).form_valid(form) def dispatch(self, request, *args, **kwargs): current_date = datetime.now() if current_date < APPLICATION_START_DATE: return render(request, 'applications/application_too_early.html') elif current_date > APPLICATION_END_DATE: return render(request, 'applications/application_too_late.html') else: return super(ApplicationView, self).dispatch(request, *args, **kwargs)
Add support for German language
/******************************************************************************* * Copyright 2015 France Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.francelabs.datafari.utils; import java.util.Arrays; import java.util.List; /** * Language Utility class * * @author France Labs * */ public class LanguageUtils { public static final List<String> availableLanguages = Arrays.asList("en", "fr", "it", "pt_br", "de"); }
/******************************************************************************* * Copyright 2015 France Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.francelabs.datafari.utils; import java.util.Arrays; import java.util.List; /** * Language Utility class * * @author France Labs * */ public class LanguageUtils { public static final List<String> availableLanguages = Arrays.asList("en", "fr", "it", "pt_br"); }
Use double quotes in script
'use strict'; (function () { var React = require('react'); var analyticsScript = '(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){' + '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),' + 'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)' + '})(window,document,"script","https://www.google-analytics.com/analytics.js","ga");' + 'ga("create", "UA-64450504-3", "auto");' + 'ga("send", "pageview");'; var Analytics = React.createClass({ render: function () { return ( <script type="text/javascript" dangerouslySetInnerHTML={{__html: analyticsScript}} /> ); } }); module.exports = Analytics; })();
'use strict'; (function () { var React = require('react'); var analyticsScript = '(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){' + '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),' + 'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)' + '})(window,document,\'script\',\'https://www.google-analytics.com/analytics.js\',\'ga\');' + 'ga(\'create\', \'UA-64450504-3\', \'auto\');' + 'ga(\'send\', \'pageview\');'; var Analytics = React.createClass({ render: function () { return ( <script type="text/javascript" dangerouslySetInnerHTML={{__html: analyticsScript}} /> ); } }); module.exports = Analytics; })();
Update listed modules to ignore
'use strict' var isPresent = require('is-present') var githubRepos = require('github-repositories') var Promise = require('pinkie-promise') var reposToIgnore = [ 'tachyons', 'tachyons-cli', 'tachyons-docs', 'tachyons-cms', 'tachyons-modules', 'tachyons-css.github.io', 'tachyons-sass', 'tachyons-styles', 'tachyons-queries', 'tachyons-z-index', 'tachyons-webpack' ] module.exports = function tachyonsModules () { return githubRepos('tachyons-css').then(function (repos) { if (isPresent(repos)) { return repos.filter(isCssModule) } else { return Promise.reject(new Error('No results found for tachyons-css')) } }) } function isCssModule (repo) { return reposToIgnore.indexOf(repo.name) === -1 }
'use strict' var isPresent = require('is-present') var githubRepos = require('github-repositories') var Promise = require('pinkie-promise') var reposToIgnore = [ 'tachyons', 'tachyons-cli', 'tachyons-docs', 'tachyons-cms', 'tachyons-modules', 'tachyons-css.github.io', 'tachyons-sass', 'tachyons-styles', 'tachyons-queries', 'tachyons-webpack' ] module.exports = function tachyonsModules () { return githubRepos('tachyons-css').then(function (repos) { if (isPresent(repos)) { return repos.filter(isCssModule) } else { return Promise.reject(new Error('No results found for tachyons-css')) } }) } function isCssModule (repo) { return reposToIgnore.indexOf(repo.name) === -1 }
Add instructions README as package data
from setuptools import setup, find_packages setup( name='pythonwarrior', version='0.0.3', packages=find_packages(), package_data={'pythonwarrior': ['templates/README']}, scripts=['bin/pythonwarrior'], author="Richard Lee", author_email="rblee88@gmail.com", description=("Game written in Python for learning Python and AI - " "a Python port of ruby-warrior"), long_description=open('README.rst').read(), install_requires=['jinja2'], license="MIT", url="https://github.com/arbylee/python-warrior", keywords="python ruby warrior rubywarrior pythonwarrior", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha" ] )
from setuptools import setup, find_packages setup( name='pythonwarrior', version='0.0.3', packages=find_packages(), scripts=['bin/pythonwarrior'], author="Richard Lee", author_email="rblee88@gmail.com", description=("Game written in Python for learning Python and AI - " "a Python port of ruby-warrior"), long_description=open('README.rst').read(), install_requires=['jinja2'], license="MIT", url="https://github.com/arbylee/python-warrior", keywords="python ruby warrior rubywarrior pythonwarrior", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha" ] )
Remove old norelease comment, the test is okay as it is
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.BaseAggregationTestCase; import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder; public class FilterTests extends BaseAggregationTestCase<FilterAggregationBuilder> { @Override protected FilterAggregationBuilder createTestAggregatorBuilder() { return new FilterAggregationBuilder(randomAlphaOfLengthBetween(1, 20), QueryBuilders.termQuery(randomAlphaOfLengthBetween(5, 20), randomAlphaOfLengthBetween(5, 20))); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.BaseAggregationTestCase; import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder; public class FilterTests extends BaseAggregationTestCase<FilterAggregationBuilder> { @Override protected FilterAggregationBuilder createTestAggregatorBuilder() { FilterAggregationBuilder factory = new FilterAggregationBuilder(randomAlphaOfLengthBetween(1, 20), QueryBuilders.termQuery(randomAlphaOfLengthBetween(5, 20), randomAlphaOfLengthBetween(5, 20))); // NORELEASE make RandomQueryBuilder work outside of the // AbstractQueryTestCase // builder.query(RandomQueryBuilder.createQuery(getRandom())); return factory; } }
Use imports for services in module information
/* * 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. */ import org.tinylog.core.Hook; import org.tinylog.core.formats.DateFormatBuilder; import org.tinylog.core.formats.JavaTimeFormatBuilder; import org.tinylog.core.formats.NumberFormatBuilder; import org.tinylog.core.formats.ValueFormatBuilder; import org.tinylog.core.providers.LoggingProviderBuilder; import org.tinylog.core.providers.NopLoggingProviderBuilder; module org.tinylog.core { uses Hook; uses ValueFormatBuilder; provides ValueFormatBuilder with DateFormatBuilder, JavaTimeFormatBuilder, NumberFormatBuilder; uses LoggingProviderBuilder; provides LoggingProviderBuilder with NopLoggingProviderBuilder; exports org.tinylog.core; exports org.tinylog.core.formats; exports org.tinylog.core.formatters; exports org.tinylog.core.providers; exports org.tinylog.runtime; }
/* * 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. */ module org.tinylog.core { uses org.tinylog.core.formats.ValueFormatBuilder; provides org.tinylog.core.formats.ValueFormatBuilder with org.tinylog.core.formats.DateFormatBuilder, org.tinylog.core.formats.JavaTimeFormatBuilder, org.tinylog.core.formats.NumberFormatBuilder; uses org.tinylog.core.providers.LoggingProviderBuilder; provides org.tinylog.core.providers.LoggingProviderBuilder with org.tinylog.core.providers.NopLoggingProviderBuilder; uses org.tinylog.core.Hook; exports org.tinylog.core; exports org.tinylog.core.formats; exports org.tinylog.core.formatters; exports org.tinylog.core.providers; exports org.tinylog.runtime; }
Tweak olfactory input stimulus to produce more interesting output.
#!/usr/bin/env python """ Generate sample olfactory model stimulus. """ import numpy as np import h5py osn_num = 1375 dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data points in time t = np.arange(0, dt*Nt, dt) I = 10.0 # amplitude of odorant concentration u_on = I*np.ones(Ot, dtype=np.float64) u_off = np.zeros(Ot, dtype=np.float64) u_reset = np.zeros(Rt, dtype=np.float64) u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on)) u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u)) with h5py.File('olfactory_input.h5', 'w') as f: f.create_dataset('real', (Nt, osn_num), dtype=np.float64, data=u_all)
#!/usr/bin/env python """ Generate sample olfactory model stimulus. """ import numpy as np import h5py osn_num = 1375 dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data points in time t = np.arange(0, dt*Nt, dt) I = -1.*0.0195 # amplitude of odorant concentration u_on = I*np.ones(Ot, dtype=np.float64) u_off = np.zeros(Ot, dtype=np.float64) u_reset = np.zeros(Rt, dtype=np.float64) u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on)) u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u)) with h5py.File('olfactory_input.h5', 'w') as f: f.create_dataset('real', (Nt, osn_num), dtype=np.float64, data=u_all)
Update to work with the latest iteration
from __future__ import print_function, division, absolute_import import argparse from argparse import RawDescriptionHelpFormatter import sys from conda.cli import common description = """ Handles interacting with Conda environments. """ example = """ examples: conda env list conda env list --json """ def configure_parser(): p = argparse.ArgumentParser() sub_parsers = p.add_subparsers() l = sub_parsers.add_parser( 'list', formatter_class=RawDescriptionHelpFormatter, description=description, help=description, epilog=example, ) common.add_parser_json(l) return p def main(): args = configure_parser().parse_args() info_dict = {'envs': []} common.handle_envs_list(info_dict['envs'], not args.json) if args.json: common.stdout_json(info_dict) if __name__ == '__main__': sys.exit(main())
from __future__ import print_function, division, absolute_import import argparse from argparse import RawDescriptionHelpFormatter import sys from conda.cli import common description = """ Handles interacting with Conda environments. """ example = """ examples: conda env list conda env list --json """ def configure_parser(): p = argparse.ArgumentParser() sub_parsers = p.add_subparsers() l = sub_parsers.add_parser( 'list', formatter_class=RawDescriptionHelpFormatter, description=description, help=description, epilog=example, ) common.add_parser_json(l) return p def main(): args = configure_parser().parse_args() info_dict = {'envs': []} common.handle_envs_list(args, info_dict['envs']) if args.json: common.stdout_json(info_dict) if __name__ == '__main__': sys.exit(main())
Add autogenerate code for angular app
var gulp = require('gulp'); gulp.task('download-deps', function (callback) { var tsd = require('gulp-tsd'); tsd({ command: 'reinstall', config: './tsd.json' }, callback); }); var compileTypescript = function(scriptname, projectdir) { var ts = require('gulp-typescript'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); var tsresult = gulp.src(projectdir + '/**/*.ts') .pipe(sourcemaps.init()) .pipe(ts({ target: 'ES5', sortOutput: true })); return tsresult.js .pipe(concat(scriptname)) .pipe(sourcemaps.write()) .pipe(gulp.dest('build')); } gulp.task('compilets-script', function () { compileTypescript("xut.js", 'script'); }); gulp.watch('script/**/*.ts', ['compilets-script']); gulp.task('compilets-angular', function () { compileTypescript("xut-angular.js", 'webapp/angular'); }); gulp.watch('webapp/angular/**/*.ts', ['compilets-script']); gulp.task('default', ['compilets-script', 'compilets-angular']);
var gulp = require('gulp'); var script_name = "xut.js"; gulp.task('download-deps', function (callback) { var tsd = require('gulp-tsd'); tsd({ command: 'reinstall', config: './tsd.json' }, callback); }); gulp.task('compilets', function () { var ts = require('gulp-typescript'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); var tsresult = gulp.src('script/**/*.ts') .pipe(sourcemaps.init()) .pipe(ts({ target: 'ES5', sortOutput: true })); return tsresult.js .pipe(concat(script_name)) .pipe(sourcemaps.write()) .pipe(gulp.dest('build')); }); gulp.watch('script/**/*.ts', ['compilets']); gulp.task('default', ['compilets']);
Use explicit relative imports for Python3 Compat
from .attribute_dict import AttributeDict from .alias_dict import AliasDict __version__ = "0.1.2" class Lexicon(AttributeDict, AliasDict): def __init__(self, *args, **kwargs): # Need to avoid combining AliasDict's initial attribute write on # self.aliases, with AttributeDict's __setattr__. Doing so results in # an infinite loop. Instead, just skip straight to dict() for both # explicitly (i.e. we override AliasDict.__init__ instead of extending # it.) # NOTE: could tickle AttributeDict.__init__ instead, in case it ever # grows one. dict.__init__(self, *args, **kwargs) dict.__setattr__(self, 'aliases', {}) def __getattr__(self, key): # Intercept deepcopy/etc driven access to self.aliases when not # actually set. (Only a problem for us, due to abovementioned combo of # Alias and Attribute Dicts, so not solvable in a parent alone.) if key == 'aliases' and key not in self.__dict__: self.__dict__[key] = {} return super(Lexicon, self).__getattr__(key)
from attribute_dict import AttributeDict from alias_dict import AliasDict __version__ = "0.1.2" class Lexicon(AttributeDict, AliasDict): def __init__(self, *args, **kwargs): # Need to avoid combining AliasDict's initial attribute write on # self.aliases, with AttributeDict's __setattr__. Doing so results in # an infinite loop. Instead, just skip straight to dict() for both # explicitly (i.e. we override AliasDict.__init__ instead of extending # it.) # NOTE: could tickle AttributeDict.__init__ instead, in case it ever # grows one. dict.__init__(self, *args, **kwargs) dict.__setattr__(self, 'aliases', {}) def __getattr__(self, key): # Intercept deepcopy/etc driven access to self.aliases when not # actually set. (Only a problem for us, due to abovementioned combo of # Alias and Attribute Dicts, so not solvable in a parent alone.) if key == 'aliases' and key not in self.__dict__: self.__dict__[key] = {} return super(Lexicon, self).__getattr__(key)
Remove unused dependencies from Webapp Fixes #3753
Package.describe({ summary: "Serves a Meteor app over HTTP", version: '1.1.7-winr.6' }); Npm.depends({connect: "2.9.0", send: "0.1.4", useragent: "2.0.7"}); Npm.strip({ multiparty: ["test/"], useragent: ["test/"] }); Package.onUse(function (api) { api.use(['logging', 'underscore', 'routepolicy', 'boilerplate-generator', 'webapp-hashing'], 'server'); api.use(['underscore'], 'client'); // At response serving time, webapp uses browser-policy if it is loaded. If // browser-policy is loaded, then it must be loaded after webapp // (browser-policy depends on webapp). So we don't explicitly depend in any // way on browser-policy here, but we use it when it is loaded, and it can be // loaded after webapp. api.export(['WebApp', 'main', 'WebAppInternals'], 'server'); api.export(['WebApp'], 'client'); api.addFiles('webapp_server.js', 'server'); api.addFiles('webapp_client.js', 'client'); }); Package.onTest(function (api) { api.use(['tinytest', 'webapp', 'http']); api.addFiles('webapp_tests.js', 'server'); });
Package.describe({ summary: "Serves a Meteor app over HTTP", version: '1.1.7-winr.6' }); Npm.depends({connect: "2.9.0", send: "0.1.4", useragent: "2.0.7"}); Npm.strip({ multiparty: ["test/"], useragent: ["test/"] }); Package.onUse(function (api) { api.use(['logging', 'underscore', 'routepolicy', 'boilerplate-generator', 'spacebars', 'htmljs', 'blaze', 'webapp-hashing'], 'server'); api.use(['underscore'], 'client'); // At response serving time, webapp uses browser-policy if it is loaded. If // browser-policy is loaded, then it must be loaded after webapp // (browser-policy depends on webapp). So we don't explicitly depend in any // way on browser-policy here, but we use it when it is loaded, and it can be // loaded after webapp. api.export(['WebApp', 'main', 'WebAppInternals'], 'server'); api.export(['WebApp'], 'client'); api.addFiles('webapp_server.js', 'server'); api.addFiles('webapp_client.js', 'client'); }); Package.onTest(function (api) { api.use(['tinytest', 'webapp', 'http']); api.addFiles('webapp_tests.js', 'server'); });
Fix table name in migration
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { $schema->table('registration_tokens', function (Blueprint $table) { $table->string('provider'); $table->string('identifier'); $table->text('user_attributes')->nullable(); $table->text('payload')->nullable()->change(); }); }, 'down' => function (Builder $schema) { $schema->table('registration_tokens', function (Blueprint $table) { $table->dropColumn('provider', 'identifier', 'user_attributes'); $table->string('payload', 150)->change(); }); } ];
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { $schema->table('registration_tokens', function (Blueprint $table) { $table->string('provider'); $table->string('identifier'); $table->text('user_attributes')->nullable(); $table->text('payload')->nullable()->change(); }); }, 'down' => function (Builder $schema) { $schema->table('auth_tokens', function (Blueprint $table) { $table->dropColumn('provider', 'identifier', 'user_attributes'); $table->string('payload', 150)->change(); }); } ];
Fix wrong state name for selected dates.
"use strict"; // @param {object} _state - live _state see README for how to use. export default function placeToEat(_state) { _state.datesSelected = _state.datesSelected || []; let select = (date) => { _state.datesSelected.push(date); }; return { select, get id() { return _state.id; }, get name() { return _state.name; }, get cuisine() { return _state.cuisine; }, get numOfTimesSelected() { return _state.datesSelected.length; } }; }
"use strict"; // @param {object} _state - live _state see README for how to use. export default function placeToEat(_state) { _state.datesChoosen = _state.datesChoosen || []; let select = (date) => { _state.datesChoosen.push(date); }; return { select, get id() { return _state.id; }, get name() { return _state.name; }, get cuisine() { return _state.cuisine; }, get numOfTimesSelected() { return _state.datesChoosen.length; } }; }
Remove limit from ember post API calls ref #3004 - this is unnecessary and causing bugs
import styleBody from 'ghost/mixins/style-body'; import AuthenticatedRoute from 'ghost/routes/authenticated'; var paginationSettings = { status: 'all', staticPages: 'all', page: 1 }; var PostsRoute = AuthenticatedRoute.extend(styleBody, { classNames: ['manage'], model: function () { // using `.filter` allows the template to auto-update when new models are pulled in from the server. // we just need to 'return true' to allow all models by default. return this.store.filter('post', paginationSettings, function () { return true; }); }, setupController: function (controller, model) { this._super(controller, model); controller.set('paginationSettings', paginationSettings); }, actions: { openEditor: function (post) { this.transitionTo('editor', post); } } }); export default PostsRoute;
import styleBody from 'ghost/mixins/style-body'; import AuthenticatedRoute from 'ghost/routes/authenticated'; var paginationSettings = { status: 'all', staticPages: 'all', page: 1, limit: 15 }; var PostsRoute = AuthenticatedRoute.extend(styleBody, { classNames: ['manage'], model: function () { // using `.filter` allows the template to auto-update when new models are pulled in from the server. // we just need to 'return true' to allow all models by default. return this.store.filter('post', paginationSettings, function () { return true; }); }, setupController: function (controller, model) { this._super(controller, model); controller.set('paginationSettings', paginationSettings); }, actions: { openEditor: function (post) { this.transitionTo('editor', post); } } }); export default PostsRoute;
Remove prod/staging ports so people don't get the idea to run this on these environments
var env = process.env.NODE_ENV || 'development'; var defaults = { "static": { port: 3003 }, "socket": { options: { origins: '*:*', log: true, heartbeats: false, authorization: false, transports: [ 'websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling' ], 'log level': 1, 'flash policy server': true, 'flash policy port': 3013, 'destroy upgrade': true, 'browser client': true, 'browser client minification': true, 'browser client etag': true, 'browser client gzip': false } }, "nohm": { url: 'localhost', port: 6379, db: 2, prefix: 'admin' }, "redis": { url: 'localhost', port: 6379, db: 2 }, "sessions": { secret: "super secret cat", db: 1 } }; module.exports = defaults;
var env = process.env.NODE_ENV || 'development'; var defaults = { "static": { port: 3003 }, "socket": { options: { origins: '*:*', log: true, heartbeats: false, authorization: false, transports: [ 'websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling' ], 'log level': 1, 'flash policy server': true, 'flash policy port': 3013, 'destroy upgrade': true, 'browser client': true, 'browser client minification': true, 'browser client etag': true, 'browser client gzip': false } }, "nohm": { url: 'localhost', port: 6379, db: 2, prefix: 'admin' }, "redis": { url: 'localhost', port: 6379, db: 2 }, "sessions": { secret: "super secret cat", db: 1 } }; if (env === 'production' || env === 'staging') { defaults["static"].port = 80; } if (env === 'staging') { defaults['static'].port = 3004; } module.exports = defaults;
[BPK-434] Add comment about BpkDataTableComment usage
/* * Backpack - Skyscanner's Design System * * Copyright 2017 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import { Column } from 'react-virtualized'; import { cssModules } from 'bpk-react-utils'; import STYLES from './bpk-data-table-column.scss'; const getClassName = cssModules(STYLES); // BpkDataTableColumn is just a props wrapper since Table only accepts Column children // BpkDataTable uses BpkDataTableColumn.toColumn to convert BpkDataTableColumn to Columns const BpkDataTableColumn = () => null; BpkDataTableColumn.toColumn = (bpkDataTableColumn, key) => { const { className, ...rest } = bpkDataTableColumn.props; const classNames = [getClassName('bpk-data-table-column')]; if (className) { classNames.push(className); } return <Column className={classNames.join(' ')} key={key} {...rest} />; }; BpkDataTableColumn.propTypes = { ...Column.propTypes }; BpkDataTableColumn.defaultProps = { ...Column.defaultProps }; export default BpkDataTableColumn;
/* * Backpack - Skyscanner's Design System * * Copyright 2017 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import { Column } from 'react-virtualized'; import { cssModules } from 'bpk-react-utils'; import STYLES from './bpk-data-table-column.scss'; const getClassName = cssModules(STYLES); const BpkDataTableColumn = () => null; BpkDataTableColumn.toColumn = (bpkDataTableColumn, key) => { const { className, ...rest } = bpkDataTableColumn.props; const classNames = [getClassName('bpk-data-table-column')]; if (className) { classNames.push(className); } return <Column className={classNames.join(' ')} key={key} {...rest} />; }; BpkDataTableColumn.propTypes = { ...Column.propTypes }; BpkDataTableColumn.defaultProps = { ...Column.defaultProps }; export default BpkDataTableColumn;
Add test for values of text columns in GeoDataFrame from file
import unittest import json import numpy as np from geopandas import GeoDataFrame class TestDataFrame(unittest.TestCase): def setUp(self): # Data from http://www.nyc.gov/html/dcp/download/bytes/nybb_13a.zip # saved as geopandas/examples/nybb_13a.zip. self.df = GeoDataFrame.from_file( '/nybb_13a/nybb.shp', vfs='zip://examples/nybb_13a.zip') def test_from_file_(self): self.assertTrue('geometry' in self.df) self.assertTrue(len(self.df) == 5) self.assertTrue(np.alltrue(self.df['BoroName'].values == np.array(['Staten Island', 'Queens', 'Brooklyn', 'Manhattan', 'Bronx']))) def test_to_json(self): text = self.df.to_json() data = json.loads(text) self.assertTrue(data['type'] == 'FeatureCollection') self.assertTrue(len(data['features']) == 5)
import unittest import json from geopandas import GeoDataFrame class TestSeries(unittest.TestCase): def setUp(self): # Data from http://www.nyc.gov/html/dcp/download/bytes/nybb_13a.zip # saved as geopandas/examples/nybb_13a.zip. self.df = GeoDataFrame.from_file( '/nybb_13a/nybb.shp', vfs='zip://examples/nybb_13a.zip') def test_from_file_(self): self.assertTrue('geometry' in self.df) self.assertTrue(len(self.df) == 5) def test_to_json(self): text = self.df.to_json() data = json.loads(text) self.assertTrue(data['type'] == 'FeatureCollection') self.assertTrue(len(data['features']) == 5)
Correct requests_oauth package name, to fix distutils installation
#!/usr/bin/env python requires = ['requests', 'requests_oauthlib'] try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nopenphoto = openphoto.main:main\n""", 'zip_safe': False, 'install_requires': requires } except ImportError: from distutils.core import setup kw = {'scripts': ['bin/openphoto'], 'requires': requires} setup(name='openphoto', version='0.3', description='Python client library for Trovebox/Openphoto', author='Pete Burgers, James Walker', url='https://github.com/openphoto/openphoto-python', packages=['openphoto'], **kw )
#!/usr/bin/env python requires = ['requests', 'requests-oauthlib'] try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nopenphoto = openphoto.main:main\n""", 'zip_safe': False, 'install_requires': requires } except ImportError: from distutils.core import setup kw = {'scripts': ['bin/openphoto'], 'requires': requires} setup(name='openphoto', version='0.3', description='Python client library for Trovebox/Openphoto', author='Pete Burgers, James Walker', url='https://github.com/openphoto/openphoto-python', packages=['openphoto'], **kw )
Write bearer token to user home dir.
// @flow /* eslint-disable no-console */ import os from 'os'; import path from 'path'; import { sshConnect, sshExec } from '../util/ssh'; import { readFile, writeFile } from '../util/fs'; import { exitError } from '../exit'; import typeof { default as Yargs } from 'yargs'; import type { BaseArgs } from './index'; const name = 'login'; const description = 'Uses your SSH key to authenticate you with the amazee.io API'; export async function setup(yargs: Yargs): Promise<Object> { return yargs.usage(`$0 ${name} - ${description}`).argv; } type Args = BaseArgs; export async function run(args: Args): Promise<number> { const { clog = console.log } = args; // TODO: We need to make the ssh path lookup smarter or request it via prompt. const homeDir = os.homedir(); const privateKeyFilePath = path.join(homeDir, '.ssh', 'id_rsa'); const privateKey = await readFile(privateKeyFilePath); const connection = await sshConnect({ host: 'localhost', port: 2020, username: 'api', privateKey, }); const output = await sshExec(connection, 'login'); const token = output.toString(); const tokenFilePath = path.join(homeDir, '.ioauth'); await writeFile(tokenFilePath, token); clog('Login successful'); // Be responsible and close the connection after our transaction. connection.end(); return 0; } export default { setup, name, description, run, };
// @flow /* eslint-disable no-console */ import os from 'os'; import path from 'path'; import { sshConnect, sshExec } from '../util/ssh'; import { readFile } from '../util/fs'; import { exitError } from '../exit'; import typeof { default as Yargs } from 'yargs'; import type { BaseArgs } from './index'; const name = 'login'; const description = 'Uses your SSH key to authenticate you with the amazee.io API'; export async function setup(yargs: Yargs): Promise<Object> { return yargs.usage(`$0 ${name} - ${description}`).argv; } type Args = BaseArgs; export async function run(args: Args): Promise<number> { const { clog = console.log } = args; const privateKey = await readFile(path.join(os.homedir(), '.ssh', 'id_rsa')); const connection = await sshConnect({ host: 'localhost', port: 2020, username: 'api', privateKey, }); const output = await sshExec(connection, 'login'); // TODO: Instead of logging the output, save it. clog(output.toString()); // Be responsible and close the connection after our transaction. connection.end(); return 0; } export default { setup, name, description, run, };
OEE-1083: Edit form for currency rates - Added configurator to hide controls 'Default currency' and 'Currency rates'
<?php namespace Oro\Bundle\CurrencyBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; class CurrencyType extends AbstractType { const CONFIG_FORM_NAME = 'oro_currency___default_currency'; /** * {@inheritdoc} */ public function getParent() { return 'currency'; } /** * {@inheritdoc} */ public function getName() { return $this->getBlockPrefix(); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'oro_currency'; } public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults(['restrict' => false]); } }
<?php namespace Oro\Bundle\CurrencyBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; class CurrencyType extends AbstractType { /** * {@inheritdoc} */ public function getParent() { return 'currency'; } /** * {@inheritdoc} */ public function getName() { return $this->getBlockPrefix(); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'oro_currency'; } public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults(['restrict' => false]); } }
Make the default selector null
from .models import Node, Info, Transmission from sqlalchemy import ForeignKey, Column, String import random class Source(Node): __tablename__ = "source" __mapper_args__ = {"polymorphic_identity": "generic_source"} uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True) def _selector(self): return None def create_information(self): """Generate new information.""" return NotImplementedError class RandomBinaryStringSource(Source): """An agent whose genome and memome are random binary strings. The source only transmits; it does not update. """ __mapper_args__ = {"polymorphic_identity": "random_binary_string_source"} @staticmethod def _data(): return "".join([str(random.randint(0, 1)) for i in range(2)])
from .models import Node, Info, Transmission from sqlalchemy import ForeignKey, Column, String import random class Source(Node): __tablename__ = "source" __mapper_args__ = {"polymorphic_identity": "generic_source"} uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True) def _selector(self): return [] def create_information(self): """Generate new information.""" return NotImplementedError class RandomBinaryStringSource(Source): """An agent whose genome and memome are random binary strings. The source only transmits; it does not update. """ __mapper_args__ = {"polymorphic_identity": "random_binary_string_source"} @staticmethod def _data(): return "".join([str(random.randint(0, 1)) for i in range(2)])
Remove doc reference to missing class.
/* ******************************************************************************* * Copyright (c) 2016 IBM Corp. and others * * 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.eclipse.microprofile.faulttolerance.spi; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Schedules executions. * * @author Jonathan Halterman * @see Schedulers */ public interface Scheduler { /** * Schedules the {@code callable} to be called after the {@code delay} for the {@code unit}. */ ScheduledFuture<?> schedule(Callable<?> callable, long delay, TimeUnit unit); }
/* ******************************************************************************* * Copyright (c) 2016 IBM Corp. and others * * 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.eclipse.microprofile.faulttolerance.spi; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Schedules executions. * * @author Jonathan Halterman * @see Schedulers * @see net.jodah.failsafe.util.concurrent.DefaultScheduledFuture */ public interface Scheduler { /** * Schedules the {@code callable} to be called after the {@code delay} for the {@code unit}. */ ScheduledFuture<?> schedule(Callable<?> callable, long delay, TimeUnit unit); }
Convert to lowercase before checking nofollow
<?php namespace PiradoIV\Munchitos; class Link { protected $node; public function __construct($node) { $this->node = $node; } public function href() { return $this->node->attr('href'); } public function title() { return $this->node->attr('title'); } public function target() { return $this->node->attr('target'); } public function isNoFollow() { return strtolower($this->node->attr('rel')) == 'nofollow'; } public function isFollow() { return !$this->isNoFollow(); } public function isFollowed() { return $this->isFollow(); } }
<?php namespace PiradoIV\Munchitos; class Link { protected $node; public function __construct($node) { $this->node = $node; } public function href() { return $this->node->attr('href'); } public function title() { return $this->node->attr('title'); } public function target() { return $this->node->attr('target'); } public function isNoFollow() { return $this->node->attr('rel') == 'nofollow'; } public function isFollow() { return !$this->isNoFollow(); } public function isFollowed() { return $this->isFollow(); } }
Fix minimum django version spec
from setuptools import setup setup( name="django-minio-storage-py-pa", license="MIT", use_scm_version=True, description="Django file storage using the minio python client", author="Tom Houlé", author_email="tom@kafunsho.be", url="https://github.com/py-pa/django-minio-storage", packages=['minio_storage'], setup_requires=['setuptools_scm'], install_requires=[ "django>=1.8", "minio>=2.2.2", ], extras_require={ "test": [ "coverage", "requests", ], }, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Framework :: Django", ], )
from setuptools import setup setup( name="django-minio-storage-py-pa", license="MIT", use_scm_version=True, description="Django file storage using the minio python client", author="Tom Houlé", author_email="tom@kafunsho.be", url="https://github.com/py-pa/django-minio-storage", packages=['minio_storage'], setup_requires=['setuptools_scm'], install_requires=[ "django>=1.9", "minio>=2.2.2", ], extras_require={ "test": [ "coverage", "requests", ], }, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Framework :: Django", ], )
Add a negative similarity crutch
#!/usr/bin/env python from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE, SIG_DFL) import argparse import sys from gensim.models.word2vec import Word2Vec import csv parser = argparse.ArgumentParser() parser.add_argument('--sim', nargs='?', type=float, default=.3) parser.add_argument('w2v') args = vars(parser.parse_args()) w2v = Word2Vec.load_word2vec_format(args['w2v'], binary=True, unicode_errors='ignore') w2v.init_sims(replace=True) print('Using %d word2vec dimensions from "%s".' % (w2v.layer1_size, sys.argv[1]), file=sys.stderr) reader = csv.reader(sys.stdin, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: word1, word2 = row[0], row[1] try: similarity = w2v.similarity(word1, word2) if similarity < 0: similarity = args['sim'] except KeyError: similarity = args['sim'] print('%s\t%s\t%f' % (word1, word2, similarity))
#!/usr/bin/env python from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE, SIG_DFL) import argparse import sys from gensim.models.word2vec import Word2Vec import csv parser = argparse.ArgumentParser() parser.add_argument('--sim', nargs='?', type=float, default=.3) parser.add_argument('w2v') args = vars(parser.parse_args()) w2v = Word2Vec.load_word2vec_format(args['w2v'], binary=True, unicode_errors='ignore') w2v.init_sims(replace=True) print('Using %d word2vec dimensions from "%s".' % (w2v.layer1_size, sys.argv[1]), file=sys.stderr) reader = csv.reader(sys.stdin, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: word1, word2 = row[0], row[1] try: similarity = w2v.similarity(word1, word2) except KeyError: similarity = args['sim'] print('%s\t%s\t%f' % (word1, word2, similarity))
Adjust tests to run migrate when necessary
# -*- encoding: utf-8 -*- import django from django.test import TestCase from django.core.management import call_command if django.VERSION >= (1, 7): from django.test import override_settings from django.apps import apps migrate_command = 'migrate' initial_data_fixture = 'initial_data_modern' clear_app_cache = apps.clear_cache else: from django.test.utils import override_settings from django.db.models import loading migrate_command = 'syncdb' initial_data_fixture = 'initial_data_legacy' def clear_app_cache(): loading.cache.loaded = False @override_settings(INSTALLED_APPS=[ 'datatableview', 'datatableview.tests.test_app', 'datatableview.tests.example_project.example_project.example_app', ]) class DatatableViewTestCase(TestCase): def _pre_setup(self): """ Asks the management script to re-sync the database. Having test-only models is a pain. """ clear_app_cache() call_command(migrate_command, interactive=False, verbosity=0) call_command('loaddata', initial_data_fixture, interactive=False, verbosity=0) super(DatatableViewTestCase, self)._pre_setup()
# -*- encoding: utf-8 -*- import django from django.test import TestCase from django.core.management import call_command if django.VERSION >= (1, 7): from django.test import override_settings from django.apps import apps initial_data_fixture = 'initial_data_modern' clear_app_cache = apps.clear_cache else: from django.test.utils import override_settings from django.db.models import loading initial_data_fixture = 'initial_data_legacy' def clear_app_cache(): loading.cache.loaded = False @override_settings(INSTALLED_APPS=[ 'datatableview', 'datatableview.tests.test_app', 'datatableview.tests.example_project.example_project.example_app', ]) class DatatableViewTestCase(TestCase): def _pre_setup(self): """ Asks the management script to re-sync the database. Having test-only models is a pain. """ clear_app_cache() call_command('syncdb', interactive=False, verbosity=0) call_command('loaddata', initial_data_fixture, interactive=False, verbosity=0) super(DatatableViewTestCase, self)._pre_setup()
Fix a potential error in the TwitterCacheManager. This looks like it would fail at some point. Python magic is keeping it going I guess. Referencing the manager instance from the manager class seems bad though.
from django.core.cache import cache from django.db import models from django.db.utils import DatabaseError from picklefield import PickledObjectField from django_extensions.db.fields import ModificationDateTimeField class TwitterCacheManager(models.Manager): def get_tweets_for(self, account): cache_key = 'tweets-for-' + str(account) tweets = cache.get(cache_key) if tweets is None: try: tweets = self.get(account=account).tweets except (TwitterCache.DoesNotExist, DatabaseError): # TODO: see if we should catch other errors tweets = [] cache.set(cache_key, tweets, 60 * 60 * 6) # 6 hours, same as cron return tweets class TwitterCache(models.Model): account = models.CharField(max_length=100, db_index=True, unique=True) tweets = PickledObjectField(default=list) updated = ModificationDateTimeField() objects = TwitterCacheManager() def __unicode__(self): return u'Tweets from @' + self.account
from django.core.cache import cache from django.db import models from django.db.utils import DatabaseError from picklefield import PickledObjectField from django_extensions.db.fields import ModificationDateTimeField class TwitterCacheManager(models.Manager): def get_tweets_for(self, account): cache_key = 'tweets-for-' + str(account) tweets = cache.get(cache_key) if tweets is None: try: tweets = TwitterCache.objects.get(account=account).tweets except (TwitterCache.DoesNotExist, DatabaseError): # TODO: see if we should catch other errors tweets = [] cache.set(cache_key, tweets, 60 * 60 * 6) # 6 hours, same as cron return tweets class TwitterCache(models.Model): account = models.CharField(max_length=100, db_index=True, unique=True) tweets = PickledObjectField(default=list) updated = ModificationDateTimeField() objects = TwitterCacheManager() def __unicode__(self): return u'Tweets from @' + self.account
Update up to changes in es5-ext package
'use strict'; var defineProperty = Object.defineProperty , toArray = require('es5-ext/array/to-array') , remove = require('es5-ext/array/#/remove') , d = require('d/d') , value = require('es5-ext/object/valid-value') , emit = require('./core').methods.emit , id = '- ee -' , pipeTag = '\u0001pipes'; module.exports = function (emitter1, emitter2) { var pipes, pipe; (value(emitter1) && value(emitter2)); if (!emitter1.emit) { throw new TypeError(emitter1 + ' is not emitter'); } pipe = { close: function () { remove.call(pipes, emitter2); } }; if (!emitter1.hasOwnProperty(id)) { defineProperty(emitter1, id, d({})); } if (emitter1[id][pipeTag]) { (pipes = emitter1[id][pipeTag]).push(emitter2); return pipe; } pipes = emitter1[id][pipeTag] = [emitter2]; defineProperty(emitter1, 'emit', d(function () { var i, emitter, data = toArray(pipes); emit.apply(this, arguments); for (i = 0; (emitter = data[i]); ++i) { emit.apply(emitter, arguments); } })); return pipe; };
'use strict'; var defineProperty = Object.defineProperty , copy = require('es5-ext/array/#/copy') , remove = require('es5-ext/array/#/remove') , d = require('d/d') , value = require('es5-ext/object/valid-value') , emit = require('./core').methods.emit , id = '- ee -' , pipeTag = '\u0001pipes'; module.exports = function (emitter1, emitter2) { var pipes, pipe; (value(emitter1) && value(emitter2)); if (!emitter1.emit) { throw new TypeError(emitter1 + ' is not emitter'); } pipe = { close: function () { remove.call(pipes, emitter2); } }; if (!emitter1.hasOwnProperty(id)) { defineProperty(emitter1, id, d({})); } if (emitter1[id][pipeTag]) { (pipes = emitter1[id][pipeTag]).push(emitter2); return pipe; } (pipes = emitter1[id][pipeTag] = [emitter2]).copy = copy; defineProperty(emitter1, 'emit', d(function () { var i, emitter, data = pipes.copy(); emit.apply(this, arguments); for (i = 0; (emitter = data[i]); ++i) { emit.apply(emitter, arguments); } })); return pipe; };
Revert 193850 "Remove references to new-run-webkit-tests" Tries to execute the perl script "run-webkit-tests" using "cmd" which is python. > Remove references to new-run-webkit-tests > > We are going to rename it to run-webkit-tests soon. > > BUG= > > Review URL: https://chromiumcodereview.appspot.com/13980005 TBR=jchaffraix@chromium.org Review URL: https://codereview.chromium.org/14222003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@193860 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/env python # Copyright (c) 2010 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. """Wrapper around third_party/WebKit/Tools/Scripts/new-run-webkit-tests""" import os import subprocess import sys def main(): cmd = [sys.executable] src_dir = os.path.abspath(os.path.join(sys.path[0], '..', '..', '..')) script_dir=os.path.join(src_dir, "third_party", "WebKit", "Tools", "Scripts") script = os.path.join(script_dir, 'new-run-webkit-tests') cmd.append(script) if '--chromium' not in sys.argv: cmd.append('--chromium') cmd.extend(sys.argv[1:]) return subprocess.call(cmd) if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python # Copyright (c) 2010 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. """Wrapper around third_party/WebKit/Tools/Scripts/run-webkit-tests""" import os import subprocess import sys def main(): cmd = [sys.executable] src_dir = os.path.abspath(os.path.join(sys.path[0], '..', '..', '..')) script_dir=os.path.join(src_dir, "third_party", "WebKit", "Tools", "Scripts") script = os.path.join(script_dir, 'run-webkit-tests') cmd.append(script) if '--chromium' not in sys.argv: cmd.append('--chromium') cmd.extend(sys.argv[1:]) return subprocess.call(cmd) if __name__ == '__main__': sys.exit(main())
Create alias for binding in IoC container
<?php namespace KeyCDN; use Illuminate\Support\ServiceProvider; use KeyCDN\Facades\KeyCDNFacade; /** * Class KeyCDNServiceProvider * @package KeyCDN */ class KeyCDNServiceProvider extends ServiceProvider { /** * Register config files */ public function boot() { $this->publishes([ __DIR__.'/../config/keycdn.php' => config_path('keycdn.php'), ], 'keycdn'); } /** * Register Service */ public function register() { $this->mergeConfigFrom( __DIR__.'/../config/keycdn.php', 'keycdn' ); $this->app->bind(KeyCDN::class, function() { return KeyCDN::create(config('keycdn.key')); }); $this->app->alias(KeyCDN::class, 'keycdn'); } /** * Get the services provided by the provider. * @return array */ public function provides() { return array('keycdn'); } }
<?php namespace KeyCDN; use Illuminate\Support\ServiceProvider; use KeyCDN\Facades\KeyCDNFacade; /** * Class KeyCDNServiceProvider * @package KeyCDN */ class KeyCDNServiceProvider extends ServiceProvider { /** * Register config files */ public function boot() { $this->publishes([ __DIR__.'/../config/keycdn.php' => config_path('keycdn.php'), ], 'keycdn'); } /** * Register Service */ public function register() { $this->mergeConfigFrom( __DIR__.'/../config/keycdn.php', 'keycdn' ); $this->app->bind(KeyCDN::class, function() { return KeyCDN::create(config('keycdn.key')); }); } /** * Get the services provided by the provider. * @return array */ public function provides() { return array('keycdn'); } }
Update PyPi package information to reflect rebranding.
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Surveys", author_email="surveys-api@googlegroups.com", keywords="google surveys api client", url="https://developers.google.com/surveys", license="Apache License 2.0", description=("Client API for Google Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Consumer Surveys", author_email="gcs-api-trusted-testers@googlegroups.com", keywords="google consumer surveys api client", url="https://github.com/google/consumer-surveys", license="Apache License 2.0", description=("Client API for Google Consumer Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
Add bold and italic helpers
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def bold(string, *args, **kw): """ Return string as a :class:`Paragraph` in bold """ return Paragraph(u'<b>{}</b>'.format(string), *args, **kw) def italic(string, *args, **kw): """ Return string as a :class:`Paragraph` in italic """ return Paragraph(u'<i>{}</i>'.format(string), *args, **kw) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height)
Remove minify plugin to test search.
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'http://dicasdejava.com.br' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTPUT_DIRECTORY = True # Plugins PLUGIN_PATHS = ['./pelican-plugins'] PLUGINS = ['sitemap'] SITEMAP = { 'format': 'xml', 'exclude': ['autor/', 'tag/', 'categoria/', 'arquivo/'], 'priorities': { 'articles': 0.5, 'indexes': 0.5, 'pages': 0.5 }, 'changefreqs': { 'articles': 'monthly', 'indexes': 'daily', 'pages': 'monthly' } } # Following items are often useful when publishing DISQUS_SITENAME = "dicas-de-java" GOOGLE_ANALYTICS = "UA-39997045-4"
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'http://dicasdejava.com.br' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTPUT_DIRECTORY = True # Plugins PLUGIN_PATHS = ['./pelican-plugins'] PLUGINS = ['sitemap', 'minify'] SITEMAP = { 'format': 'xml', 'exclude': ['autor/', 'tag/', 'categoria/', 'arquivo/'], 'priorities': { 'articles': 0.5, 'indexes': 0.5, 'pages': 0.5 }, 'changefreqs': { 'articles': 'monthly', 'indexes': 'daily', 'pages': 'monthly' } } # Following items are often useful when publishing DISQUS_SITENAME = "dicas-de-java" GOOGLE_ANALYTICS = "UA-39997045-4"
Revert "Add queries.rate to the 'autoscaling' consumer."
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin.monitoring; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; /** * Metrics used for autoscaling * * @author bratseth */ public class AutoscalingMetrics { public static final MetricSet autoscalingMetricSet = create(); private static MetricSet create() { return new MetricSet("autoscaling", metrics("cpu.util", "mem.util", "disk.util", "application_generation", "in_service")); } private static Set<Metric> metrics(String ... metrics) { return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet()); } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin.monitoring; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; /** * Metrics used for autoscaling * * @author bratseth */ public class AutoscalingMetrics { public static final MetricSet autoscalingMetricSet = create(); private static MetricSet create() { return new MetricSet("autoscaling", metrics("cpu.util", "mem.util", "disk.util", "application_generation", "in_service", "queries.rate")); } private static Set<Metric> metrics(String ... metrics) { return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet()); } }
Revert "refactor: add progress reporter back in for karma tests" This reverts commit c69ef2d06d27aa453bad35d55e7f30fa24cbafe1.
module.exports = function (config) { config.set({ basePath: './', frameworks: ['jasmine'], browsers: ['Chrome', 'Firefox', 'PhantomJS'], files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'dist/ng-restful-collection.js', 'tests/**/*.js' ], captureTimeout: 60000, colors: true, logLevel: config.LOG_INFO, port: 9876, plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-phantomjs-launcher', 'karma-coverage' ], runnerPort: 9100, singleRun: true, autoWatch: false, coverageReporter: { type: 'lcov', dir: 'coverage/' }, preprocessors: { 'dist/ng-restful-collection.js': ['coverage'] }, reporters: ['coverage'] }); };
module.exports = function (config) { config.set({ basePath: './', frameworks: ['jasmine'], browsers: ['Chrome', 'Firefox', 'PhantomJS'], files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'dist/ng-restful-collection.js', 'tests/**/*.js' ], captureTimeout: 60000, colors: true, logLevel: config.LOG_INFO, port: 9876, plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-phantomjs-launcher', 'karma-coverage' ], runnerPort: 9100, singleRun: true, autoWatch: false, coverageReporter: { type: 'lcov', dir: 'coverage/' }, preprocessors: { 'dist/ng-restful-collection.js': ['coverage'] }, reporters: ['progress', 'coverage'] }); };
Throw an error if a field equality validator is attached to a field which is not a field set.
<?php class FieldEqualityValidator extends Validator { protected $first = null; protected $second = null; public function __construct($first, $second, $messages = array()) { Helpers::whenNot(is_string($first), "The first field name must be a string."); Helpers::whenNot(is_string($second), "The second field name must be a string."); $this->first = $first; $this->second = $second; parent::__construct($messages); } protected function perform($field) { Helpers::whenNot($field instanceof FieldSet, "Field equality validators can only be attached to field sets."); $first = $field->getChild($this->first); $second = $field->getChild($this->second); Helpers::when(is_null($first), "The first field name provided to the validator does not correspond to an existing field."); Helpers::when(is_null($second), "The second field name provided to the validator does not correspond to an existing field."); Helpers::when($first instanceof FieldSet, "The first field name provided to the validator corresponds to a field set which cannot be validated for equality."); Helpers::when($second instanceof FieldSet, "The second field name provided to the validator corresponds to a field set which cannot be validated for equality."); if($first->getValue() != $second->getValue()) { $second->addError($this->getMessage("invalid")); } } } ?>
<?php class FieldEqualityValidator extends Validator { protected $first = null; protected $second = null; public function __construct($first, $second, $messages = array()) { Helpers::whenNot(is_string($first), "The first field name must be a string."); Helpers::whenNot(is_string($second), "The second field name must be a string."); $this->first = $first; $this->second = $second; parent::__construct($messages); } protected function perform($field) { $first = $field->getChild($this->first); $second = $field->getChild($this->second); Helpers::when(is_null($first), "The first field name provided to the validator does not correspond to an existing field."); Helpers::when(is_null($second), "The second field name provided to the validator does not correspond to an existing field."); Helpers::when($first instanceof FieldSet, "The first field name provided to the validator corresponds to a field set which cannot be validated for equality."); Helpers::when($second instanceof FieldSet, "The second field name provided to the validator corresponds to a field set which cannot be validated for equality."); if($first->getValue() != $second->getValue()) { $second->addError($this->getMessage("invalid")); } } } ?>
Add loader js file for web client
// SwellRT bootstrap script // A fake SwellRT object to register on ready handlers // before the GWT module is loaded window.swellrt = { _readyHandlers: [], onReady: function(handler) { if (!handler || typeof handler !== "function") return; this._readyHandlers.push(handler); } } var scripts = document.getElementsByTagName('script'); var thisScript = scripts[scripts.length -1]; if (thisScript) { var p = document.createElement('a'); p.href = thisScript.src; // Polyfill for ES6 proxy/reflect if (!window.Proxy || !window.Reflect) { var reflectSrc = p.protocol + "//" +p.host + "/reflect.js"; document.write("<script src='"+reflectSrc+"'></script>"); } var scriptSrc = p.protocol + "//" +p.host + "/swellrt_beta/swellrt_beta.nocache.js"; document.write("<script src='"+scriptSrc+"'></script>"); }
// SwellRT bootstrap script // A fake SwellRT object to register on ready handlers // before the GWT module is loaded window.SwellRT = { _readyHandlers: [], ready: function(handler) { if (!handler || typeof handler !== "function") return; this._readyHandlers.push(handler); } } var scripts = document.getElementsByTagName('script'); var thisScript = scripts[scripts.length -1]; if (thisScript) { var p = document.createElement('a'); p.href = thisScript.src; // Polyfill for ES6 proxy/reflect if (!window.Proxy || !window.Reflect) { var reflectSrc = p.protocol + "//" +p.host + "/reflect.js"; document.write("<script src='"+reflectSrc+"'></script>"); } var scriptSrc = p.protocol + "//" +p.host + "/webapi/webapi.nocache.js"; document.write("<script src='"+scriptSrc+"'></script>"); }
core: Fix default network status on attach Network status is being saved to DB & later on updated, so need to save some default value and NonOperational is a reasonable choice. Change-Id: I17ea1594fe54203ce5d98fedd77dade64537f57c Signed-off-by: Mike Kolesnik <c6947eedc1b0e500810c3b3db45e5f4633b0ea7d@redhat.com>
package org.ovirt.engine.core.common.action; import org.ovirt.engine.core.common.businessentities.Network; import org.ovirt.engine.core.common.businessentities.NetworkStatus; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.network_cluster; public class AttachNetworkToVdsGroupParameter extends NetworkClusterParameters { private static final long serialVersionUID = -2874549285727269806L; private Network _network; public AttachNetworkToVdsGroupParameter(VDSGroup group, Network net) { super(new network_cluster(group.getId(), net.getId(), NetworkStatus.NonOperational, // Cluster attachment data can sometimes be missing, so use defaults in that case. net.getCluster() == null ? false : net.getCluster().getis_display(), net.getCluster() == null ? true : net.getCluster().isRequired())); _network = net; } public Network getNetwork() { return _network; } public AttachNetworkToVdsGroupParameter() { } }
package org.ovirt.engine.core.common.action; import org.ovirt.engine.core.common.businessentities.Network; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.network_cluster; public class AttachNetworkToVdsGroupParameter extends NetworkClusterParameters { private static final long serialVersionUID = -2874549285727269806L; private Network _network; public AttachNetworkToVdsGroupParameter(VDSGroup group, Network net) { super(new network_cluster(group.getId(), net.getId(), null, // Cluster attachment data can sometimes be missing, so use defaults in that case. net.getCluster() == null ? false : net.getCluster().getis_display(), net.getCluster() == null ? true : net.getCluster().isRequired())); _network = net; } public Network getNetwork() { return _network; } public AttachNetworkToVdsGroupParameter() { } }
Add documentation, refactor to use config
# -*- coding: utf-8 -*- """ File to collect all unigrams and all name-unigrams (label PER) from a corpus file. The corpus file must have one document/article per line. The words must be labeled in the form word/LABEL. Example file content: Yestarday John/PER Doe/PER said something amazing. Washington/LOC D.C./LOC is the capital of the U.S. The foobird is a special species of birds. It's commonly found on mars. ... Execute via: python -m preprocessing/collect_unigrams """ from __future__ import absolute_import, division, print_function, unicode_literals import os from model.unigrams import Unigrams from config import * def main(): """Main function.""" # collect all unigrams (all labels, including "O") print("Collecting unigrams...") ug_all = Unigrams() ug_all.fill_from_articles(ARTICLES_FILEPATH, verbose=True) ug_all.write_to_file(UNIGRAMS_FILEPATH) ug_all = None # collect only unigrams of label PER print("Collecting person names (label=PER)...") ug_names = Unigrams() ug_names.fill_from_articles_labels(ARTICLES_FILEPATH, ["PER"], verbose=True) ug_names.write_to_file(UNIGRAMS_PERSON_FILEPATH) print("Finished.") if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Execute via: python -m preprocessing/collect_unigrams """ from __future__ import absolute_import, division, print_function, unicode_literals import os from model.unigrams import Unigrams CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) ARTICLES_FILEPATH = "/media/aj/grab/nlp/corpus/processed/wikipedia-ner/annotated-fulltext.txt" WRITE_UNIGRAMS_FILEPATH = os.path.join(CURRENT_DIR, "unigrams.txt") WRITE_UNIGRAMS_PERSON_FILEPATH = os.path.join(CURRENT_DIR, "unigrams_per.txt") def main(): print("Collecting unigrams...") ug_all = Unigrams() ug_all.fill_from_articles(ARTICLES_FILEPATH, verbose=True) ug_all.write_to_file(WRITE_UNIGRAMS_FILEPATH) ug_all = None print("Collecting person names (label=PER)...") ug_names = Unigrams() ug_names.fill_from_articles_labels(ARTICLES_FILEPATH, ["PER"], verbose=True) ug_names.write_to_file(WRITE_UNIGRAMS_PERSON_FILEPATH) print("Finished.") if __name__ == "__main__": main()
Fix camelCasing the method name. RELNOTES: None PiperOrigin-RevId: 310508754
// Copyright 2020 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.profiler; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link SingleStatRecorder}. */ @RunWith(JUnit4.class) public class SingleStatRecorderTest { @Test public void meanAndStandardDeviation() { SingleStatRecorder recorder = new SingleStatRecorder(null, 2); recorder.addStat(43, null); recorder.addStat(49, null); recorder.addStat(51, null); recorder.addStat(57, null); MetricData metrics = recorder.snapshot(); assertThat(metrics.getAvg()).isWithin(.01).of(50); assertThat(metrics.getStdDev()).isWithin(.01).of(5); } }
// Copyright 2020 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.profiler; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link SingleStatRecorder}. */ @RunWith(JUnit4.class) public class SingleStatRecorderTest { @Test public void meanAndstandardDeviation() { SingleStatRecorder recorder = new SingleStatRecorder(null, 2); recorder.addStat(43, null); recorder.addStat(49, null); recorder.addStat(51, null); recorder.addStat(57, null); MetricData metrics = recorder.snapshot(); assertThat(metrics.getAvg()).isWithin(.01).of(50); assertThat(metrics.getStdDev()).isWithin(.01).of(5); } }
Add a docs build target
import setuptools NAME = "gidgethub" tests_require = ['pytest>=3.0.0'] setuptools.setup( name=NAME, version="0.1.0.dev1", description="A sans-I/O GitHub API library", url="https://github.com/brettcannon/gidgethub", author="Brett Cannon", author_email="brett@python.org", license="Apache", classifiers=[ 'Intended Audience :: Developers', "License :: OSI Approved :: Apache Software License", "Development Status :: 2 - Pre-Alpha", 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.6', ], keywords="github sans-io", packages=setuptools.find_packages(), zip_safe=True, python_requires=">=3.6.0", setup_requires=['pytest-runner>=2.11.0'], tests_require=tests_require, install_requires=['uritemplate>=3.0.0'], extras_require={ "docs": ["sphinx"], "test": tests_require }, )
import setuptools NAME = "gidgethub" tests_require = ['pytest>=3.0.0'] setuptools.setup( name=NAME, version="0.1.0.dev1", description="A sans-I/O GitHub API library", url="https://github.com/brettcannon/gidgethub", author="Brett Cannon", author_email="brett@python.org", license="Apache", classifiers=[ 'Intended Audience :: Developers', "License :: OSI Approved :: Apache Software License", "Development Status :: 2 - Pre-Alpha", 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.6', ], keywords="github sans-io", packages=setuptools.find_packages(), zip_safe=True, python_requires=">=3.6.0", setup_requires=['pytest-runner>=2.11.0'], tests_require=tests_require, install_requires=['uritemplate>=3.0.0'], extras_require={ "test": tests_require }, )
Remove no longer valid todo
package fitnesse.components; import static org.junit.Assert.*; import org.junit.Test; public class PluginsClassLoaderTest { @Test public void whenPluginsDirectoryDoesNotExist() throws Exception { new PluginsClassLoader().getClassLoader("nonExistingRootDirectory"); assertTrue("didn't cause exception", true); } @Test public void addPluginsToClassLoader() throws Exception { String[] dynamicClasses = new String[]{"fitnesse.testing.PluginX", "fitnesse.testing.PluginY"}; ClassLoader cl = PluginsClassLoader.getClassLoader("."); assertLoadingClassWorksNow(cl, dynamicClasses); } private void assertLoadingClassWorksNow(ClassLoader cl, String... dynamicClasses) { for (String dynamicClass : dynamicClasses) { try { Class<?> dynamicallyLoadedClass = Class.forName(dynamicClass, true, cl); assertEquals(dynamicClass, dynamicallyLoadedClass.getName()); } catch (ClassNotFoundException e) { fail("Class not found: " + e.getMessage()); } } } }
package fitnesse.components; import static org.junit.Assert.*; import org.junit.Test; public class PluginsClassLoaderTest { @Test public void whenPluginsDirectoryDoesNotExist() throws Exception { new PluginsClassLoader().getClassLoader("nonExistingRootDirectory"); assertTrue("didn't cause exception", true); } @Test public void addPluginsToClassLoader() throws Exception { String[] dynamicClasses = new String[]{"fitnesse.testing.PluginX", "fitnesse.testing.PluginY"}; //todo This fails because some other test probably loads plugin path assertLoadingClassCausesException(dynamicClasses); ClassLoader cl = PluginsClassLoader.getClassLoader("."); assertLoadingClassWorksNow(cl, dynamicClasses); } private void assertLoadingClassWorksNow(ClassLoader cl, String... dynamicClasses) { for (String dynamicClass : dynamicClasses) { try { Class<?> dynamicallyLoadedClass = Class.forName(dynamicClass, true, cl); assertEquals(dynamicClass, dynamicallyLoadedClass.getName()); } catch (ClassNotFoundException e) { fail("Class not found: " + e.getMessage()); } } } }
Add PREFIX to api url
angular.module('reted.services', []) .factory('API', function($resource) { var PREFIX = (document.location.hostname === 'localhost') ? '' : 'http://ted2srt.org'; return $resource('/api/', null, { getTalks: { url: PREFIX + '/api/talks', method: 'GET', isArray: true }, getTalk: { url: PREFIX + '/api/talks/:slug', method: 'GET', params: { slug: '@slug' } }, getTalkTranscript: { url: PREFIX + '/api/talks/:id/transcripts/txt?lang=en', method: 'GET', params: { id: '@id' }, transformResponse: function(data, headersGetter, status) { return {text: data}; } } }) }) .factory('Talks', function(API) { var talks = []; var all = function() { return talks; }; var loadMore = function() { var params = {} if (talks.length) { params.tid = talks.slice(-1)[0].id; } return API.getTalks(params, function (data) { talks = talks.concat(data); }).$promise; } return { loadMore: loadMore, all: all } });
angular.module('reted.services', []) .factory('API', function($resource) { return $resource('/api/', null, { getTalks: { url: '/api/talks', method: 'GET', isArray: true }, getTalk: { url: '/api/talks/:slug', method: 'GET', params: { slug: '@slug' } }, getTalkTranscript: { url: '/api/talks/:id/transcripts/txt?lang=en', method: 'GET', params: { id: '@id' }, transformResponse: function(data, headersGetter, status) { return {text: data}; } } }) }) .factory('Talks', function(API) { var talks = []; var all = function() { return talks; }; var loadMore = function() { var params = {} if (talks.length) { params.tid = talks.slice(-1)[0].id; } return API.getTalks(params, function (data) { talks = talks.concat(data); }).$promise; } return { loadMore: loadMore, all: all } });
Fix Transform tool CMD modifier on OSX
(function () { var ns = $.namespace('pskl.tools.transform'); ns.AbstractTransformTool = function () {}; pskl.utils.inherit(ns.AbstractTransformTool, pskl.tools.Tool); ns.AbstractTransformTool.prototype.applyTransformation = function (evt) { var allFrames = evt.shiftKey; var allLayers = pskl.utils.UserAgent.isMac ? evt.metaKey : evt.ctrlKey; this.applyTool_(evt.altKey, allFrames, allLayers); $.publish(Events.PISKEL_RESET); this.raiseSaveStateEvent({ altKey : evt.altKey, allFrames : allFrames, allLayers : allLayers }); }; ns.AbstractTransformTool.prototype.applyTool_ = function (altKey, allFrames, allLayers) { var currentFrameIndex = pskl.app.piskelController.getCurrentFrameIndex(); var layers = allLayers ? pskl.app.piskelController.getLayers() : [pskl.app.piskelController.getCurrentLayer()]; layers.forEach(function (layer) { var frames = allFrames ? layer.getFrames() : [layer.getFrameAt(currentFrameIndex)]; frames.forEach(function (frame) { this.applyToolOnFrame_(frame, altKey); }.bind(this)); }.bind(this)); }; ns.AbstractTransformTool.prototype.replay = function (frame, replayData) { this.applyTool_(replayData.altKey, replayData.allFrames, replayData.allLayers); }; })();
(function () { var ns = $.namespace('pskl.tools.transform'); ns.AbstractTransformTool = function () {}; pskl.utils.inherit(ns.AbstractTransformTool, pskl.tools.Tool); ns.AbstractTransformTool.prototype.applyTransformation = function (evt) { var allFrames = evt.shiftKey; var allLayers = evt.ctrlKey; this.applyTool_(evt.altKey, allFrames, allLayers); $.publish(Events.PISKEL_RESET); this.raiseSaveStateEvent({ altKey : evt.altKey, allFrames : allFrames, allLayers : allLayers }); }; ns.AbstractTransformTool.prototype.applyTool_ = function (altKey, allFrames, allLayers) { var currentFrameIndex = pskl.app.piskelController.getCurrentFrameIndex(); var layers = allLayers ? pskl.app.piskelController.getLayers() : [pskl.app.piskelController.getCurrentLayer()]; layers.forEach(function (layer) { var frames = allFrames ? layer.getFrames() : [layer.getFrameAt(currentFrameIndex)]; frames.forEach(function (frame) { this.applyToolOnFrame_(frame, altKey); }.bind(this)); }.bind(this)); }; ns.AbstractTransformTool.prototype.replay = function (frame, replayData) { this.applyTool_(replayData.altKey, replayData.allFrames, replayData.allLayers); }; })();
Send 401 Unauthorized for all requests (Except Telegram webhooks)
var config = require('./config'); var http = require('http'); var bot = require('./modules/bot.js'); var tg = require('./modules/telegramAPI'); tg.setupWebhook(); http.createServer(function (req, res) { var body = ''; req.on('data', function(chunk) { body += chunk; }); req.on('end', function() { if (req.url === config.BOT_WEBHOOK_PATH) { res.writeHead(200); try { body = JSON.parse(body); } catch (e) { console.log(`Bad JSON: ${e.message}`); return; }; bot.verifyMessage(body); } else { res.writeHead(401); } res.end(); }); }).listen(config.SERVER_PORT);
var config = require('./config'); var http = require('http'); var bot = require('./modules/bot.js'); var tg = require('./modules/telegramAPI'); tg.setupWebhook(); http.createServer(function (req, res) { var body = ''; req.on('data', function(chunk) { body += chunk; }); req.on('end', function() { if (req.url === config.BOT_WEBHOOK_PATH) { res.writeHead(200); try { body = JSON.parse(body); } catch (e) { console.log(`Bad JSON: ${e.message}`); return; }; bot.verifyMessage(body); } else { res.writeHead(400); } res.end(); }); }).listen(config.SERVER_PORT);
Add TODO comment about defineMessages()
/* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ import {__addLocaleData as addIMFLocaleData} from 'intl-messageformat'; import {__addLocaleData as addIRFLocaleData} from 'intl-relativeformat'; import defaultLocaleData from './en'; export {default as IntlProvider} from './components/intl'; export {default as FormattedGroup} from './components/group'; export {default as FormattedDate} from './components/date'; export {default as FormattedTime} from './components/time'; export {default as FormattedRelative} from './components/relative'; export {default as FormattedNumber} from './components/number'; export {default as FormattedPlural} from './components/plural'; export {default as FormattedMessage} from './components/message'; export {default as FormattedHTMLMessage} from './components/html-message'; export {intlShape} from './types'; // TODO Should there be a `defineMessages()` function that takes a collection? export function defineMessage(messageDescriptor) { // TODO: Type check in dev? Return something different? return messageDescriptor; } export function addLocaleData(data = []) { let locales = Array.isArray(data) ? data : [data]; locales.forEach((localeData) => { addIMFLocaleData(localeData); addIRFLocaleData(localeData); }); } addLocaleData(defaultLocaleData);
/* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ import {__addLocaleData as addIMFLocaleData} from 'intl-messageformat'; import {__addLocaleData as addIRFLocaleData} from 'intl-relativeformat'; import defaultLocaleData from './en'; export {default as IntlProvider} from './components/intl'; export {default as FormattedGroup} from './components/group'; export {default as FormattedDate} from './components/date'; export {default as FormattedTime} from './components/time'; export {default as FormattedRelative} from './components/relative'; export {default as FormattedNumber} from './components/number'; export {default as FormattedPlural} from './components/plural'; export {default as FormattedMessage} from './components/message'; export {default as FormattedHTMLMessage} from './components/html-message'; export {intlShape} from './types'; export function defineMessage(messageDescriptor) { // TODO: Type check in dev? Return something different? return messageDescriptor; } export function addLocaleData(data = []) { let locales = Array.isArray(data) ? data : [data]; locales.forEach((localeData) => { addIMFLocaleData(localeData); addIRFLocaleData(localeData); }); } addLocaleData(defaultLocaleData);
Refactor transforms from object to array.
import { parser } from './parser'; import { compile } from './compiler'; import { entity } from './transform/entity'; import { whitespace } from './optimize/whitespace'; import { getTemplateName } from './utils'; import { drawGraph } from './graph'; export class Compiler { constructor(options = {}) { this.options = Object.assign({ asModule: true }, options); this.transforms = [whitespace, entity]; this.globals = ['window', 'Math']; } compile(filename, code) { let ast = parser.parse(filename, code); // Transform. this.transforms.forEach(transform => transform(ast)); return compile(getTemplateName(getBaseName(filename)), ast, this.options, this.globals); } drawAstTree(filename, code) { let ast = parser.parse(filename, code); // Transform. this.transforms.forEach(transform => transform(ast)); return drawGraph(ast); } } function getBaseName(name) { return name.split('/').pop().replace(/\.\w+$/, ''); }
import { parser } from './parser'; import { compile } from './compiler'; import { entity } from './transform/entity'; import { whitespace } from './optimize/whitespace'; import { getTemplateName } from './utils'; import { drawGraph } from './graph'; export class Compiler { constructor(options = {}) { this.options = Object.assign({ asModule: true }, options); this.transforms = {whitespace, entity}; this.globals = ['window', 'Math']; } compile(filename, code) { let ast = parser.parse(filename, code); // Transform. Object.keys(this.transforms).forEach((key) => this.transforms[key](ast)); return compile(getTemplateName(getBaseName(filename)), ast, this.options, this.globals); } drawAstTree(filename, code) { let ast = parser.parse(filename, code); // Transform. Object.keys(this.transforms).forEach((key) => this.transforms[key](ast)); return drawGraph(ast); } } function getBaseName(name) { return name.split('/').pop().replace(/\.\w+$/, ''); }
Fix the ASAN build by xfailing test_decimal when ASAN_OPTIONS is set. Adding decimal columns crashes an ASAN built impalad. This change skips the test. Change-Id: Ic94055a3f0d00f89354177de18bc27d2f4cecec2 Reviewed-on: http://gerrit.ent.cloudera.com:8080/2532 Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com> Tested-by: jenkins Reviewed-on: http://gerrit.ent.cloudera.com:8080/2594
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted tests for decimal type. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestDecimalQueries(ImpalaTestSuite): BATCH_SIZES = [0, 1] @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestDecimalQueries, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES)) # On CDH4, hive does not support decimal so we can't run these tests against # the other file formats. Enable them on C5. cls.TestMatrix.add_constraint(lambda v:\ (v.get_value('table_format').file_format == 'text' and v.get_value('table_format').compression_codec == 'none') or v.get_value('table_format').file_format == 'parquet') def test_queries(self, vector): if os.environ.get('ASAN_OPTIONS') == 'handle_segv=0': pytest.xfail(reason="IMPALA-959: Sum on a decimal column fails ASAN") new_vector = copy(vector) new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size') self.run_test_case('QueryTest/decimal', new_vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted tests for decimal type. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestDecimalQueries(ImpalaTestSuite): BATCH_SIZES = [0, 1] @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestDecimalQueries, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES)) # On CDH4, hive does not support decimal so we can't run these tests against # the other file formats. Enable them on C5. cls.TestMatrix.add_constraint(lambda v:\ (v.get_value('table_format').file_format == 'text' and v.get_value('table_format').compression_codec == 'none') or v.get_value('table_format').file_format == 'parquet') def test_queries(self, vector): new_vector = copy(vector) new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size') self.run_test_case('QueryTest/decimal', new_vector)
Add missing property type declaration
<?php namespace Jstewmc\Rtf\Element\Control\Word; /** * The "\cxs" control word indicates an "ignored" steno group. Steno is written as a * series of strokes using pure steno notation with forward-slashes between them but * no leading- or trailing-slashes. * * The valid steno characters, in order, are STKPWHRAO*EUFRPBLGTSDZ. When the number * bar is used, the digits 0-9 are valid. Finally, the hyphen (-) and number sign (#) * are allowed. * * A hyphen is used in cases where there may be confusion between initial and final * consonants. For instance, to differentiate between the strokes /RBGS and /-RBGS. * * If the number bar was used in a stroke, the stroke contains a number sign to * indicate that. The number sign may be anywhere within the stroke, but it should * probably be at one end or the other. Keep in mind, most steno programs will output * the digit when the number bar is used to create a number, but the number sign when * the number bar is used to create a stroke (e.g., "/K#"). */ class Cxs extends Word { /** * The "\cxs" is an ignored control word */ protected bool $isIgnored = true; public function __construct(?int $parameter = null) { parent::__construct('cxs', $parameter); } }
<?php namespace Jstewmc\Rtf\Element\Control\Word; /** * The "\cxs" control word indicates an "ignored" steno group. Steno is written as a * series of strokes using pure steno notation with forward-slashes between them but * no leading- or trailing-slashes. * * The valid steno characters, in order, are STKPWHRAO*EUFRPBLGTSDZ. When the number * bar is used, the digits 0-9 are valid. Finally, the hyphen (-) and number sign (#) * are allowed. * * A hyphen is used in cases where there may be confusion between initial and final * consonants. For instance, to differentiate between the strokes /RBGS and /-RBGS. * * If the number bar was used in a stroke, the stroke contains a number sign to * indicate that. The number sign may be anywhere within the stroke, but it should * probably be at one end or the other. Keep in mind, most steno programs will output * the digit when the number bar is used to create a number, but the number sign when * the number bar is used to create a stroke (e.g., "/K#"). */ class Cxs extends Word { /** * The "\cxs" is an ignored control word */ protected $isIgnored = true; public function __construct(?int $parameter = null) { parent::__construct('cxs', $parameter); } }
Remove support for Python 2
#!/usr/bin/env python from os import path from setuptools import setup with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f: long_description = f.read() setup(name='django_uncertainty', version='1.5', description='A Django middleware to generate predictable errors on sites', long_description=long_description, author='Agustin Barto', author_email='abarto@gmail.com', url='https://github.com/abarto/django_uncertainty', license='BSD', install_requires=[], tests_require=['Django>=1.10'], test_suite='uncertainty.tests.runtests.runtests', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ], packages=['uncertainty'])
#!/usr/bin/env python from os import path from setuptools import setup with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f: long_description = f.read() setup(name='django_uncertainty', version='1.5', description='A Django middleware to generate predictable errors on sites', long_description=long_description, author='Agustin Barto', author_email='abarto@gmail.com', url='https://github.com/abarto/django_uncertainty', license='BSD', install_requires=[], tests_require=['Django>=1.10'], test_suite='uncertainty.tests.runtests.runtests', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ], packages=['uncertainty'])
Move QueryApi to load before Orm
'use strict'; let Defiant = undefined; class Engine { constructor() { Defiant = require('./defiant'); // Create registries for plugins. this.registry = {}; // Initialize default Plugins. this.pluginRegistry = new Defiant.Plugin.PluginRegistry(); [ Defiant.Plugin.Settings, Defiant.Plugin.QueryApi, Defiant.Plugin.Orm, Defiant.Plugin.Http, Defiant.Plugin.Router, Defiant.Plugin.Menu, Defiant.Plugin.ThemeBase, Defiant.Plugin.ThemeBootstrap, Defiant.Plugin.Theme, Defiant.Plugin.Layout, Defiant.Plugin.Message, Defiant.Plugin.FormApi, Defiant.Plugin.Session, Defiant.Plugin.Account, Defiant.Plugin.FileApi, Defiant.Library, Defiant.Library.JQuery, Defiant.Library.JQueryUI, Defiant.Library.Materialize, ].map(plugin => this.pluginRegistry.set(plugin, this)); } defineBootstrapDirectory(directory) { this.bootstrapDirectory = directory; return this; } addPlugin(plugin) { this.pluginRegistry.set(plugin, this); return this; } async init() { for (let plugin of this.pluginRegistry.getOrderedElements()) { await plugin.init(); } } } module.exports = Engine;
'use strict'; let Defiant = undefined; class Engine { constructor() { Defiant = require('./defiant'); // Create registries for plugins. this.registry = {}; // Initialize default Plugins. this.pluginRegistry = new Defiant.Plugin.PluginRegistry(); [ Defiant.Plugin.Settings, Defiant.Plugin.Orm, Defiant.Plugin.Http, Defiant.Plugin.Router, Defiant.Plugin.Menu, Defiant.Plugin.ThemeBase, Defiant.Plugin.ThemeBootstrap, Defiant.Plugin.Theme, Defiant.Plugin.QueryApi, Defiant.Plugin.Layout, Defiant.Plugin.Message, Defiant.Plugin.FormApi, Defiant.Plugin.Session, Defiant.Plugin.Account, Defiant.Plugin.FileApi, Defiant.Library, Defiant.Library.JQuery, Defiant.Library.JQueryUI, Defiant.Library.Materialize, ].map(plugin => this.pluginRegistry.set(plugin, this)); } defineBootstrapDirectory(directory) { this.bootstrapDirectory = directory; return this; } addPlugin(plugin) { this.pluginRegistry.set(plugin, this); return this; } async init() { for (let plugin of this.pluginRegistry.getOrderedElements()) { await plugin.init(); } } } module.exports = Engine;
Use LocMemCache instead of real memcache
DATABASES = {'default':{ 'NAME':':memory:', 'ENGINE':'django.db.backends.sqlite3' }} # install the bare minimum for # testing django-brake INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'brake', ) # This is where our ratelimiting information is stored. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' } } # Might be good to also test against real memcached. #CACHE_BACKEND = 'memcached://127.0.0.1:11211/' # point to ourselves as the root urlconf, define no patterns (see below) ROOT_URLCONF = 'test_settings' # set this to turn off an annoying "you're doing it wrong" message SECRET_KEY = 'HAHAHA ratelimits!' # turn this file into a pseudo-urls.py. from django.conf.urls.defaults import * urlpatterns = patterns('',)
DATABASES = {'default':{ 'NAME':':memory:', 'ENGINE':'django.db.backends.sqlite3' }} # install the bare minimum for # testing django-brake INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'brake', ) # This is where our ratelimiting information is stored. # Unfortunately, the DummyCache doesn't work for our purposes. CACHE_BACKEND = 'memcached://127.0.0.1:11211/' # point to ourselves as the root urlconf, define no patterns (see below) ROOT_URLCONF = 'test_settings' # set this to turn off an annoying "you're doing it wrong" message SECRET_KEY = 'HAHAHA ratelimits!' # turn this file into a pseudo-urls.py. from django.conf.urls.defaults import * urlpatterns = patterns('',)
Add missing function in __all__.
# Copyright 2012 Kevin Goodsell # # This software is licensed under the Eclipse Public License (EPL) V1.0. ''' Interface to the STAF API. ''' # Using __all__ makes pydoc work properly. Otherwise it looks at the modules the # items actually come from and assumes they don't belong in the docs for # __init__. __all__ = [ 'Handle', 'wrap_data', 'add_privacy_delimiters', 'remove_privacy_delimiters', 'mask_private_data', 'escape_privacy_delimiters', 'errors', 'strerror', 'STAFError', 'STAFResultError', 'unmarshal', 'unmarshal_force', 'STAFUnmarshalError', 'MapClassDefinition', 'MapClass', 'unmarshal_recursive', 'unmarshal_non_recursive', 'unmarshal_none', ] from ._staf import ( Handle, wrap_data, add_privacy_delimiters, remove_privacy_delimiters, mask_private_data, escape_privacy_delimiters, ) from ._errors import ( errors, strerror, STAFError, STAFResultError, ) from ._marshal import ( unmarshal, unmarshal_force, STAFUnmarshalError, MapClassDefinition, MapClass, unmarshal_recursive, unmarshal_non_recursive, unmarshal_none, )
# Copyright 2012 Kevin Goodsell # # This software is licensed under the Eclipse Public License (EPL) V1.0. ''' Interface to the STAF API. ''' # Using __all__ makes pydoc work properly. Otherwise it looks at the modules the # items actually come from and assumes they don't belong in the docs for # __init__. __all__ = [ 'Handle', 'wrap_data', 'add_privacy_delimiters', 'remove_privacy_delimiters', 'mask_private_data', 'escape_privacy_delimiters', 'errors', 'strerror', 'STAFError', 'STAFResultError', 'unmarshal', 'STAFUnmarshalError', 'MapClassDefinition', 'MapClass', 'unmarshal_recursive', 'unmarshal_non_recursive', 'unmarshal_none', ] from ._staf import ( Handle, wrap_data, add_privacy_delimiters, remove_privacy_delimiters, mask_private_data, escape_privacy_delimiters, ) from ._errors import ( errors, strerror, STAFError, STAFResultError, ) from ._marshal import ( unmarshal, unmarshal_force, STAFUnmarshalError, MapClassDefinition, MapClass, unmarshal_recursive, unmarshal_non_recursive, unmarshal_none, )
Remove deprecated fa- prefix from LM icons
import Ember from 'ember'; import layout from '../templates/components/lm-type-icon'; const { computed } = Ember; export default Ember.Component.extend({ layout, listItem: false, type: null, mimetype: null, tagName: 'span', classNames: ['lm-type-icon'], icon: computed('type', 'mimetype', function() { let type = this.get('type'); let mimetype = this.get('mimetype') || ''; if(type === 'link'){ return 'link'; } else if(type === 'citation'){ return 'paragraph'; } else { if(mimetype.search(/pdf/) !== -1){ return 'file-pdf-o'; } if(mimetype.search(/ppt|keynote|pps|pptx|powerpoint/) !== -1){ return 'file-powerpoint-o'; } if(mimetype.search(/mp4|mpg|mpeg|mov/) !== -1){ return 'file-movie-o'; } if(mimetype.search(/wav|mp3|aac|flac/) !== -1){ return 'file-audio-o'; } } return 'file'; }) });
import Ember from 'ember'; import layout from '../templates/components/lm-type-icon'; const { computed } = Ember; export default Ember.Component.extend({ layout, listItem: false, type: null, mimetype: null, tagName: 'span', classNames: ['lm-type-icon'], icon: computed('type', 'mimetype', function() { let type = this.get('type'); let mimetype = this.get('mimetype') || ''; if(type === 'link'){ return 'fa-link'; } else if(type === 'citation'){ return 'fa-paragraph'; } else { if(mimetype.search(/pdf/) !== -1){ return 'fa-file-pdf-o'; } if(mimetype.search(/ppt|keynote|pps|pptx|powerpoint/) !== -1){ return 'fa-file-powerpoint-o'; } if(mimetype.search(/mp4|mpg|mpeg|mov/) !== -1){ return 'fa-file-movie-o'; } if(mimetype.search(/wav|mp3|aac|flac/) !== -1){ return 'fa-file-audio-o'; } } return 'fa-file'; }) });
Fix typo causing unnecessary requests
var express = require('express'); var router = express.Router(); var Watchlist = require('../models/watchlist'); // POST watchlist router.post('/', function (req, res, next) { var user = req.user; var post = req.body; if (post.status == 'attend' || post.status == 'watch' ) { Watchlist.add(user, post, function (err, result) { if (err) throw err; if (!req.xhr) { res.redirect('/event/' + post.event_id); } }); } else if (!post.status) { Watchlist.remove(user, post, function (err, result) { if (err) throw err; if (!req.xhr) { res.redirect('/event/' + post.event_id); } }); } }); // Get watchlist item status for event/user router.get('/status/:event_id', function(req, res, next) { var user = req.user; Watchlist.get(user, req.params.event_id, function (err, result) { if (err) throw err; res.send(result); }); }); // GET watchlists by event router.get('/list/:event_id', function(req, res, next) { Watchlist.getAllByEvent(req.params.event_id, function (err, watchlists) { if (err) throw err; }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var Watchlist = require('../models/watchlist'); // POST watchlist router.post('/', function (req, res, next) { var user = req.user; var post = req.body; if (post.status == 'attend' || post.status == 'watch' ) { Watchlist.add(user, post, function (err, result) { if (err) throw err; if (!res.xhr) { res.redirect('/event/' + post.event_id); } }); } else if (!post.status) { Watchlist.remove(user, post, function (err, result) { if (err) throw err; if (!res.xhr) { res.redirect('/event/' + post.event_id); } }); } }); // Get watchlist item status for event/user router.get('/status/:event_id', function(req, res, next) { var user = req.user; Watchlist.get(user, req.params.event_id, function (err, result) { if (err) throw err; res.send(result); }); }); // GET watchlists by event router.get('/list/:event_id', function(req, res, next) { Watchlist.getAllByEvent(req.params.event_id, function (err, watchlists) { if (err) throw err; }); }); module.exports = router;
Set override planting to true by default
package com.agricraft.agricore.plant; import java.util.List; public class AgriSeed extends AgriObject { protected final boolean overridePlanting; public AgriSeed() { this("minecraft:wheat_seeds"); } public AgriSeed(String seed) { this(seed, false); } public AgriSeed(String seed, boolean useTags) { this(seed, useTags, ""); } public AgriSeed(String seed, boolean useTags, String data, String... ignoredData) { super("item", seed, useTags, data, ignoredData); this.overridePlanting = true; } public AgriSeed(String seed, boolean useTags, String data, List<String> ignoredData) { super("item", seed, useTags, data, ignoredData); this.overridePlanting = true; } public boolean isOverridePlanting() { return this.overridePlanting; } }
package com.agricraft.agricore.plant; import java.util.List; public class AgriSeed extends AgriObject { protected final boolean overridePlanting; public AgriSeed() { this("minecraft:wheat_seeds"); } public AgriSeed(String seed) { this(seed, false); } public AgriSeed(String seed, boolean useTags) { this(seed, useTags, ""); } public AgriSeed(String seed, boolean useTags, String data, String... ignoredData) { super("item", seed, useTags, data, ignoredData); this.overridePlanting = false; } public AgriSeed(String seed, boolean useTags, String data, List<String> ignoredData) { super("item", seed, useTags, data, ignoredData); this.overridePlanting = false; } public boolean isOverridePlanting() { return this.overridePlanting; } }
Fix task validation to recognize `@CompileClasspath`
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.project.taskfactory; import org.gradle.api.Task; import org.gradle.internal.Cast; import java.util.Map; /** * Class for easy access to task property validation from the validator task. */ public class TaskPropertyValidationAccess { @SuppressWarnings("unused") public static void collectTaskValidationProblems(Class<?> task, Map<String, Boolean> problems) { TaskClassInfoStore infoStore = new DefaultTaskClassInfoStore(new DefaultTaskClassValidatorExtractor(new ClasspathPropertyAnnotationHandler(), new CompileClasspathPropertyAnnotationHandler())); TaskClassInfo info = infoStore.getTaskClassInfo(Cast.<Class<? extends Task>>uncheckedCast(task)); for (String nonAnnotatedPropertyName : info.getNonAnnotatedPropertyNames()) { problems.put(String.format("Task type '%s' declares property that is not annotated: '%s'.", task.getName(), nonAnnotatedPropertyName), Boolean.FALSE); } } }
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.project.taskfactory; import org.gradle.api.Task; import org.gradle.internal.Cast; import java.util.Map; /** * Class for easy access to task property validation from the validator task. */ public class TaskPropertyValidationAccess { @SuppressWarnings("unused") public static void collectTaskValidationProblems(Class<?> task, Map<String, Boolean> problems) { TaskClassInfoStore infoStore = new DefaultTaskClassInfoStore(new DefaultTaskClassValidatorExtractor(new ClasspathPropertyAnnotationHandler())); TaskClassInfo info = infoStore.getTaskClassInfo(Cast.<Class<? extends Task>>uncheckedCast(task)); for (String nonAnnotatedPropertyName : info.getNonAnnotatedPropertyNames()) { problems.put(String.format("Task type '%s' declares property that is not annotated: '%s'.", task.getName(), nonAnnotatedPropertyName), Boolean.FALSE); } } }
[new] Add function updateElastic, deleteElastic Добавлен каркас функция для обновления и удаления записей всего индекса ElasticSearch
<?php namespace app\commands; use app\models\Language; use budyaga\users\models\User; use yii\console\Controller; use yii\db\Expression; class ArticleController extends Controller { public function actionSeed($count = 1) { for ($i=0; $i<$count; $i++) { $faker =\Faker\Factory::create(); $article = new \app\models\Article; $article->title_original=$faker->text(80); $article->title_translate=$faker->text(80); $article->user_id='2'; $article->lang_original_id='2'; $article->lang_translate_id='1'; $article->save(); var_export($article->errors); } echo (" created"." ".$count." "."articles "); } /** * Функция обновления всего индекса в ElasticSearch * */ public function updateElastic() { } /** * Функция удаления всего индекса в ElasticSearch * */ public function deleteElastic() { } }
<?php namespace app\commands; use app\models\Language; use budyaga\users\models\User; use yii\console\Controller; use yii\db\Expression; class ArticleController extends Controller { public function actionSeed($count = 1) { for ($i=0; $i<$count; $i++) { $faker =\Faker\Factory::create(); $article = new \app\models\Article; $article->title_original=$faker->text(80); $article->title_translate=$faker->text(80); $article->user_id='2'; $article->lang_original_id='2'; $article->lang_translate_id='1'; $article->save(); var_export($article->errors); } echo (" created"." ".$count." "."articles "); } }
Use more meaningful function names
const videoClip = { video: '', initWidth: 0, initHeight: 0, width: 0, height: 0, start: 0; end: 0; duration: function () { return this.end - this.start; }; mirror: false, scale: 1.0, fps: 0.0, speed: 1.0, ratio: 0.0, // initWidth / initHeight. setWidth: function (w) { // Set width to w and keep aspect ratio unchanged. this.width = w; this.height = this.width / this.ratio; return this; }, setHeight: function (h) { // Set Height to h and keep aspect ratio unchanged. this.height = h; this.weight = this.height * this.ratio; return this; }, setScale: function (s) { this.scale = s; this.width = this.initWidth * this.scale; this.height = this.initHeight * this.scale; return this; } }; module.exports = videoClip;
const videoClip = { video: '', initWidth: 0, initHeight: 0, width: 0, height: 0, start: 0; end: 0; duration: function () { return this.end - this.start; }; mirror: false, scale: 1.0, fps: 0.0, speed: 1.0, ratio: 0.0, // initWidth / initHeight. updateWidth: function (h) { this.width = this.ratio * h; return this; }, updateHeight: function (w) { this.height = w / this.ratio; return this; }, updateWidthAndHeight: function (s) { this.width = this.initWidth * s; this.height = this.initHeight * s; return this; } }; module.exports = videoClip;
Add tests about the server.
import Server from './server'; import { MockSocket } from './com/mocks'; describe('Server', function() { beforeEach(function() { this.server = new Server(); }); describe('connection of new client', function() { beforeEach(function() { this.client = new MockSocket(); this.server.connect(this.client); this.message = this.client.lastMessage('init'); }); it('welcomes the player', function() { expect(this.message.message).toEqual('welcome'); }); it('gives the player\'s name', function() { expect(this.message.name).toMatch(/^Player [0-9]+$/); }); it('gives the player\'s id', function() { expect(this.message.id).toMatch(/^[0-9]+$/); }); it('adds the client to its players list', function() { expect(this.server.players).toHaveKey(this.client); }); }); describe('disconnection of a client', function() { beforeEach(function() { this.client = new MockSocket(); this.server.connect(this.client); this.server.disconnect(this.client); }); it('removes client from the list', function() { expect(this.server.players).not.toHaveKey(this.client); }); }); });
import Server from './server'; import { MockSocket } from './com/mocks'; describe('Server', function() { beforeEach(function() { this.server = new Server(); }); describe('connection of new client', function() { beforeEach(function() { this.client = new MockSocket(); this.server.connect(this.client); this.message = this.client.lastMessage('init'); }); it('welcomes the player', function() { expect(this.message.message).toEqual('welcome'); }); it('gives the player\'s name', function() { expect(this.message.name).toMatch(/^Player [0-9]+$/); }); it('gives the player\'s id', function() { expect(this.message.id).toMatch(/^[0-9]+$/); }); it('adds the client to its players list', function() { expect(this.server.players).toHaveKey(this.client); }); }); });
Use pointer to not copy service.
package cruncher import ( "github.com/davecgh/go-spew/spew" "pilosa/core" "pilosa/dispatch" "pilosa/index" "pilosa/transport" ) type Cruncher struct { *core.Service close_chan chan bool api *index.FragmentContainer } func (cruncher *Cruncher) Run(port int) { spew.Dump("Cruncher.Run") spew.Dump(port) cruncher.api = index.NewFragmentContainer() /* bh = api.Get(frag,tileid) api.SetBit(frag,bh,1) api.Count(frag,bh) api.Union(frag,[bh1,bh2]) api.Intersect(frag,[bh1,bh2]) */ cruncher.Service.Run() } func NewCruncher() *Cruncher { service := core.NewService() fragment_container := index.NewFragmentContainer() cruncher := Cruncher{service, make(chan bool), fragment_container} cruncher.Transport = transport.NewTcpTransport(service) cruncher.Dispatch = dispatch.NewCruncherDispatch(service) return &cruncher }
package cruncher import ( "github.com/davecgh/go-spew/spew" "pilosa/core" "pilosa/dispatch" "pilosa/index" "pilosa/transport" ) type Cruncher struct { core.Service close_chan chan bool api *index.FragmentContainer } func (cruncher *Cruncher) Run(port int) { spew.Dump("Cruncher.Run") spew.Dump(port) cruncher.api = index.NewFragmentContainer() /* bh = api.Get(frag,tileid) api.SetBit(frag,bh,1) api.Count(frag,bh) api.Union(frag,[bh1,bh2]) api.Intersect(frag,[bh1,bh2]) */ cruncher.Service.Run() } func NewCruncher() *Cruncher { service := core.NewService() fragment_container := index.NewFragmentContainer() cruncher := Cruncher{*service, make(chan bool), fragment_container} cruncher.Transport = transport.NewTcpTransport(service) cruncher.Dispatch = dispatch.NewCruncherDispatch(service) return &cruncher }
Remove page title management from store
'use strict'; var createStore = require('fluxible/addons').createStore, ApplicationStore; function isEqualRoute(currentRoute, route) { if (currentRoute && route) { return currentRoute.path === route.path } return false; } ApplicationStore = createStore({ storeName: 'ApplicationStore', handlers: { CHANGE_ROUTE: 'handleNavigate' }, initialize: function () { this.currentRoute = null; }, handleNavigate: function (route) { if (!isEqualRoute(this.currentRoute, route) || !this.currentRoute) { this.currentRoute = route; this.emitChange(); } }, getState: function () { return { route: this.currentRoute }; }, dehydrate: function () { return this.getState(); }, rehydrate: function (state) { this.currentRoute = state.route; } }); module.exports = ApplicationStore;
'use strict'; var createStore = require('fluxible/addons').createStore, ApplicationStore; ApplicationStore = createStore({ storeName: 'ApplicationStore', handlers: { UPDATE_PAGE_TITLE: 'updatePageTitle' }, initialize: function () { this.pageTitle = ''; }, updatePageTitle: function (title) { this.pageTitle = title.pageTitle; this.emitChange(); }, getPageTitle: function () { return this.pageTitle; }, getState: function () { return { pageTitle: this.pageTitle }; }, dehydrate: function () { return this.getState(); }, rehydrate: function (state) { this.pageTitle = state.pageTitle; } }); module.exports = ApplicationStore;
Make SFC test a python call to main() Instead of python -> bash -> python, call the SFC test using the execute() method that is inherited from FeatureBase and it's a bash call by default. With this change, we call the SFC test using main() of run_tests.py of SFC repo and will have real time output. Change-Id: I6d59821e603c88697a82b95c5626c5b703c11026 Signed-off-by: jose.lausuch <a4ed9890ad7f6494ac84a749f29a4dc3449a1186@ericsson.com> Signed-off-by: George Paraskevopoulos <97fa9f4b61869a8ee92863df90135c882f7b3aa0@intracom-telecom.com>
#!/usr/bin/python # # Copyright (c) 2016 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # import functest.core.feature_base as base from sfc.tests.functest import run_tests class OpenDaylightSFC(base.FeatureBase): def __init__(self): super(OpenDaylightSFC, self).__init__(project='sfc', case='functest-odl-sfc', repo='dir_repo_sfc') def execute(self): return run_tests.main()
#!/usr/bin/python # # Copyright (c) 2016 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # import functest.core.feature_base as base class OpenDaylightSFC(base.FeatureBase): def __init__(self): super(OpenDaylightSFC, self).__init__(project='sfc', case='functest-odl-sfc', repo='dir_repo_sfc') dir_sfc_functest = '{}/sfc/tests/functest'.format(self.repo) self.cmd = 'cd %s && python ./run_tests.py' % dir_sfc_functest
Fix linking to engine's application route
import Ember from 'ember'; import { attributeMungingMethod } from './link-to-utils'; const { LinkComponent, getOwner, get, set } = Ember; export default LinkComponent.extend({ [attributeMungingMethod]() { this._super(...arguments); let owner = getOwner(this); if (owner.mountPoint) { // Prepend engine mount point to targetRouteName this._prefixProperty(owner.mountPoint, 'targetRouteName'); // Prepend engine mount point to current-when if set if (get(this, 'current-when') !== null) { this._prefixProperty(owner.mountPoint, 'current-when'); } } }, _prefixProperty(prefix, prop) { let propValue = get(this, prop); let namespacedPropValue; if (propValue === 'application') { namespacedPropValue = prefix; } else { namespacedPropValue = prefix + '.' + propValue; } set(this, prop, namespacedPropValue); } });
import Ember from 'ember'; import { attributeMungingMethod } from './link-to-utils'; const { LinkComponent, getOwner, get, set } = Ember; export default LinkComponent.extend({ [attributeMungingMethod]() { this._super(...arguments); let owner = getOwner(this); if (owner.mountPoint) { // Prepend engine mount point to targetRouteName let fullRouteName = owner.mountPoint + '.' + get(this, 'targetRouteName'); set(this, 'targetRouteName', fullRouteName); // Prepend engine mount point to current-when if set let currentWhen = get(this, 'current-when'); if (currentWhen !== null) { let fullCurrentWhen = owner.mountPoint + '.' + currentWhen; set(this, 'current-when', fullCurrentWhen); } } } });
Use once binding to avoid endless 2-way disconnects
var io = require('socket.io').listen(parseInt(process.env.PORT)), twitter = require('ntwitter') io.set("origins", process.env.ALLOWED_ORIGINS) io.set("log level", 2) io.sockets.on("connection", function(socket) { var tweetStream; socket.on("userstream", function(data) { var twitterClient = new twitter({ consumer_key: process.env.CONSUMER_KEY, consumer_secret: process.env.CONSUMER_SECRET, access_token_key: data.token, access_token_secret: data.secret }); twitterClient.stream('user', {}, function(_tweetStream) { tweetStream = _tweetStream tweetStream.on('data', function(tweet) { socket.emit('tweet', tweet) }) // if twitter or network failure happens, just // kill the and let the client manage retries tweetStream.once("end", function() { socket.disconnect() }) tweetStream.once("destroy", function() { socket.disconnect() }) tweetStream.once("error", function() { socket.disconnect() }) }) }) socket.once("disconnect", function() { if (tweetStream) { tweetStream.destroy() } }) })
var io = require('socket.io').listen(parseInt(process.env.PORT)), twitter = require('ntwitter') io.set("origins", process.env.ALLOWED_ORIGINS) io.set("log level", 2) io.sockets.on("connection", function(socket) { var tweetStream; socket.on("userstream", function(data) { var twitterClient = new twitter({ consumer_key: process.env.CONSUMER_KEY, consumer_secret: process.env.CONSUMER_SECRET, access_token_key: data.token, access_token_secret: data.secret }); twitterClient.stream('user', {}, function(_tweetStream) { tweetStream = _tweetStream tweetStream.on('data', function(tweet) { socket.emit('tweet', tweet) }) // if twitter or network failure happens, just // kill the and let the client manage retries tweetStream.on("end", function() { socket.disconnect() }) tweetStream.on("destroy", function() { socket.disconnect() }) tweetStream.on("error", function() { socket.disconnect() }) }) }) socket.on("disconnect", function() { if (tweetStream) { tweetStream.destroy() } }) })
Add configurable numberOfDepartments to RandomUsersRetriever getUsers
/* eslint-disable no-magic-numbers */ export default class RandomUsersRetriever { getUsers(numberOfUsers, numberOfDepartments = 1) { const users = []; // Add nodes to random parents for (let i = 0; i < numberOfUsers; i++) { const user = this.getAppUser( i, i === 0 ? null : this._getRandomIntInclusive(0, i), `Department ${this._getRandomIntInclusive(1, numberOfDepartments)}`); users.push(user); } return Promise.resolve(users); } getAppUser(i, managerId, department) { const user = { id: i, displayName: '{{ displayName }}', jobTitle: '{{ job_title }}', department: department, userPrincipalName: `${i}@example.com`, city: 'New York', state: 'NY', country: 'USA', email: `${i}@example.com`, telephoneNumber: '555-555-1212', manager: managerId ? this.getAppUser(managerId) : null }; this.counter++; return user; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random _getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } }
export default class RandomUsersRetriever { getUsers(numberOfUsers) { const users = []; // Add nodes to random parents for (let i = 0; i < numberOfUsers; i++) { const user = this.getAppUser( i, i === 0 ? null : this._getRandomIntInclusive(0, i)); // eslint-disable-line no-magic-numbers users.push(user); } return Promise.resolve(users); } getAppUser(i, managerId) { const user = { id: i, displayName: '{{ displayName }}', jobTitle: '{{ job_title }}', department: '{{ department }}', userPrincipalName: `${i}@example.com`, city: 'New York', state: 'NY', country: 'USA', email: `${i}@example.com`, telephoneNumber: '555-555-1212', manager: managerId ? this.getAppUser(managerId) : null }; this.counter++; return user; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random _getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; // eslint-disable-line no-magic-numbers } }
Sort languages by country name Instead of sorting languages by country code, sort by country name.
import Ember from 'ember'; import countries from './countries'; export default Ember.Component.extend({ i18n: Ember.inject.service(), countries: countries, languages: Ember.computed('countries', function() { var langs = []; this.get('countries').forEach((country) => { country.languages.forEach((lang) => { langs.push({ countryCode: country.code, countryName: country.name, name: lang.name, code: lang.code }); }); }); langs.sort(function(a, b) { if (a.countryName > b.countryName) { return 1; } if (a.countryName < b.countryName) { return -1; } return 0; }); return langs; }), onPick: null, country: null, actions: { pickLanguage(language, code) { this.get('onPick')(language, code); this.set('i18n.locale', code); } } });
import Ember from 'ember'; import countries from './countries'; export default Ember.Component.extend({ i18n: Ember.inject.service(), countries: countries, languages: Ember.computed('countries', function() { var langs = []; this.get('countries').forEach((country) => { country.languages.forEach((lang) => { langs.push({ countryCode: country.code, name: lang.name, code: lang.code }); }); }); langs.sort(function(a, b) { if (a.countryCode > b.countryCode) { return 1; } if (a.countryCode < b.countryCode) { return -1; } return 0; }); return langs; }), onPick: null, country: null, actions: { pickLanguage(language, code) { this.get('onPick')(language, code); this.set('i18n.locale', code); } } });
Add auto_reload to twig templates
<?php use LastCall\Mannequin\Core\MannequinConfig; use LastCall\Mannequin\Html\HtmlExtension; use LastCall\Mannequin\Twig\TwigExtension; use Symfony\Component\Finder\Finder; $htmlFinder = Finder::create() ->files() ->name('*.html') ->in(__DIR__.'/demo/static'); $twigFinder = Finder::create() ->files() ->name('*.twig') ->in(__DIR__.'/demo/templates'); $assetFinder = Finder::create() ->files() ->in(__DIR__.'/demo/css'); $twig = new TwigExtension([ 'finder' => $twigFinder, 'twig_root' => __DIR__.'/demo/templates', 'twig_options' => [ 'auto_reload' => TRUE ] ]); $html = new HtmlExtension([ 'finder' => $htmlFinder, ]); $config = MannequinConfig::create([ 'ui' => new \LastCall\Mannequin\Core\Ui\LocalUi(__DIR__.'/ui'), ]) ->setGlobalJs(['https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/js/foundation.min.js']) ->setGlobalCss(['demo/css/style.css']) ->setAssets($assetFinder) ->addExtension($html) ->addExtension($twig); return $config;
<?php use LastCall\Mannequin\Core\MannequinConfig; use LastCall\Mannequin\Html\HtmlExtension; use LastCall\Mannequin\Twig\TwigExtension; use Symfony\Component\Finder\Finder; $htmlFinder = Finder::create() ->files() ->name('*.html') ->in(__DIR__.'/demo/static'); $twigFinder = Finder::create() ->files() ->name('*.twig') ->in(__DIR__.'/demo/templates'); $assetFinder = Finder::create() ->files() ->in(__DIR__.'/demo/css'); $twig = new TwigExtension([ 'finder' => $twigFinder, 'twig_root' => __DIR__.'/demo/templates', ]); $html = new HtmlExtension([ 'finder' => $htmlFinder, ]); $config = MannequinConfig::create([ 'ui' => new \LastCall\Mannequin\Core\Ui\LocalUi(__DIR__.'/ui'), ]) ->setGlobalJs(['https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/js/foundation.min.js']) ->setGlobalCss(['demo/css/style.css']) ->setAssets($assetFinder) ->addExtension($html) ->addExtension($twig); return $config;
Add login_required decorator to protected sites
from django.conf.urls import url, include from django.contrib.auth import views as auth_views from . import views from django.contrib.auth.decorators import login_required urlpatterns = [ # Authentication ## Override logout next_page url(r'^accounts/logout/$', auth_views.logout, {'next_page': '/'}, name='auth_logout'), url(r'^accounts/', include('registration.backends.hmac.urls')), # Backend urls url(r'^$', views.HomeView.as_view(), name='home'), url(r'^submit$', login_required(views.SubmitView.as_view()), name='submit'), url(r'^scores$', views.ScoreboardView.as_view(), name='scores'), url(r'^chals$', login_required(views.ChallengesView.as_view()), name='chals'), url(r'^chals/hint/(?P<buy_hint>[0-9]+)/buy', login_required(views.ChallengesView.as_view()), name='buy_hint'), url(r'^stats$', views.StatisticsView.as_view(), name='stats'), ]
from django.conf.urls import url, include from django.http import HttpResponseRedirect from django.conf import settings from django.contrib.auth import views as auth_views from . import views urlpatterns = [ # Authentication ## Override logout next_page url(r'^accounts/logout/$', auth_views.logout, {'next_page': '/'}, name='auth_logout'), url(r'^accounts/', include('registration.backends.hmac.urls')), # Backend urls url(r'^$', views.HomeView.as_view(), name='home'), url(r'^submit$', views.SubmitView.as_view(), name='submit'), url(r'^scores$', views.ScoreboardView.as_view(), name='scores'), url(r'^chals$', views.ChallengesView.as_view(), name='chals'), url(r'^chals/hint/(?P<buy_hint>[0-9]+)/buy', views.ChallengesView.as_view(), name='buy_hint'), url(r'^stats$', views.StatisticsView.as_view(), name='stats'), ]