text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Complete walk of polynomial degrees to find most balance between under and overfitting
import numpy as np from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.cross_validation import cross_val_score def main(): np.random.seed(0) n_samples = 30 degrees = range(1, 16) true_fn = lambda X: np.cos(1.5 * np.pi * X) X = np.sort(np.random.rand(n_samples)) y = true_fn(X) + np.random.randn(n_samples) * 0.1 for d in degrees: poly_features = PolynomialFeatures(degree=d, include_bias=False) model = LinearRegression() pipeline = Pipeline([('polynomial_features', poly_features), ('linear_regression', model)]) pipeline.fit(X[:, np.newaxis], y) scores = cross_val_score(pipeline, X[:, np.newaxis], y, scoring='mean_squared_error', cv=10) print('Degree {:>2}: mse = {}, std = {}'.format( d, -scores.mean(), scores.std())) if __name__ == '__main__': main()
import numpy as np from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.cross_validation import cross_val_score def main(): np.random.seed(0) n_samples = 30 degrees = range(1, 16) true_fn = lambda X: np.cos(1.5 * np.pi * X) X = np.sort(np.random.rand(n_samples)) y = true_fn(X) + np.random.randn(n_samples) * 0.1 for d in degrees: poly_features = PolynomialFeatures(degree=d, include_bias=False) model = LinearRegression() pipeline = Pipeline([("polynomial_features", poly_features), ("linear_regression", model)]) pipeline.fit(X[:, np.newaxis], y) scores = cross_val_score(pipeline, X[:, np.newaxis], y, scoring="mean_squared_error", cv=10) print("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( degrees[i], -scores.mean(), scores.std())) if __name__ == '__main__': main()
Refresh quotation_series field to show series
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt $.extend(cur_frm.cscript, { onload: function() { if(cur_frm.doc.__onload && cur_frm.doc.__onload.quotation_series) { cur_frm.fields_dict.quotation_series.df.options = cur_frm.doc.__onload.quotation_series; cur_frm.refresh_field("quotation_series"); } }, refresh: function(){ toggle_mandatory(cur_frm) }, enable_checkout: function(){ toggle_mandatory(cur_frm) } }); function toggle_mandatory (cur_frm){ cur_frm.toggle_reqd("payment_gateway_account", false); if(cur_frm.doc.enabled && cur_frm.doc.enable_checkout) { cur_frm.toggle_reqd("payment_gateway_account", true); } }
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt $.extend(cur_frm.cscript, { onload: function() { if(cur_frm.doc.__onload && cur_frm.doc.__onload.quotation_series) { cur_frm.fields_dict.quotation_series.df.options = cur_frm.doc.__onload.quotation_series; } }, refresh: function(){ toggle_mandatory(cur_frm) }, enable_checkout: function(){ toggle_mandatory(cur_frm) } }); function toggle_mandatory (cur_frm){ cur_frm.toggle_reqd("payment_gateway_account", false); if(cur_frm.doc.enabled && cur_frm.doc.enable_checkout) { cur_frm.toggle_reqd("payment_gateway_account", true); } }
Add check for empty sequence or regex.
#!/bin/env python3 # Prosite regular expressions matcher # Copyright (c) 2014 Tomasz Truszkowski # All rights reserved. import prosite_matcher if __name__ == '__main__': print("\n Hi, this is Prosite Matcher! \n") sequence = input("Sequence: ") regex = input("Regular expression: ") if sequence != None and sequence != "" and regex != None and regex != "": prositeMatcher = prosite_matcher.PrositeMatcher() prositeMatcher.compile(regex) matches, ranges = prositeMatcher.get_matches(sequence) print("Found patterns: ", end="") if (len(matches) > 0): print(sequence[ 0 : ranges[0][0] ], end="") for i in range(0, len(matches)): print("\033[91m", end="") print(sequence[ ranges[i][0] : ranges[i][1] ], end="") print("\033[0m", end="") if (i < len(matches) - 1): print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="") print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)]) else: print(sequence) print("") for elem in list(zip(matches, ranges)): print(elem[0], end=" ") print(elem[1]) print("") else: print("Sequence and regular expression can't be empty.")
#!/bin/env python3 # Prosite regular expressions matcher # Copyright (c) 2014 Tomasz Truszkowski # All rights reserved. import prosite_matcher if __name__ == '__main__': print("\n Hi, this is Prosite Matcher! \n") sequence = input("Sequence: ") regex = input("Regular expression: ") prositeMatcher = prosite_matcher.PrositeMatcher() prositeMatcher.compile(regex) matches, ranges = prositeMatcher.get_matches(sequence) print("Found patterns: ", end="") if (len(matches) > 0): print(sequence[ 0 : ranges[0][0] ], end="") for i in range(0, len(matches)): print("\033[91m", end="") print(sequence[ ranges[i][0] : ranges[i][1] ], end="") print("\033[0m", end="") if (i < len(matches) - 1): print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="") print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)]) else: print(sequence) print("") for elem in list(zip(matches, ranges)): print(elem[0], end=" ") print(elem[1]) print("")
Add command-line argument for server host
# Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com> # 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 utils utils.AddVendorFolderToSysPath() import argparse import waitress import handlers def ParseArgs(): parser = argparse.ArgumentParser() parser.add_argument( '--host', type = str, default = '127.0.0.1', help = 'server host' ) parser.add_argument( '--port', type = int, default = 0, help = 'server port' ) return parser.parse_args() def Main(): args = ParseArgs() waitress.serve( handlers.app, host = args.host, port = args.port ) if __name__ == "__main__": Main()
# Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com> # 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 utils utils.AddVendorFolderToSysPath() import argparse import waitress import handlers def ParseArgs(): parser = argparse.ArgumentParser() parser.add_argument( '--port', type = int, default = 0, help = 'server port') return parser.parse_args() def Main(): args = ParseArgs() waitress.serve( handlers.app, host = '127.0.0.1', port = args.port ) if __name__ == "__main__": Main()
Add prop "spin" for icon
const React = require('react'); const classNames = require('classnames'); const Icon = React.createClass({ propTypes: { // Icon of the icon in the collection id: React.PropTypes.string, // Type of collection type: React.PropTypes.string, // Extra className className: React.PropTypes.string, // Is the icon spinning? spin: React.PropTypes.bool }, getDefaultProps: function() { return { type: 'octicon', spin: false }; }, render: function() { let { type, id, className, spin } = this.props; className = classNames( type + ' ' + type + '-' + id, className, { 'icon-spin': spin } ); return <i className={className}></i>; } }); module.exports = Icon;
var React = require('react'); var Icon = React.createClass({ propTypes: { id: React.PropTypes.string, type: React.PropTypes.string, className: React.PropTypes.string }, getDefaultProps: function() { return { type: 'octicon' }; }, render: function() { var type = this.props.type; var id = this.props.id; var className = this.props.className; if (!className) { className = type + ' ' + type + '-' + id; } return <i className={className}></i>; } }); module.exports = Icon;
Set status code for now found
var path = require('path'); var deliver = require('deliver'); var mime = require('mime'); var url = require('url'); module.exports = function (fileStore) { return function (req, res, next) { res.send = function (pathname, isNotRelative, statusCode) { req.url = (isNotRelative) ? pathname : fileStore.getPath(path.join('/', req.config.cwd, pathname || '')); // S3 content types aren't set, // so they need to be set res.on('header', function () { res.setHeader('content-type', mime.lookup(url.parse(req.url).pathname)); }); return deliver(req, { statusCode: statusCode }).pipe(res); }; next(); }; };
var path = require('path'); var deliver = require('deliver'); var mime = require('mime'); var url = require('url'); module.exports = function (fileStore) { return function (req, res, next) { res.send = function (pathname, isNotRelative, statusCode) { req.url = (isNotRelative) ? pathname : fileStore.getPath(path.join('/', req.config.cwd, pathname || '')); // S3 content types aren't set, // so they need to be set res.on('header', function () { // if (status) res.statusCode = statusCode; // TODO: test this res.setHeader('content-type', mime.lookup(url.parse(req.url).pathname)); }); return deliver(req).pipe(res); }; next(); }; };
Fix compilation issue in stub
// Copyright © 2017 Swarm Market <info@swarm.market> // // 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 cmd import ( "context" "github.com/spf13/cobra" "github.com/swarmdotmarket/perigord/migration" perigord "github.com/swarmdotmarket/perigord/perigord/cmd" ) var migrateCmd = &cobra.Command{ Use: "migrate", Run: func(cmd *cobra.Command, args []string) { if err := migration.RunMigrations(context.Background()); err != nil { perigord.Fatal(err) } }, } func init() { RootCmd.AddCommand(migrateCmd) }
// Copyright © 2017 Swarm Market <info@swarm.market> // // 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 cmd import ( "github.com/spf13/cobra" "github.com/swarmdotmarket/perigord/migration" perigord "github.com/swarmdotmarket/perigord/perigord/cmd" ) var migrateCmd = &cobra.Command{ Use: "migrate", Run: func(cmd *cobra.Command, args []string) { if err := migration.RunMigrations(); err != nil { perigord.Fatal(err) } }, } func init() { RootCmd.AddCommand(migrateCmd) }
Use absolute path for reading description from file (thanks @hodgestar)
import os from setuptools import setup, find_packages def listify(filename): return filter(None, open(filename, 'r').readlines()) def read_file(filename): filepath = os.path.join(os.path.dirname(__file__), filename) return open(filepath, 'r').read() setup( name="python-smpp", version="0.1.6a", url='http://github.com/praekelt/python-smpp', license='BSD', description="Python SMPP Library", long_description=read_file('README.rst'), author='Praekelt Foundation', author_email='dev@praekeltfoundation.org', packages=find_packages(), install_requires=['setuptools'].extend(listify('requirements.pip')), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
from setuptools import setup, find_packages def listify(filename): return filter(None, open(filename, 'r').readlines()) setup( name="python-smpp", version="0.1.6a", url='http://github.com/praekelt/python-smpp', license='BSD', description="Python SMPP Library", long_description=open('README.rst', 'r').read(), author='Praekelt Foundation', author_email='dev@praekeltfoundation.org', packages=find_packages(), install_requires=['setuptools'].extend(listify('requirements.pip')), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Use existing console for Ant build log
package org.metaborg.spoofax.eclipse.meta.ant; import java.io.PrintStream; import org.apache.tools.ant.DefaultLogger; import org.eclipse.ui.console.MessageConsole; import org.metaborg.spoofax.eclipse.util.ConsoleUtils; public class EclipseAntLogger extends DefaultLogger { private final MessageConsole console; private final PrintStream stream; public EclipseAntLogger() { super(); console = ConsoleUtils.get("Spoofax console"); stream = new PrintStream(console.newMessageStream()); } @Override protected void printMessage(String message, PrintStream unusedStream, int priority) { /* * HACK: instead of setting the output and error streams, just pass our own stream to printMessage. The reason * being that Ant likes to change the stream to stdout and stderr after class instantiation, overriding our * streams. */ super.printMessage(message, stream, priority); } }
package org.metaborg.spoofax.eclipse.meta.ant; import java.io.PrintStream; import org.apache.tools.ant.DefaultLogger; import org.eclipse.ui.console.MessageConsole; import org.metaborg.spoofax.eclipse.util.ConsoleUtils; public class EclipseAntLogger extends DefaultLogger { private final MessageConsole console; private final PrintStream stream; public EclipseAntLogger() { super(); console = ConsoleUtils.get("Spoofax language build"); stream = new PrintStream(console.newMessageStream()); console.activate(); } @Override protected void printMessage(String message, PrintStream unusedStream, int priority) { /* * HACK: instead of setting the output and error streams, just pass our own stream to printMessage. The reason * being that Ant likes to change the stream to stdout and stderr after class instantiation, overriding our * streams. */ super.printMessage(message, stream, priority); } }
Add another proxy server example string
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "159.122.164.163:8080", # (Example) - set your own proxy here "example2": "158.69.138.8:1080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "159.122.164.163:8080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Set a base API endpoint
import express from 'express' import {logger, http_logger} from './utils/logger' import {cookie_parser, session} from './utils/session' import body_parser from 'body-parser' import passport from 'passport' import express_validator from 'express-validator' import {authentication_router} from './routers/authentication_router' import {group_router} from './routers/group_router' import {counter_router} from './routers/counter_router' import {error_handler} from './utils/errors' import {init_authentication} from './utils/authentication' import {init_mongodb} from './utils/mongodb' init_mongodb(() => { const app = express() app.use(http_logger) app.use(cookie_parser) app.use(body_parser.urlencoded({ extended: true, })) app.use(body_parser.json()) app.use(session) app.use(passport.initialize()) app.use(passport.session()) app.use(express_validator()) app.use(authentication_router) const base_api_endpoint = '/api/v1' app.use(base_api_endpoint, group_router) app.use(base_api_endpoint, counter_router) app.use(error_handler) init_authentication() const port = process.env.VK_GROUP_STATS_SERVER_PORT || 3000 app.listen(port, () => { logger.info(`app listening on port ${port}`) }) })
import express from 'express' import {logger, http_logger} from './utils/logger' import {cookie_parser, session} from './utils/session' import body_parser from 'body-parser' import passport from 'passport' import express_validator from 'express-validator' import {authentication_router} from './routers/authentication_router' import {group_router} from './routers/group_router' import {counter_router} from './routers/counter_router' import {error_handler} from './utils/errors' import {init_authentication} from './utils/authentication' import {init_mongodb} from './utils/mongodb' init_mongodb(() => { const app = express() app.use(http_logger) app.use(cookie_parser) app.use(body_parser.urlencoded({ extended: true, })) app.use(body_parser.json()) app.use(session) app.use(passport.initialize()) app.use(passport.session()) app.use(express_validator()) app.use(authentication_router) app.use(group_router) app.use(counter_router) app.use(error_handler) init_authentication() const port = process.env.VK_GROUP_STATS_SERVER_PORT || 3000 app.listen(port, () => { logger.info(`app listening on port ${port}`) }) })
Remove deprecated --dev flag for composer
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install', $returnStatus); if ($returnStatus !== 0) { exit(1); } passthru( './vendor/bin/phpcs --standard=PSR2 -n src tests *.php', $returnStatus ); if ($returnStatus !== 0) { exit(1); } passthru('./vendor/bin/phpunit', $returnStatus); if ($returnStatus !== 0) { exit(1); } $xml = new SimpleXMLElement(file_get_contents('clover.xml')); foreach ($xml->xpath('//file/metrics') as $metric) { if ((int)$metric['elements'] !== (int)$metric['coveredelements']) { fputs(STDERR, "Code coverage was NOT 100%\n"); exit(1); } } echo "Code coverage was 100%\n";
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install --dev', $returnStatus); if ($returnStatus !== 0) { exit(1); } passthru( './vendor/bin/phpcs --standard=PSR2 -n src tests *.php', $returnStatus ); if ($returnStatus !== 0) { exit(1); } passthru('./vendor/bin/phpunit', $returnStatus); if ($returnStatus !== 0) { exit(1); } $xml = new SimpleXMLElement(file_get_contents('clover.xml')); foreach ($xml->xpath('//file/metrics') as $metric) { if ((int)$metric['elements'] !== (int)$metric['coveredelements']) { fputs(STDERR, "Code coverage was NOT 100%\n"); exit(1); } } echo "Code coverage was 100%\n";
Update tests to reflect c03ba5c
<?php namespace Thumbor; class UrlTest extends \PHPUnit_Framework_TestCase { public function testSign() { $this->assertEquals( '-qITCsYPvj2Lt0ivIX1eXHhGFOM=', Url::sign( 'fit-in/560x420/filters:fill(green)/my%2Fbig%2Fimage.jpg', 'MY_SECURE_KEY' ) ); } public function testToString() { $url = new Url( 'my/big/image.jpg', array('fit-in', '560x420', 'filters:fill(green)'), 'http://thumbor-server:8888', 'MY_SECURE_KEY' ); $this->assertEquals( 'http://thumbor-server:8888/-qITCsYPvj2Lt0ivIX1eXHhGFOM=/fit-in/560x420/filters:fill(green)/my%2Fbig%2Fimage.jpg', "$url" ); } }
<?php namespace Thumbor; class UrlTest extends \PHPUnit_Framework_TestCase { public function testSign() { $this->assertEquals( 'bDv76lTvUdX6vORS96scx7P185c=', Url::sign( 'fit-in/560x420/filters:fill(green)/my/big/image.jpg', 'MY_SECURE_KEY' ) ); } public function testToString() { $url = new Url( 'my/big/image.jpg', array('fit-in', '560x420', 'filters:fill(green)'), 'http://thumbor-server:8888', 'MY_SECURE_KEY' ); $this->assertEquals( 'http://thumbor-server:8888/bDv76lTvUdX6vORS96scx7P185c=/fit-in/560x420/filters:fill(green)/my%2Fbig%2Fimage.jpg', "$url" ); } }
Update Version signature to remove warning Signed-off-by: Vincent Demeester <87e1f221a672a14a323e57bb65eaea19d3ed3804@sbr.pm>
package app import ( "fmt" "os" "runtime" "text/template" "github.com/Sirupsen/logrus" "github.com/docker/libcompose/version" "github.com/urfave/cli" ) var versionTemplate = `Version: {{.Version}} ({{.GitCommit}}) Go version: {{.GoVersion}} Built: {{.BuildTime}} OS/Arch: {{.Os}}/{{.Arch}}` // Version prints the libcompose version number and additionnal informations. func Version(c *cli.Context) error { if c.Bool("short") { fmt.Println(version.VERSION) return nil } tmpl, err := template.New("").Parse(versionTemplate) if err != nil { logrus.Fatal(err) } v := struct { Version string GitCommit string GoVersion string BuildTime string Os string Arch string }{ Version: version.VERSION, GitCommit: version.GITCOMMIT, GoVersion: runtime.Version(), BuildTime: version.BUILDTIME, Os: runtime.GOOS, Arch: runtime.GOARCH, } if err := tmpl.Execute(os.Stdout, v); err != nil { logrus.Fatal(err) } fmt.Printf("\n") return nil }
package app import ( "fmt" "os" "runtime" "text/template" "github.com/Sirupsen/logrus" "github.com/docker/libcompose/version" "github.com/urfave/cli" ) var versionTemplate = `Version: {{.Version}} ({{.GitCommit}}) Go version: {{.GoVersion}} Built: {{.BuildTime}} OS/Arch: {{.Os}}/{{.Arch}}` // Version prints the libcompose version number and additionnal informations. func Version(c *cli.Context) { if c.Bool("short") { fmt.Println(version.VERSION) return } tmpl, err := template.New("").Parse(versionTemplate) if err != nil { logrus.Fatal(err) } v := struct { Version string GitCommit string GoVersion string BuildTime string Os string Arch string }{ Version: version.VERSION, GitCommit: version.GITCOMMIT, GoVersion: runtime.Version(), BuildTime: version.BUILDTIME, Os: runtime.GOOS, Arch: runtime.GOARCH, } if err := tmpl.Execute(os.Stdout, v); err != nil { logrus.Fatal(err) } fmt.Printf("\n") return }
Add the scripts to the page.
<!DOCTYPE html> <html> <head> <title>The Awesome Blog</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap --> <link href="/assets/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="/assets/css/bootstrap_theme.css" rel="stylesheet" media="screen"> </head> <body> <div class="container"> <h3 class="muted">The Awesome Blog!</h3> <?php if ($logged_in) echo $navbar; ?> <?php echo $content; ?> </div> <!-- /container --> <script src="http://code.jquery.com/jquery.js"></script> <script src="/assets/js/bootstrap.min.js"></script> <?php foreach ($scripts as $script) { echo "<script src='$script'></script>"; } ?> </body> </html>
<!DOCTYPE html> <html> <head> <title>The Awesome Blog</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap --> <link href="/assets/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="/assets/css/bootstrap_theme.css" rel="stylesheet" media="screen"> </head> <body> <div class="container"> <h3 class="muted">The Awesome Blog!</h3> <?php if ($logged_in) echo $navbar; ?> <?php echo $content; ?> </div> <!-- /container --> <script src="http://code.jquery.com/jquery.js"></script> <script src="/assets/js/bootstrap.min.js"></script> </body> </html>
Increase max message size for responses
/** * Copyright 2016 Gertjan Al * * 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 io.parsingdata.metal.tools.service; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(final MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/metal"); } @Override public void registerStompEndpoints(final StompEndpointRegistry registry) { registry.addEndpoint("/websocket").withSockJS(); } @Override public void configureWebSocketTransport(final WebSocketTransportRegistration registration) { registration.setMessageSizeLimit(Integer.MAX_VALUE); } }
/** * Copyright 2016 Gertjan Al * * 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 io.parsingdata.metal.tools.service; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(final MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/metal"); } @Override public void registerStompEndpoints(final StompEndpointRegistry registry) { registry.addEndpoint("/websocket").withSockJS(); } }
Change version back to 0.2.0a post-release.
from setuptools import setup, find_packages setup( name='vumi-wikipedia', version='0.2.0a', description='Vumi Wikipedia App', packages=find_packages(), include_package_data=True, install_requires=[ 'vumi>=0.5', 'unidecode', ], url='http://github.com/praekelt/vumi-wikipedia', license='BSD', long_description=open('README', 'r').read(), maintainer='Praekelt Foundation', maintainer_email='dev@praekelt.com', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
from setuptools import setup, find_packages setup( name='vumi-wikipedia', version='0.1.2', description='Vumi Wikipedia App', packages=find_packages(), include_package_data=True, install_requires=[ 'vumi>=0.5', 'unidecode', ], url='http://github.com/praekelt/vumi-wikipedia', license='BSD', long_description=open('README', 'r').read(), maintainer='Praekelt Foundation', maintainer_email='dev@praekelt.com', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
Reword label on strategy picker Closes #349
$(document).on("page:change", function(){ $("select.multi-select").multiselect({ buttonText: function(options) { var text = 'Customise technology behaviour'; if (options.length) { text = text + ' (' + options.length + ' selected)'; } return text; }, dropRight: true }); var cappingInput = $("input[type=checkbox][value=capping_solar_pv]") cappingInput.parents('a').append($(".slider-wrapper.hidden")); cappingInput.on("change", showSlider); showSlider.call(cappingInput); function showSlider(){ var sliderWrapper = $(this).parents('a').find(".slider-wrapper"); if($(this).is(":checked")){ sliderWrapper.removeClass("hidden"); } else{ sliderWrapper.addClass("hidden"); } }; $("#solar_pv_capping").slider({ focus: true, formatter: function(value){ return value + "%"; } }); });
$(document).on("page:change", function(){ $("select.multi-select").multiselect({ buttonWidth: '200px', buttonText: function(options) { if (options.length) { return "Pick a strategy (" + options.length + " selected)"; } else { return "Pick a strategy"; } }, dropRight: true }); var cappingInput = $("input[type=checkbox][value=capping_solar_pv]") cappingInput.parents('a').append($(".slider-wrapper.hidden")); cappingInput.on("change", showSlider); showSlider.call(cappingInput); function showSlider(){ var sliderWrapper = $(this).parents('a').find(".slider-wrapper"); if($(this).is(":checked")){ sliderWrapper.removeClass("hidden"); } else{ sliderWrapper.addClass("hidden"); } }; $("#solar_pv_capping").slider({ focus: true, formatter: function(value){ return value + "%"; } }); });
Remove opt_this param in forEach function
/** * @module ol/geom/flat/segments */ /** * This function calls `callback` for each segment of the flat coordinates * array. If the callback returns a truthy value the function returns that * value immediately. Otherwise the function returns `false`. * @param {Array<number>} flatCoordinates Flat coordinates. * @param {number} offset Offset. * @param {number} end End. * @param {number} stride Stride. * @param {function(import("../../coordinate.js").Coordinate, import("../../coordinate.js").Coordinate): T} callback Function * called for each segment. * @return {T|boolean} Value. * @template T */ export function forEach(flatCoordinates, offset, end, stride, callback) { const point1 = [flatCoordinates[offset], flatCoordinates[offset + 1]]; const point2 = []; let ret; for (; (offset + stride) < end; offset += stride) { point2[0] = flatCoordinates[offset + stride]; point2[1] = flatCoordinates[offset + stride + 1]; ret = callback(point1, point2); if (ret) { return ret; } point1[0] = point2[0]; point1[1] = point2[1]; } return false; }
/** * @module ol/geom/flat/segments */ /** * This function calls `callback` for each segment of the flat coordinates * array. If the callback returns a truthy value the function returns that * value immediately. Otherwise the function returns `false`. * @param {Array<number>} flatCoordinates Flat coordinates. * @param {number} offset Offset. * @param {number} end End. * @param {number} stride Stride. * @param {function(this: S, import("../../coordinate.js").Coordinate, import("../../coordinate.js").Coordinate): T} callback Function * called for each segment. * @param {S=} opt_this The object to be used as the value of 'this' * within callback. * @return {T|boolean} Value. * @template T,S */ export function forEach(flatCoordinates, offset, end, stride, callback, opt_this) { const point1 = [flatCoordinates[offset], flatCoordinates[offset + 1]]; const point2 = []; let ret; for (; (offset + stride) < end; offset += stride) { point2[0] = flatCoordinates[offset + stride]; point2[1] = flatCoordinates[offset + stride + 1]; ret = callback.call(opt_this, point1, point2); if (ret) { return ret; } point1[0] = point2[0]; point1[1] = point2[1]; } return false; }
Fix ServerSelectionTimeoutError: No servers found yet
# -*- coding: utf-8 -*- import ssl from src.testers.decorators import requires_userinfo @requires_userinfo def available(test): """ Check if MongoDB is compiled with OpenSSL support """ return 'OpenSSLVersion' in test.tester.info \ or 'openssl' in test.tester.info @requires_userinfo def enabled(test): """ Check if TLS/SSL is enabled on the server side """ if not available(test): return 3 try: with test.tester.conn._socket_for_writes() as socket_info: socket = socket_info.sock return isinstance(socket, ssl.SSLSocket) except (KeyError, AttributeError): return False @requires_userinfo def valid(test): """ Verify if server certificate is valid """ if not enabled(test): return 3 with test.tester.conn._socket_for_writes() as socket_info: cert = socket_info.sock.getpeercert() if not cert: return [2, 'Your server is presenting a self-signed certificate, which will not ' 'protect your connections from man-in-the-middle attacks.'] return True
# -*- coding: utf-8 -*- import ssl from src.testers.decorators import requires_userinfo @requires_userinfo def available(test): """ Check if MongoDB is compiled with OpenSSL support """ return 'OpenSSLVersion' in test.tester.info \ or 'openssl' in test.tester.info @requires_userinfo def enabled(test): """ Check if TLS/SSL is enabled on the server side """ if not available(test): return 3 try: with test.tester.conn._socket_for_writes() as socket_info: socket = socket_info.sock return isinstance(socket, ssl.SSLSocket) except (KeyError, AttributeError): return False def valid(test): """ Verify if server certificate is valid """ if not enabled(test): return 3 with test.tester.conn._socket_for_writes() as socket_info: cert = socket_info.sock.getpeercert() if not cert: return [2, 'Your server is presenting a self-signed certificate, which will not ' 'protect your connections from man-in-the-middle attacks.'] return True
Implement behavior for a non-existent file
#! /usr/bin/env node const {stdout, stderr, exit, argv} = process; const mv = require('mv'); const flags = require('minimist')(argv.slice(2)); const files = flags._; if (flags.h) stdout.write(require('./help/usage')); if (flags.help) stdout.write([ require('./help/synopsis'), require('./help/options'), require('./help/examples'), ].join('\n\n')); if (flags.h || flags.help) exit(0); if (files.length !== 2) { stderr.write(require('./help/usage')); exit(1); } mv(files[0], files[1], (error) => { if (error) { if (error.code === 'ENOENT') { stderr.write(`File not found: \`${files[0]}\`.`); exit(1); } else throw error; } exit(0); });
#! /usr/bin/env node const {stdout, stderr, exit, argv} = process; const mv = require('mv'); const flags = require('minimist')(argv.slice(2)); const files = flags._; if (flags.h) stdout.write(require('./help/usage')); if (flags.help) stdout.write([ require('./help/synopsis'), require('./help/options'), require('./help/examples'), ].join('\n\n')); if (flags.h || flags.help) exit(0); if (files.length !== 2) { stderr.write(require('./help/usage')); exit(1); } mv(files[0], files[1], (error) => { if (error) { stderr.write(error.message + '\n'); exit(2); } exit(0); });
Change license to BSD. 1.4
# coding: utf-8 from distutils.core import setup # python setup.py sdist --formats=bztar # python setup.py sdist --formats=bztar upload description = 'National characters transcription module.' import trans long_description = open('documentation.rst', 'rb').read() version = trans.__version__ setup( name = 'trans', version = version, description = description, long_description = long_description, author = 'Zelenyak Aleksandr aka ZZZ', author_email = 'ZZZ.Sochi@GMail.com', url = 'http://www.python.org/pypi/trans/', license = 'BSD', platforms = 'any', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], py_modules = ['trans'], )
# coding: utf-8 from distutils.core import setup # python setup.py sdist --formats=bztar # python setup.py sdist --formats=bztar upload description = 'National characters transcription module.' import trans long_description = open('documentation.rst', 'rb').read() version = trans.__version__ setup( name = 'trans', version = version, description = description, long_description = long_description, author = 'Zelenyak Aleksandr aka ZZZ', author_email = 'ZZZ.Sochi@GMail.com', url = 'http://www.python.org/pypi/trans/', license = 'GPL', platforms = 'any', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], py_modules = ['trans'], )
auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, }
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
Fix new syntax and add example using numpy arrays
import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt import numpy as np from fovea.graphics import * plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((a, b)).T[0], np.array((a, b)).T[1], 'g') cc, dd = Point2D((3,-2.5)), Point2D((-5.1,1.8)) plt.plot(np.array((cc, dd)).T[0], np.array((cc, dd)).T[1], 'b:') c, d = force_line_to_extent(Point2D((3,-2.5)), Point2D((-5.1,1.8)), plotter.domain, plotter.coords) plt.plot(np.array((c, d)).T[0], np.array((c, d)).T[1], 'r') e, f = force_line_to_extent(np.array((0.25,0)), np.array((1.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((e, f)).T[0], np.array((e, f)).T[1], 'g') plt.show()
import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt from fovea.graphics import * # ISSUE: fix to use new argument format for function (no global) plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1))) plt.plot(np.array((a, b)).T[0], np.array((a, b)).T[1], 'g') cc, dd = Point2D((3,-2.5)), Point2D((-5.1,1.8)) plt.plot(np.array((cc, dd)).T[0], np.array((cc, dd)).T[1], 'b:') c, d = force_line_to_extent(Point2D((3,-2.5)), Point2D((-5.1,1.8))) plt.plot(np.array((c, d)).T[0], np.array((c, d)).T[1], 'r') plt.show()
Fix UDF test, take two Change-Id: I817389d94dab665199d2c1b7365e8ce0d1495c41 Reviewed-on: http://gerrit.ent.cloudera.com:8080/504 Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com> Tested-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestUdfs(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestUdfs, cls).add_test_dimensions() # UDFs require codegen cls.TestMatrix.add_constraint( lambda v: v.get_value('exec_option')['disable_codegen'] == False) # There is no reason to run these tests using all dimensions. cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format == 'text' and\ v.get_value('table_format').compression_codec == 'none') # This must run serially because other tests executing 'invalidate metadata' will nuke # all loaded functions. # TODO: This can be run in parallel once functions are persisted correctly. @pytest.mark.execute_serially def test_udfs(self, vector): self.run_test_case('QueryTest/udf', vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestUdfs(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestUdfs, cls).add_test_dimensions() # UDFs require codegen cls.TestMatrix.add_constraint( lambda v: v.get_value('exec_option')['disable_codegen'] == False) # There is no reason to run these tests using all dimensions. cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format == 'text' and\ v.get_value('table_format').compression_codec == 'none') def test_udfs(self, vector): self.run_test_case('QueryTest/udf', vector)
Exclude non-null properties in response.
/* Copyright 2018 Telstra Open Source * * 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.openkilda.northbound.dto.switches; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Value; @Value @JsonInclude(JsonInclude.Include.NON_NULL) public class PortDto { @JsonProperty("switch_id") private String switchId; @JsonProperty("port_no") private int portNo; @JsonProperty("success") private Boolean success; @JsonProperty("message") private String message; public PortDto(@JsonProperty("switch_id") String switchId, @JsonProperty("port_id") int portNo, @JsonProperty("success") Boolean success, @JsonProperty("message") String message) { this.switchId = switchId; this.portNo = portNo; this.success = success; this.message = message; } }
/* Copyright 2018 Telstra Open Source * * 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.openkilda.northbound.dto.switches; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Value; @Value public class PortDto { @JsonProperty("switch_id") private String switchId; @JsonProperty("port_no") private int portNo; @JsonProperty("success") private Boolean success; @JsonProperty("message") private String message; public PortDto(@JsonProperty("switch_id") String switchId, @JsonProperty("port_id") int portNo, @JsonProperty("success") Boolean success, @JsonProperty("message") String message) { this.switchId = switchId; this.portNo = portNo; this.success = success; this.message = message; } }
Make xvfb e files end with .err
#!/usr/bin/env python # -*- coding: utf-8 -*- """ util.py Utility functions/constants across seam """ __author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>' __copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved' import sys PY2 = sys.version_info[0] == 2 if PY2: STRING_TYPE = basestring else: STRING_TYPE = str import os from string import digits, ascii_letters from random import choice total = digits + ascii_letters def get_tmp_filename(ext='out', basename='/tmp', fname_length=32): fname = ''.join(choice(total) for _ in range(fname_length)) return os.path.join(basename, '{}.{}'.format(fname, ext)) def wrap_with_xvfb(command, wait=5, server_args='-screen 0, 1600x1200x24'): parts = ['xvfb-run', '-a', # automatically get a free server number '-f {}'.format(get_tmp_filename()), '-e {}'.format(get_tmp_filename(ext='err')), '--wait={:d}'.format(wait), '--server-args="{}"'.format(server_args), command] return ' '.join(parts)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ util.py Utility functions/constants across seam """ __author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>' __copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved' import sys PY2 = sys.version_info[0] == 2 if PY2: STRING_TYPE = basestring else: STRING_TYPE = str import os from string import digits, ascii_letters from random import choice total = digits + ascii_letters def get_tmp_filename(ext='out', basename='/tmp', fname_length=32): fname = ''.join(choice(total) for _ in range(fname_length)) return os.path.join(basename, '{}.{}'.format(fname, ext)) def wrap_with_xvfb(command, wait=5, server_args='-screen 0, 1600x1200x24'): parts = ['xvfb-run', '-a', # automatically get a free server number '-f {}'.format(get_tmp_filename()), '-e {}'.format(get_tmp_filename()), '--wait={:d}'.format(wait), '--server-args="{}"'.format(server_args), command] return ' '.join(parts)
Disable derequire in test environments by default
/* jshint node: true */ 'use strict'; var derequire = require('broccoli-derequire'); module.exports = { name: 'ember-derequire', included: function(app) { this._super.included.apply(this, arguments); this.options = app.options.derequire || {}; var defaultOptions = {enabled: this.app.env !== 'test'}; for (var option in defaultOptions) { if (!this.options.hasOwnProperty(option)) { this.options[option] = defaultOptions[option]; } } }, postprocessTree: function(type, tree) { if (type === 'all' && this.isEnabled()) { tree = derequire(tree, this.options); } return tree; }, contentFor:function (type) { if(type === 'app-boot' && this.isEnabled()){ return 'var define = define; var require = require;' } }, isEnabled:function() { return this.options && this.options.enabled; } };
/* jshint node: true */ 'use strict'; var derequire = require('broccoli-derequire'); module.exports = { name: 'ember-derequire', included: function(app) { this._super.included.apply(this, arguments); this.options = app.options.derequire || {}; var defaultOptions = {enabled: true}; for (var option in defaultOptions) { if (!this.options.hasOwnProperty(option)) { this.options[option] = defaultOptions[option]; } } }, postprocessTree: function(type, tree) { if (type === 'all' && this.options && this.options.enabled) { tree = derequire(tree, this.options); } return tree; }, contentFor:function (type) { if(type === 'app-boot'){ return 'var define = define; var require = require;' } } };
Fix redirect when switch language.
import React, { Component } from 'react' import { Link } from 'react-router' import Header from 'Components/Header' import Footer from 'Components/Footer' import zhcn from '../../../intl/zh-cn' import en from '../../../intl/en' import 'styles/pages/index.scss' const format = (locale) => { return (key) => { let v = null; if (locale === 'zh-cn') { v = zhcn[key] } else { v = en[key] } return v || key; } } export default class Index extends Component { changeLang(lang) { let {pathname, query} = this.props.location query.locale = lang this.context.router.replace({pathname: pathname, query}) } render() { const {query} = this.props.location const __ = format(query.locale); return ( <div id='container'> <Header __={__} query={query} changeLang={this.changeLang.bind(this)} /> {React.cloneElement(this.props.children, {__, query})} <Footer __={__} query={query} /> </div> ) } } Index.contextTypes = { router: React.PropTypes.object.isRequired }
import React, { Component } from 'react' import { Link } from 'react-router' import Header from 'Components/Header' import Footer from 'Components/Footer' import zhcn from '../../../intl/zh-cn' import en from '../../../intl/en' import 'styles/pages/index.scss' const format = (locale) => { return (key) => { let v = null; if (locale === 'zh-cn') { v = zhcn[key] } else { v = en[key] } return v || key; } } export default class Index extends Component { changeLang(lang) { let {pathname, query} = this.props.location query.locale = lang this.context.router.replace({pathname: location.pathname, query}) } render() { const {query} = this.props.location const __ = format(query.locale); return ( <div id='container'> <Header __={__} query={query} changeLang={this.changeLang.bind(this)} /> {React.cloneElement(this.props.children, {__, query})} <Footer __={__} query={query} /> </div> ) } } Index.contextTypes = { router: React.PropTypes.object.isRequired }
Add code for PDO connects to ms sql and sqlite, fix comments. git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@858 54a900ba-8191-11dd-a5c9-f1483cedc3eb
<?php include '_CONFIG.php'; try { $dbh = new PDO("mysql:host=$CC_dbhost;dbname=$CC_database_name", $CC_dbusername, $CC_dbpasswd); // MS SQL Server and Sybase with PDO_DBLIB //$dbh = new PDO("mssql:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd"); //$dbh = new PDO("sybase:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd"); // SQLite Database #$dbh = new PDO("sqlite:my/database/path/database.db"); } catch(PDOException $e) { echo $e->getMessage(); }
<?php include '_CONFIG.php'; try { $dbh = new PDO("mysql:host=$CC_dbhost;dbname=$CC_database_name", $CC_dbusername, $CC_dbpasswd); # MS SQL Server and Sybase with PDO_DBLIB #$dbh = new PDO("mssql:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd"); #$dbh = new PDO("sybase:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd"); # SQLite Database #$dbh = new PDO("sqlite:my/database/path/database.db"); } catch(PDOException $e) { echo $e->getMessage(); }
Use anyPost instead of POST / to catch all POST on /*
package xcarpaccio; import net.codestory.http.Configuration; import net.codestory.http.payload.Payload; import net.codestory.http.routes.Routes; public class WebConfiguration implements Configuration { private final Logger logger = new Logger(); @Override public void configure(Routes routes) { routes. get("/ping", "pong"). post("/feedback", (context) -> { Message message = context.extract(Message.class); logger.log(message.type + ": " + message.content); return new Payload(204); }). anyPost(context -> { String method = context.method(); String uri = context.uri(); String body = context.extract(String.class); logger.log(method + " " + uri + " " + body); return new Payload(204); }) ; } }
package xcarpaccio; import net.codestory.http.Configuration; import net.codestory.http.payload.Payload; import net.codestory.http.routes.Routes; public class WebConfiguration implements Configuration { private final Logger logger = new Logger(); @Override public void configure(Routes routes) { routes. get("/ping", "pong"). post("/feedback", (context) -> { Message message = context.extract(Message.class); logger.log(message.type + ": " + message.content); return new Payload(204); }). post("/", (context) -> { String method = context.method(); String uri = context.uri(); String body = context.extract(String.class); logger.log(method + " " + uri + " " + body); return new Payload(204); }) ; } }
Use a more descriptive variable name and point out, that the parameter must not be null. git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1721006 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 org.apache.jmeter.report.core; import java.io.Closeable; import org.apache.jmeter.report.core.Sample; /** * Describes sample writer basic operations.<br> * <br> * Basically a sample writer is able to write samples to an unknown destination * and close itself. <br> * * @since 2.14 */ abstract public class SampleWriter implements Closeable { /** * Write a sample to the underlying destination * * @param sample * The sample to be written (Must not be {@code null}) * @return The number of samples written at this time to the underlying * destination */ abstract public long write(Sample sample); }
/* * 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 org.apache.jmeter.report.core; import java.io.Closeable; import org.apache.jmeter.report.core.Sample; /** * Describes sample writer basic operations.<br> * <br> * Basically a sample writer is able to write samples to an unknown destination * and close itself. <br> * * @since 2.14 */ abstract public class SampleWriter implements Closeable { /** * Write a sample to the underlying destination * * @param s * The sample to be written * @return The number of samples written at this time to the undernlying * destination */ abstract public long write(Sample s); }
Set font height to improve glyph quality
var fontName = 'seti', gulp = require('gulp'), iconfont = require('gulp-iconfont'), iconfontCss = require('gulp-iconfont-css'), svgmin = require('gulp-svgmin'); gulp.task('font', function(){ gulp.src(['./icons/*.svg']) .pipe(iconfontCss({ fontName: fontName, path: './styles/_fonts/_template.less', targetPath: '../seti.less/', fontPath: './styles/_fonts/seti/' })) .pipe(iconfont({ normalize: true, fontHeight: 1000, fontName: fontName, formats: ['ttf', 'eot', 'woff', 'woff2', 'svg'] })) .pipe(gulp.dest('./styles/_fonts/seti/')); }); gulp.task('icon', ['svg', 'font']); gulp.task('icons', ['svg', 'font']); gulp.task('svg', function() { gulp.src('./icons/*.svg') .pipe(svgmin()) .pipe(gulp.dest('./icons')); });
var fontName = 'seti', gulp = require('gulp'), iconfont = require('gulp-iconfont'), iconfontCss = require('gulp-iconfont-css'), svgmin = require('gulp-svgmin'); gulp.task('font', function(){ gulp.src(['./icons/*.svg']) .pipe(iconfontCss({ fontName: fontName, path: './styles/_fonts/_template.less', targetPath: '../seti.less/', fontPath: './styles/_fonts/seti/' })) .pipe(iconfont({ normalize: true, fontName: fontName, formats: ['ttf', 'eot', 'woff', 'woff2', 'svg'] })) .pipe(gulp.dest('./styles/_fonts/seti/')); }); gulp.task('icon', ['svg', 'font']); gulp.task('icons', ['svg', 'font']); gulp.task('svg', function() { gulp.src('./icons/*.svg') .pipe(svgmin()) .pipe(gulp.dest('./icons')); });
Add a test to show JSON at the root.
package hello.controllers; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import hello.configuration.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @AutoConfigureMockMvc public class RootControllerTest { @Autowired private MockMvc mvc; @Test public void getRoot() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()); } @Test public void getJsonRoot() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } }
package hello.controllers; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import hello.configuration.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @AutoConfigureMockMvc public class RootControllerTest { @Autowired private MockMvc mvc; @Test public void getRoot() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()); } }
Revert "Redundant information is redundant." This reverts commit ed9224a57ac396f62d75d1111d4a3be2927b1695.
<?php //connect to the database $dbconn = pg_Connect("host=capstone06.cs.pdx.edu dbname=real user=postgres password=bees"); if (!$dbconn) { die("Error connecting to database."); } echo('{"graphs":['); $result = pg_exec($dbconn, "SELECT COUNT(subgraph_id) FROM subgraphs;"); $rows = pg_fetch_array($result, 0); $num = $rows[0]; for ($i = 1; $i < $num; $i++) { $result = pg_exec($dbconn, "SELECT num FROM subgraphs WHERE subgraph_id = $i;"); $count = pg_numrows($result); if ($count <= 0) { die("Bad query at $i"); } $array = pg_fetch_array($result, 0); if ($i > 1) { echo(', '); } echo('{"subgraph_id": ' . $i . ', "num": ' . $array[0] . '}'); } echo('] }'); pg_close($dbconn);
<?php //connect to the database $dbconn = pg_Connect("host=capstone06.cs.pdx.edu dbname=real user=postgres password=bees"); if (!$dbconn) { die("Error connecting to database."); } //there is no subgraph_id 0 echo('{"subgraphs":[0,'); $result = pg_exec($dbconn, "SELECT COUNT(subgraph_id) FROM subgraphs;"); $rows = pg_fetch_array($result, 0); $num = $rows[0]; for ($i = 1; $i < $num; $i++) { $result = pg_exec($dbconn, "SELECT num FROM subgraphs WHERE subgraph_id = $i;"); $count = pg_numrows($result); if ($count <= 0) { die("Bad query at $i"); } $array = pg_fetch_array($result, 0); if ($i > 1) { echo(', '); } echo($array[0]); } echo('] }'); pg_close($dbconn);
Remove link blog in menu
<?php namespace Olitaz\HomeBundle\Menu; use Knp\Bundle\MenuBundle\Menu; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Router; class MainMenu extends Menu { /** * @param Request $request * @param Router $router */ public function __construct(Request $request, Router $router) { parent::__construct(); $this->setCurrentUri($request->getRequestUri()); $this->addChild('Home', $router->generate('OlitazHomeBundle_homepage')); $this->addChild('Présentation', $router->generate('OlitazHomeBundle_presentation')); $this->addChild('Prestations', $router->generate('OlitazHomeBundle_prestations')); // $this->addChild('Références', $router->generate('OlitazHomeBundle_homepage')); $this->addChild('Contact', $router->generate('OlitazHomeBundle_contact')); } }
<?php namespace Olitaz\HomeBundle\Menu; use Knp\Bundle\MenuBundle\Menu; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Router; class MainMenu extends Menu { /** * @param Request $request * @param Router $router */ public function __construct(Request $request, Router $router) { parent::__construct(); $this->setCurrentUri($request->getRequestUri()); $this->addChild('Home', $router->generate('OlitazHomeBundle_homepage')); $this->addChild('Présentation', $router->generate('OlitazHomeBundle_presentation')); $this->addChild('Prestations', $router->generate('OlitazHomeBundle_prestations')); // $this->addChild('Références', $router->generate('OlitazHomeBundle_homepage')); $this->addChild('Contact', $router->generate('OlitazHomeBundle_contact')); $this->addChild('Blog', 'http://blog.olitaz.fr/'); } }
Add flags to the intent so it is launched correctly.
package io.selendroid.server.util; import android.content.Context; import android.content.Intent; import android.net.Uri; /** * A helper class for working with intents */ public class Intents { /** * Create an intent to start an activity, for both ServerInstrumentation and LightweightInstrumentation */ public static Intent createStartActivityIntent(Context context, String mainActivityName) { Intent intent = new Intent(); intent.setClassName(context, mainActivityName); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); return intent; } /** * Create an implicit intent based on the given URI. */ public static Intent createUriIntent(String intentUri) { return new Intent(Intent.ACTION_VIEW, Uri.parse(intentUri)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); } }
package io.selendroid.server.util; import android.content.Context; import android.content.Intent; import android.net.Uri; /** * A helper class for working with intents */ public class Intents { /** * Create an intent to start an activity, for both ServerInstrumentation and LightweightInstrumentation */ public static Intent createStartActivityIntent(Context context, String mainActivityName) { Intent intent = new Intent(); intent.setClassName(context, mainActivityName); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); return intent; } /** * Create an implicit intent based on the given URI. */ public static Intent createUriIntent(String intentUri) { return new Intent(Intent.ACTION_VIEW, Uri.parse(intentUri)); } }
Add limit on stats service
"use strict"; //Load dependencies var applicationStorage = process.require("core/applicationStorage"); /** * Insert a stat object * @param tier * @param raid * @param stat * @param callback */ module.exports.insertOne = function (tier, raid, stats, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); var obj = {tier: tier, raid: raid, stats: stats} collection.insertOne(obj, function (error) { callback(error); }); }; /** * Return the last stat (max 200) * @param raid * @param callback */ module.exports.getStats = function (tier, raid, limit, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); collection.find({tier: tier, raid: raid}, {stats:1}) .sort({_id: 1}) .limit(limit) .toArray(function (error, stats) { console.log(stats); callback(error, stats); }); };
"use strict"; //Load dependencies var applicationStorage = process.require("core/applicationStorage"); /** * Insert a stat object * @param tier * @param raid * @param stat * @param callback */ module.exports.insertOne = function (tier, raid, stats, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); var obj = {tier: tier, raid: raid, stats: stats} collection.insertOne(obj, function (error) { callback(error); }); }; /** * Return the last stat (max 200) * @param raid * @param callback */ module.exports.getStats = function (tier, raid, limit, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); collection.find({tier: tier, raid: raid}, {stats:1}) .sort({_id: -1}) .limit(limit) .toArray(function (error, stats) { console.log(stats); callback(error, stats); }); };
Fix to exclude slug field when is_home option is checked on page save
<?php namespace TypiCMS\Modules\Pages\Http\Requests; use TypiCMS\Modules\Core\Http\Requests\AbstractFormRequest; class FormRequest extends AbstractFormRequest { public function rules() { return [ 'template' => 'nullable|alpha_dash|max:255', 'image_id' => 'nullable|integer', 'module' => 'nullable|max:255', 'template' => 'nullable|max:255', 'title.*' => 'nullable|max:255', 'slug.*' => 'nullable|alpha_dash|max:255|exclude_if:is_home,1|required_with:title.*', 'meta_keywords.*' => 'nullable|max:255', 'meta_description.*' => 'nullable|max:255', ]; } }
<?php namespace TypiCMS\Modules\Pages\Http\Requests; use TypiCMS\Modules\Core\Http\Requests\AbstractFormRequest; class FormRequest extends AbstractFormRequest { public function rules() { return [ 'template' => 'nullable|alpha_dash|max:255', 'image_id' => 'nullable|integer', 'module' => 'nullable|max:255', 'template' => 'nullable|max:255', 'title.*' => 'nullable|max:255', 'slug.*' => 'nullable|alpha_dash|max:255|required_with:title.*', 'meta_keywords.*' => 'nullable|max:255', 'meta_description.*' => 'nullable|max:255', ]; } }
Check for nil first in interferace casting (go).
package main // safe -- 15.9ns/op // unsafe -- 1.6ns/op import ( "fmt" "syscall" "unsafe" ) // can we unsafe cast to unwrap all the interface layers? Or is the value in // memory different now? No! We have a new layer of indirection... func unsafeErr(err error) uintptr { if err != nil { p1 := (uintptr)(unsafe.Pointer(&err)) p2 := (*uintptr)(unsafe.Pointer(p1+8)) return *(*uintptr)(unsafe.Pointer(*p2)) } else { return 0 } } // Safe way, type assertion func safeErr(err error) uintptr { return uintptr(err.(syscall.Errno)) } func main() { // uinptr -> Errno -> error num := uintptr(16) errn := syscall.Errno(num) err := error(errn) fmt.Println("Num:", num) fmt.Println("Errno:", errn) fmt.Println("Error:", err) fmt.Println("Unsafe way:", unsafeErr(err)) fmt.Println("Safe way:", safeErr(err)) }
package main // safe -- 7.01ns/op // unsafe -- 0.60ns/op import ( "fmt" "syscall" "unsafe" ) // can we unsafe cast to unwrap all the interface layers? Or is the value in // memory different now? No! We have a new layer of indirection... func unsafeErr(err error) uintptr { p1 := (uintptr)(unsafe.Pointer(&err)) p2 := (*uintptr)(unsafe.Pointer(p1+8)) return *(*uintptr)(unsafe.Pointer(*p2)) } // Safe way, type assertion func safeErr(err error) uintptr { return uintptr(err.(syscall.Errno)) } func main() { // uinptr -> Errno -> error num := uintptr(16) errn := syscall.Errno(num) err := error(errn) fmt.Println("Num:", num) fmt.Println("Errno:", errn) fmt.Println("Error:", err) fmt.Println("Unsafe way:", unsafeErr(err)) fmt.Println("Safe way:", safeErr(err)) }
Set to "use strict" mode
(function(google) { 'use strict'; google.load('search', '1', { language: 'en', nocss: true }); google.setOnLoadCallback(function() { var cx = '000850824335660518947:3osiz3zllwq'; var customSearchOptions = {}; var customSearchControl = new google.search.CustomSearchControl(cx, customSearchOptions); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.enableSearchResultsOnly(); options.setAutoComplete(false); customSearchControl.draw('searchResult', options); function parseParamsFromUrl() { var params = {}; var parts = window.location.search.substr(1).split('&'); for (var i = 0; i < parts.length; i++) { var keyValuePair = parts[i].split('='); var key = decodeURIComponent(keyValuePair[0]); params[key] = keyValuePair[1] ? decodeURIComponent(keyValuePair[1].replace(/\+/g, ' ')) : keyValuePair[1]; } return params; } var urlParams = parseParamsFromUrl(); var queryParamName = 'q'; if (urlParams[queryParamName]) { customSearchControl.execute(urlParams[queryParamName]); } }, true); })(google);
(function(google) { google.load('search', '1', { language: 'en', nocss: true }); google.setOnLoadCallback(function() { var cx = '000850824335660518947:3osiz3zllwq'; var customSearchOptions = {}; var customSearchControl = new google.search.CustomSearchControl(cx, customSearchOptions); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.enableSearchResultsOnly(); options.setAutoComplete(false); customSearchControl.draw('searchResult', options); function parseParamsFromUrl() { var params = {}; var parts = window.location.search.substr(1).split('&'); for (var i = 0; i < parts.length; i++) { var keyValuePair = parts[i].split('='); var key = decodeURIComponent(keyValuePair[0]); params[key] = keyValuePair[1] ? decodeURIComponent(keyValuePair[1].replace(/\+/g, ' ')) : keyValuePair[1]; } return params; } var urlParams = parseParamsFromUrl(); var queryParamName = 'q'; if (urlParams[queryParamName]) { customSearchControl.execute(urlParams[queryParamName]); } }, true); })(google);
Declare dependency (belongs to commit:b56fc64)
from setuptools import setup, find_packages setup( name='zeit.calendar', version='1.6.12.dev0', author='gocept, Zeit Online', author_email='zon-backend@zeit.de', url='http://www.zeit.de/', description="vivi calendar", packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, license='BSD', namespace_packages=['zeit'], install_requires=[ 'setuptools', 'pyramid_dogpile_cache2', 'z3c.etestbrowser', 'zeit.cms>=2.105.1.dev0', ], entry_points={ 'fanstatic.libraries': [ 'zeit_calendar=zeit.calendar.browser.resources:lib', ], } )
from setuptools import setup, find_packages setup( name='zeit.calendar', version='1.6.12.dev0', author='gocept, Zeit Online', author_email='zon-backend@zeit.de', url='http://www.zeit.de/', description="vivi calendar", packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, license='BSD', namespace_packages=['zeit'], install_requires=[ 'setuptools', 'pyramid_dogpile_cache2', 'z3c.etestbrowser', 'zeit.cms>=2.64.0.dev0', ], entry_points={ 'fanstatic.libraries': [ 'zeit_calendar=zeit.calendar.browser.resources:lib', ], } )
Change url routes to use primary key instead of id
from django.conf.urls import patterns, include, url from django.contrib.auth.decorators import login_required from imager_images.views import (AlbumCreate, AlbumUpdate, AlbumDelete, PhotoCreate, PhotoDelete) urlpatterns = patterns('imager_images.views', url(r'^upload/$', login_required(PhotoCreate.as_view()), name='upload'), url(r'^delete/(?P<pk>\d+)/$', login_required(PhotoDelete.as_view()), name='delete'), url(r'^album_create/$', login_required(AlbumCreate.as_view()), name='album_create'), url(r'^album_update/(?P<pk>\d+)/$', login_required(AlbumUpdate.as_view()), name='album_update'), url(r'^album_delete/(?P<pk>\d+)/$', login_required(AlbumDelete.as_view()), name='album_delete'), )
from django.conf.urls import patterns, include, url from django.contrib.auth.decorators import login_required from imager_images.views import (AlbumCreate, AlbumUpdate, AlbumDelete, PhotoCreate, PhotoDelete) urlpatterns = patterns('imager_images.views', url(r'^upload/$', login_required(PhotoCreate.as_view()), name='upload'), url(r'^delete/(?P<id>\d+)/$', login_required(PhotoDelete.as_view()), name='delete'), url(r'^album_create/$', login_required(AlbumCreate.as_view()), name='album_create'), url(r'^album_update/(?P<id>\d+)/$', login_required(AlbumUpdate.as_view()), name='album_update'), url(r'^album_delete/(?P<id>\d+)/$', login_required(AlbumDelete.as_view()), name='album_delete'), )
Refresh db connections on uwsgi fork
import os import logging from uwsgidecorators import postfork from flask import Flask from model.base import db from route.base import blueprint # Register models and routes import model import route logging.basicConfig(level=logging.INFO) app = Flask(__name__) # app.config['PROPAGATE_EXCEPTIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://' +\ os.environ['USER'] + ':' +\ os.environ['PASSWORD'] + '@' +\ 'db/' + os.environ['SCHEMA'] db.init_app(app) with app.test_request_context(): db.create_all() db.session.commit() app.register_blueprint(blueprint) @postfork def refresh_db(): db.session.remove() db.init_app(app)
import os import logging from flask import Flask from model.base import db from route.base import blueprint # Register models and routes import model import route logging.basicConfig(level=logging.INFO) app = Flask(__name__) # app.config['PROPAGATE_EXCEPTIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://' +\ os.environ['USER'] + ':' +\ os.environ['PASSWORD'] + '@' +\ 'db/' + os.environ['SCHEMA'] db.init_app(app) with app.test_request_context(): db.create_all() db.session.commit() app.register_blueprint(blueprint)
Use verbose names in example table
from achilles import blocks, tables from time import sleep from models import Person register = blocks.Library('example') COUNTER = 0 @register.block(template_name='blocks/message.html') def counter(): global COUNTER COUNTER += 1 return { 'message': 'Block loaded %s times' % COUNTER, } @register.block(template_name='blocks/message.html') def slow(): sleep(1) return { 'message':'This block was loaded after page was loaded!', } @register.block('mytable') class Table(tables.Table): first_name = tables.Column(verbose_name='First name') last_name = tables.Column(verbose_name='First name') call_example = tables.ActionColumn(action='example:miau_person', verbose_name='Miauify') model = Person
from achilles import blocks, tables from time import sleep from models import Person register = blocks.Library('example') COUNTER = 0 @register.block(template_name='blocks/message.html') def counter(): global COUNTER COUNTER += 1 return { 'message': 'Block loaded %s times' % COUNTER, } @register.block(template_name='blocks/message.html') def slow(): sleep(1) return { 'message':'This block was loaded after page was loaded!', } @register.block('mytable') class Table(tables.Table): first_name = tables.Column() last_name = tables.Column() call_example = tables.ActionColumn(action='example:miau_person', verbose_name='miau') model = Person
Update bulk image generation command
from django.core.management.base import BaseCommand import easy_thumbnails from mediaman.models import ArtefactRepresentation import os #import ImageFile from PIL import ImageFile class Command(BaseCommand): help = "Generate thumbnails for Artefact Representations" def handle(self, *args, **options): unbuffered = os.fdopen(self.stdout.fileno(), 'w', 0) self.stdout = unbuffered ImageFile.MAXBLOCK = 1024 * 1024 * 10 # default is 64k, fixes "Suspension not allowed here" error from PIL ars = ArtefactRepresentation.objects.filter(public=True) self.stdout.write("Found %s public images\n" % ars.count()) for ar in ars: # self.stdout.write(str(ar.image) + "\n") if ar.image.storage.exists(ar.image): easy_thumbnails.files.generate_all_aliases( ar.image, include_global=True) self.stdout.write('.') else: self.stdout.write('n') self.stdout.write("\nProcessed all images\n")
from django.core.management.base import BaseCommand import easy_thumbnails from mediaman.models import ArtefactRepresentation import os class Command(BaseCommand): help = "Generate thumbnails for Artefact Representations" def handle(self, *args, **options): unbuffered = os.fdopen(self.stdout.fileno(), 'w', 0) self.stdout = unbuffered ars = ArtefactRepresentation.objects.all() self.stdout.write("Found %s images\n" % ars.count()) for ar in ars: # self.stdout.write(str(ar.image) + "\n") if ar.image.storage.exists(ar.image): easy_thumbnails.files.generate_all_aliases( ar.image, include_global=True) self.stdout.write('.') else: self.stdout.write('n') self.stdout.write("\nProcessed all images\n")
Hide Game ID input since it is automatically set
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import ugettext_lazy as _ from core import models DUPLICATE_PLAYER_ERROR = \ _('There is already a player with this name in your game') class CreateGameForm(forms.Form): bank_cash = forms.IntegerField(required=False, initial=12000) def clean_bank_cash(self): data = self.cleaned_data['bank_cash'] if data == None: data = 0 return data class AddPlayerForm(forms.ModelForm): class Meta: model = models.Player fields = ('game', 'name', 'cash') error_messages = { NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR}, } widgets = { 'game': forms.HiddenInput(), }
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import ugettext_lazy as _ from core import models DUPLICATE_PLAYER_ERROR = \ _('There is already a player with this name in your game') class CreateGameForm(forms.Form): bank_cash = forms.IntegerField(required=False, initial=12000) def clean_bank_cash(self): data = self.cleaned_data['bank_cash'] if data == None: data = 0 return data class AddPlayerForm(forms.ModelForm): class Meta: model = models.Player fields = ('game', 'name', 'cash') error_messages = { NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR}, }
Fix LoginForm to be conformant to builtin AuthenticationForm
from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control', })) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control', })) class SearchTrip(forms.Form): origin_id = forms.IntegerField() destination_id = forms.IntegerField() datetime = forms.DateTimeField()
from django import forms class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control', })) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control', })) class SearchTrip(forms.Form): origin_id = forms.IntegerField() destination_id = forms.IntegerField() datetime = forms.DateTimeField()
Add notification manager to service
package es.shyri.longoperationservice; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v7.app.NotificationCompat; /** * Created by Shyri on 01/02/2016. */ public class LongOperationService extends Service { public static final int NOTIFICATION_ID = 1234; private NotificationManager nm; private final IBinder mBinder = new LocalBinder(); public void onCreate() { super.onCreate(); nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } } /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { public LongOperationService getService() { // Return this instance of LocalService so clients can call public methods return LongOperationService.this; } } }
package es.shyri.longoperationservice; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; /** * Created by Shyri on 01/02/2016. */ public class LongOperationService extends Service { private final IBinder mBinder = new LocalBinder(); @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } } /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { public LongOperationService getService() { // Return this instance of LocalService so clients can call public methods return LongOperationService.this; } } }
Add required packages for pip install
#!/usr/bin/env python from setuptools import setup setup( name='ckanapi', version='3.3-dev', description= 'A command line interface and Python module for ' 'accessing the CKAN Action API', license='MIT', author='Ian Ward', author_email='ian@excess.org', url='https://github.com/ckan/ckanapi', packages=[ 'ckanapi', 'ckanapi.tests', 'ckanapi.tests.mock', 'ckanapi.cli', ], install_requires=[ 'setuptools', 'docopt', 'requests', 'simplejson', ], test_suite='ckanapi.tests', zip_safe=False, entry_points = """ [console_scripts] ckanapi=ckanapi.cli.main:main [paste.paster_command] ckanapi=ckanapi.cli.paster:CKANAPICommand """ )
#!/usr/bin/env python from setuptools import setup setup( name='ckanapi', version='3.3-dev', description= 'A command line interface and Python module for ' 'accessing the CKAN Action API', license='MIT', author='Ian Ward', author_email='ian@excess.org', url='https://github.com/ckan/ckanapi', packages=[ 'ckanapi', 'ckanapi.tests', 'ckanapi.tests.mock', 'ckanapi.cli', ], test_suite='ckanapi.tests', zip_safe=False, entry_points = """ [console_scripts] ckanapi=ckanapi.cli.main:main [paste.paster_command] ckanapi=ckanapi.cli.paster:CKANAPICommand """ )
Call connect instead of reconnect.
try: from .. import api, shared as G from ... import editor from ..exc_fmt import str_e from ..protocols import floo_proto except (ImportError, ValueError): from floo import editor from floo.common import api, shared as G from floo.common.exc_fmt import str_e from floo.common.protocols import floo_proto PORT_BLOCK_MSG = '''The Floobits plugin can't work because outbound traffic on TCP port 3448 is being blocked. See https://%s/help/network''' class NoReconnectProto(floo_proto.FlooProtocol): def reconnect(self): try: api.get_workspace(self.host, 'Floobits', 'doesnotexist') except Exception as e: print(str_e(e)) editor.error_message('Something went wrong. See https://%s/help/floorc to complete the installation.' % self.host) else: if not G.OUTBOUND_FILTERING: G.OUTBOUND_FILTERING = True return self.connect() editor.error_message('Something went wrong. See https://%s/help/floorc to complete the installation.' % self.host) self.stop()
try: from .. import api, shared as G from ... import editor from ..exc_fmt import str_e from ..protocols import floo_proto except (ImportError, ValueError): from floo import editor from floo.common import api, shared as G from floo.common.exc_fmt import str_e from floo.common.protocols import floo_proto PORT_BLOCK_MSG = '''The Floobits plugin can't work because outbound traffic on TCP port 3448 is being blocked. See https://%s/help/network''' class NoReconnectProto(floo_proto.FlooProtocol): def reconnect(self): try: api.get_workspace(self.host, 'Floobits', 'doesnotexist') except Exception as e: print(str_e(e)) editor.error_message('Something went wrong. See https://%s/help/floorc to complete the installation.' % self.host) else: if not G.OUTBOUND_FILTERING: G.OUTBOUND_FILTERING = True return super(NoReconnectProto, self).reconnect() editor.error_message('Something went wrong. See https://%s/help/floorc to complete the installation.' % self.host) self.stop()
Allow ignore directive with trailing spaces
// Copyright 2020 Frederik Zipp. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gocyclo import ( "go/ast" "strings" ) type directives []string func (ds directives) HasIgnore() bool { return ds.isPresent("ignore") } func (ds directives) isPresent(name string) bool { for _, d := range ds { if d == name { return true } } return false } func parseDirectives(doc *ast.CommentGroup) directives { if doc == nil { return directives{} } const prefix = "//gocyclo:" var ds directives for _, comment := range doc.List { if strings.HasPrefix(comment.Text, prefix) { ds = append(ds, strings.TrimSpace(strings.TrimPrefix(comment.Text, prefix))) } } return ds }
// Copyright 2020 Frederik Zipp. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gocyclo import ( "go/ast" "strings" ) type directives []string func (ds directives) HasIgnore() bool { return ds.isPresent("ignore") } func (ds directives) isPresent(name string) bool { for _, d := range ds { if d == name { return true } } return false } func parseDirectives(doc *ast.CommentGroup) directives { if doc == nil { return directives{} } const prefix = "//gocyclo:" var ds directives for _, comment := range doc.List { if strings.HasPrefix(comment.Text, prefix) { ds = append(ds, strings.TrimPrefix(comment.Text, prefix)) } } return ds }
Add timestamps to pivot table
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTagsAndPostTagTables extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tags', function (Blueprint $table) { $table->increments('id')->comment('Primary key.'); $table->string('tag_name'); $table->string('tag_slug'); $table->timestamps(); }); Schema::create('post_tag', function (Blueprint $table) { $table->integer('post_id'); $table->integer('tag_id'); $table->primary(['post_id', 'tag_id']); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('tags', function (Blueprint $table) { Schema::drop('tags'); }); Schema::table('post_tag', function (Blueprint $table) { Schema::drop('post_tag'); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTagsAndPostTagTables extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tags', function (Blueprint $table) { $table->increments('id')->comment('Primary key.'); $table->string('tag_name'); $table->string('tag_slug'); $table->timestamps(); }); Schema::create('post_tag', function (Blueprint $table) { $table->integer('post_id'); $table->integer('tag_id'); $table->primary(['post_id', 'tag_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('tags', function (Blueprint $table) { Schema::drop('tags'); }); Schema::table('post_tag', function (Blueprint $table) { Schema::drop('post_tag'); }); } }
Mark empty test as incomplete To make things more explicit.
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ // +--------------------------------------------------------------------------- // | SWAN [ $_SWANBR_SLOGAN_$ ] // +--------------------------------------------------------------------------- // | Copyright $_SWANBR_COPYRIGHT_$ // +--------------------------------------------------------------------------- // | Version $_SWANBR_VERSION_$ // +--------------------------------------------------------------------------- // | Licensed ( $_SWANBR_LICENSED_URL_$ ) // +--------------------------------------------------------------------------- // | $_SWANBR_WEB_DOMAIN_$ // +--------------------------------------------------------------------------- namespace KafkaTest\Produce; /** +------------------------------------------------------------------------------ * Kafka protocol since Kafka v0.8 +------------------------------------------------------------------------------ * * @package * @version $_SWANBR_VERSION_$ * @copyright Copyleft * @author $_SWANBR_AUTHOR_$ +------------------------------------------------------------------------------ */ class ProduceTest extends \PHPUnit_Framework_TestCase { // {{{ consts // }}} // {{{ members // }}} // {{{ functions // {{{ public function testSend() /** * testSend * * @access public * @return void */ public function testSend() { $this->markTestIncomplete('Test not implemented yet'); } // }}} // }}} }
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ // +--------------------------------------------------------------------------- // | SWAN [ $_SWANBR_SLOGAN_$ ] // +--------------------------------------------------------------------------- // | Copyright $_SWANBR_COPYRIGHT_$ // +--------------------------------------------------------------------------- // | Version $_SWANBR_VERSION_$ // +--------------------------------------------------------------------------- // | Licensed ( $_SWANBR_LICENSED_URL_$ ) // +--------------------------------------------------------------------------- // | $_SWANBR_WEB_DOMAIN_$ // +--------------------------------------------------------------------------- namespace KafkaTest\Produce; /** +------------------------------------------------------------------------------ * Kafka protocol since Kafka v0.8 +------------------------------------------------------------------------------ * * @package * @version $_SWANBR_VERSION_$ * @copyright Copyleft * @author $_SWANBR_AUTHOR_$ +------------------------------------------------------------------------------ */ class ProduceTest extends \PHPUnit_Framework_TestCase { // {{{ consts // }}} // {{{ members // }}} // {{{ functions // {{{ public function testSend() /** * testSend * * @access public * @return void */ public function testSend() { } // }}} // }}} }
Remove hard coding the 401 and instead give it a readable name.
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. var http = require('http'); var httpStatus = require('http-status'); module.exports = function(apikeyCache) { 'use strict'; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function* validateAPIKey(next) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Invalid apikey'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Invalid apikey'); } this.mcapp = { user: user }; yield next; }; };
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. var http = require('http'); module.exports = function(apikeyCache) { 'use strict'; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function* validateAPIKey(next) { let apikey = this.query.apikey || this.throw(401, 'Invalid apikey'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(401, 'Invalid apikey'); } this.mcapp = { user: user }; yield next; }; };
Use Setuptools instead of the deprecated Disutils
from setuptools import setup setup( name='enumerator', version='0.1.4', author='Erik Dominguez, Steve Coward', author_email='maleus@overflowsecurity.com, steve@sugarstack.io', maintainer='Steve Coward', maintainer_email='steve@sugarstack.io', scripts=['bin/enumerator'], packages=['enumerator', 'enumerator.static', 'enumerator.lib', 'enumerator.lib.services'], package_data={ '': ['*.txt'], }, url='http://pypi.python.org/pypi/enumerator/', license='LICENSE.txt', description='enumerator is a tool built to assist in automating the often tedious task of enumerating a target or list of targets during a penetration test.', long_description=open('README.txt').read(), install_requires=[ 'blinker==1.3', ], )
from distutils.core import setup setup( name='enumerator', version='0.1.4', author='Erik Dominguez, Steve Coward', author_email='maleus@overflowsecurity.com, steve@sugarstack.io', maintainer='Steve Coward', maintainer_email='steve@sugarstack.io', scripts=['bin/enumerator'], packages=['enumerator', 'enumerator.static', 'enumerator.lib', 'enumerator.lib.services'], package_data={ '': ['*.txt'], }, url='http://pypi.python.org/pypi/enumerator/', license='LICENSE.txt', description='enumerator is a tool built to assist in automating the often tedious task of enumerating a target or list of targets during a penetration test.', long_description=open('README.txt').read(), install_requires=[ 'blinker==1.3', ], )
Add directive allowing users to use our auth policy
default_settings = [ ('auth_url', str, 'http://localhost:5000/v3'), ('region', str, 'RegionOne'), ('user_domain_name', str, 'Default'), ('cacert', str, ''), ] def parse_settings(settings): parsed = {} def populate(name, convert, default): sname = '%s%s' % ('keystone.', name) value = convert(settings.get(sname, default)) parsed[sname] = value for name, convert, default in default_settings: populate(name, convert, default) return parsed def includeme(config): """ Set up standard configurator registrations. Use via: .. code-block:: python config = Configurator() config.include('pyramid_keystone') """ # We use an action so that the user can include us, and then add the # required variables, upon commit we will pick up those changes. def register(): registry = config.registry settings = parse_settings(registry.settings) registry.settings.update(settings) config.action('keystone-configure', register) config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
default_settings = [ ('auth_url', str, 'http://localhost:5000/v3'), ('region', str, 'RegionOne'), ('user_domain_name', str, 'Default'), ('cacert', str, ''), ] def parse_settings(settings): parsed = {} def populate(name, convert, default): sname = '%s%s' % ('keystone.', name) value = convert(settings.get(sname, default)) parsed[sname] = value for name, convert, default in default_settings: populate(name, convert, default) return parsed def includeme(config): """ Set up standard configurator registrations. Use via: .. code-block:: python config = Configurator() config.include('pyramid_keystone') """ # We use an action so that the user can include us, and then add the # required variables, upon commit we will pick up those changes. def register(): registry = config.registry settings = parse_settings(registry.settings) registry.settings.update(settings) config.action('keystone-configure', register)
Include code the cancels the request after 5s
var media = require('rtc-media'); var h = require('hyperscript'); var crel = require('crel'); var screenshare = require('..')({ chromeExtension: 'rtc.io screenshare', version: '^1.0.0' }); var buttons = { install: h('button', 'Install Extension', { onclick: function() { chrome.webstore.install(); }}), capture: h('button', 'Capture Screen', { onclick: shareScreen }) }; function shareScreen() { screenshare.request(function(err, constraints) { if (err) { return console.error('Could not capture window: ', err); } console.log('attempting capture with constraints: ', constraints); media({ constraints: constraints, target: document.getElementById('main') }); }); // you better select something quick or this will be cancelled!!! setTimeout(screenshare.cancel, 5e3); } // detect whether the screenshare plugin is available and matches // the required version screenshare.available(function(err, version) { var actions = document.getElementById('actions'); if (err) { return actions.appendChild(buttons.install); } actions.appendChild(buttons.capture); }); // on install show the capture button and remove the install button if active screenshare.on('activate', function() { if (buttons.install.parentNode) { buttons.install.parentNode.removeChild(buttons.install); } document.getElementById('actions').appendChild(buttons.capture); });
var media = require('rtc-media'); var h = require('hyperscript'); var crel = require('crel'); var screenshare = require('..')({ chromeExtension: 'rtc.io screenshare', version: '^1.0.0' }); var buttons = { install: h('button', 'Install Extension', { onclick: function() { chrome.webstore.install(); }}), capture: h('button', 'Capture Screen', { onclick: shareScreen }) }; function shareScreen() { screenshare.request(function(err, constraints) { if (err) { return console.error('Could not capture window: ', err); } console.log('attempting capture with constraints: ', constraints); media({ constraints: constraints, target: document.getElementById('main') }); }); } // detect whether the screenshare plugin is available and matches // the required version screenshare.available(function(err, version) { var actions = document.getElementById('actions'); if (err) { return actions.appendChild(buttons.install); } actions.appendChild(buttons.capture); }); // on install show the capture button and remove the install button if active screenshare.on('activate', function() { if (buttons.install.parentNode) { buttons.install.parentNode.removeChild(buttons.install); } document.getElementById('actions').appendChild(buttons.capture); });
Add Error title if Service does not register success.
<?php namespace Daruwanov\Provider; use Silex\Application; use Silex\ServiceProviderInterface; use Mandrill; use Mandrill_Messages; /* * MandrillServiceProvider */ class MandrillMessagesServiceProvider implements ServiceProviderInterface { /* * register */ public function register(Application $app) { $app['mandrill.messages'] = $app->share(function() use ($app) { if(isset($app['mandrill']) && is_array($app['mandrill'])) { $mandrill = new Mandrill($app['mandrill']['password']); $mandrillMessages = new Mandrill_Messages($mandrill); } else { throw new \Exception("Error: Array key 'mandrill' does not exist or input data not Array"); } return $mandrillMessages; }); } public function boot(Application $app) { } }
<?php namespace Daruwanov\Provider; use Silex\Application; use Silex\ServiceProviderInterface; use Mandrill; use Mandrill_Messages; /* * MandrillServiceProvider */ class MandrillMessagesServiceProvider implements ServiceProviderInterface { /* * register */ public function register(Application $app) { $app['mandrill.messages'] = $app->share(function() use ($app) { if(isset($app['mandrill']) && is_array($app['mandrill'])) { $mandrill = new Mandrill($app['mandrill']['password']); $mandrillMessages = new Mandrill_Messages($mandrill); } else { throw new \Exception("Bas"); } return $mandrillMessages; }); } public function boot(Application $app) { } }
user_voting: Add date field for timestamps
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.db import models from user_voting.managers import VoteManager SCORES = ( (u'+1', +1), (u'-1', -1), (u'?', 0), ) class Vote(models.Model): """ A vote on an object by a User. """ user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey('content_type', 'object_id') score = models.SmallIntegerField() date = models.DateTimeField(auto_now=True) objects = VoteManager() class Meta: db_table = 'user_votes' # One vote per user per object unique_together = (('user', 'content_type', 'object_id'),) def __unicode__(self): return u'%s: score %d by %s' % (self.object, self.score, self.user)
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.db import models from user_voting.managers import VoteManager SCORES = ( (u'+1', +1), (u'-1', -1), (u'?', 0), ) class Vote(models.Model): """ A vote on an object by a User. """ user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey('content_type', 'object_id') score = models.SmallIntegerField() objects = VoteManager() class Meta: db_table = 'user_votes' # One vote per user per object unique_together = (('user', 'content_type', 'object_id'),) def __unicode__(self): return u'%s: score %d by %s' % (self.object, self.score, self.user)
Fix relative import of models
""" Define custom transformations. See class Transformation in models.py for the base class Transformation. This file stores a list of all the subclasses of Transformation made available by default. Note that they don't necessarily tell you anything about the nature in which two Info's relate to each other, but if used sensibly they will do so. """ from .models import Transformation class Replication(Transformation): """An instance of one info being identically copied into another.""" __mapper_args__ = { "polymorphic_identity": "replication" } class Mutation(Transformation): """An instance of one info being tranformed into another + mutations.""" __mapper_args__ = { "polymorphic_identity": "mutation" } class Compression(Transformation): """An instance of one info being compressed into another.""" __mapper_args__ = { "polymorphic_identity": "compression" } class Response(Transformation): """An instance of one info being a response to another.""" __mapper_args__ = { "polymorphic_identity": "response" }
""" Define custom transformations. See class Transformation in models.py for the base class Transformation. This file stores a list of all the subclasses of Transformation made available by default. Note that they don't necessarily tell you anything about the nature in which two Info's relate to each other, but if used sensibly they will do so. """ from models import Transformation class Replication(Transformation): """An instance of one info being identically copied into another.""" __mapper_args__ = { "polymorphic_identity": "replication" } class Mutation(Transformation): """An instance of one info being tranformed into another + mutations.""" __mapper_args__ = { "polymorphic_identity": "mutation" } class Compression(Transformation): """An instance of one info being compressed into another.""" __mapper_args__ = { "polymorphic_identity": "compression" } class Response(Transformation): """An instance of one info being a response to another.""" __mapper_args__ = { "polymorphic_identity": "response" }
Fix failing unit tests for bigbase
package bigbase import ( "testing" ) func TestBigMandelbrotSanity(t *testing.T) { origin := BigComplex{MakeBigFloat(0.0, testPrec), MakeBigFloat(0.0, testPrec)} non := BigComplex{MakeBigFloat(2.0, testPrec), MakeBigFloat(4, testPrec)} sqrtDL := MakeBigFloat(2.0, testPrec) const iterateLimit uint8 = 255 originMember := BigMandelbrotMember{ C: &origin, SqrtDivergeLimit: &sqrtDL, Prec: testPrec, } nonMember := BigMandelbrotMember{ C: &non, SqrtDivergeLimit: &sqrtDL, Prec: testPrec, } originMember.Mandelbrot(iterateLimit) nonMember.Mandelbrot(iterateLimit) if !originMember.InSet { t.Error("Expected origin to be in Mandelbrot set") } if nonMember.InSet { t.Error("Expected ", nonMember, " to be outside Mandelbrot set") } if nonMember.InvDiv >= iterateLimit { t.Error("Expected negativeMembership to have InvDivergence below IterateLimit") } }
package bigbase import ( "testing" ) func TestBigMandelbrotSanity(t *testing.T) { origin := BigComplex{MakeBigFloat(0.0, testPrec), MakeBigFloat(0.0, testPrec)} non := BigComplex{MakeBigFloat(2.0, testPrec), MakeBigFloat(4, testPrec)} sqrtDL := MakeBigFloat(2.0, testPrec) const iterateLimit uint8 = 255 originMember := BigMandelbrotMember{ C: &origin, SqrtDivergeLimit: &sqrtDL, Prec: testPrec, } nonMember := BigMandelbrotMember{ C: &non, SqrtDivergeLimit: &sqrtDL, Prec: testPrec, } originMember.Mandelbrot(iterateLimit) nonMember.Mandelbrot(iterateLimit) if !originMember.SetMember() { t.Error("Expected origin to be in Mandelbrot set") } if nonMember.SetMember() { t.Error("Expected ", nonMember, " to be outside Mandelbrot set") } if nonMember.InverseDivergence() >= iterateLimit { t.Error("Expected negativeMembership to have InvDivergence below IterateLimit") } }
Remove hack for popper fix
/* eslint-env node */ 'use strict'; const EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { let app = new EmberApp(defaults, { 'ember-bootstrap': { 'importBootstrapFont': true, 'bootstrapVersion': 3, 'importBootstrapCSS': true }, 'ember-power-select': { theme: 'bootstrap' }, fingerprint: { enabled: false }, sourcemaps: { enabled: true, // This allows sourcemaps to be generated in all environments extensions: ['js'] } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. // app.import('node_modules/popper.js/dist/umd/popper.js.map', { destDir: 'assets' }); return app.toTree(); };
/* eslint-env node */ 'use strict'; const EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { let app = new EmberApp(defaults, { 'ember-bootstrap': { 'importBootstrapFont': true, 'bootstrapVersion': 3, 'importBootstrapCSS': true }, 'ember-power-select': { theme: 'bootstrap' }, fingerprint: { enabled: false }, sourcemaps: { enabled: true, // This allows sourcemaps to be generated in all environments extensions: ['js'] } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('node_modules/popper.js/dist/umd/popper.js.map', { destDir: 'assets' }); return app.toTree(); };
Use old JS for loop over forEach for backwards compatibility.
src = """ (function() { var initialX = 0; var initialY = 0; function onMouseMove(ev) { var x = ev.screenX - initialX; var y = ev.screenY - initialY; window.pywebview._bridge.call('moveWindow', [x, y], 'move'); } function onMouseUp() { window.removeEventListener('mousemove', onMouseMove); } function onMouseDown(ev) { initialX = ev.clientX; initialY = ev.clientY; window.addEventListener('mouseup', onMouseUp); window.addEventListener('mousemove', onMouseMove); } var dragBlocks = document.querySelectorAll('%s'); for(var i=0; i < dragBlocks.length; i++) { dragBlocks[i].addEventListener('mousedown', onMouseDown); } })(); """
src = """ (function() { var initialX = 0; var initialY = 0; function onMouseMove(ev) { var x = ev.screenX - initialX; var y = ev.screenY - initialY; window.pywebview._bridge.call('moveWindow', [x, y], 'move'); } function onMouseUp() { window.removeEventListener('mousemove', onMouseMove); } function onMouseDown(ev) { initialX = ev.clientX; initialY = ev.clientY; window.addEventListener('mouseup', onMouseUp); window.addEventListener('mousemove', onMouseMove); } var dragBlocks = document.querySelectorAll('%s'); dragBlocks.forEach(function(dragBlock) { dragBlock.addEventListener('mousedown', onMouseDown); }); })(); """
Fix for workchat composer cursor jumping Summary: As figured out in T47552048, the issue of cursor jumping is happening because the draft editor's selection state is not in the correct state. After digging in, I discovered that the draft editor manages this state through the contenteditable div's onSelect event, but it is not being fired in certain cases. So I am changing the code to update the selection state when mouseUp and keyUp events are fired, and this fixes the issue as these events are fired even in those cases where onSelect is not. Although this means that there are some redundant updates to the selection state, this shouldn't cause any bugs. I suspect this is happening because of some change/bug on how chrome is firing events on contenteditable, since it doesn't repro on firefox and also I couldn't find any code changes that match the bug timeline. Reviewed By: claudiopro Differential Revision: D17054885 fbshipit-source-id: 06b1e96629828d4cb1c9cab36c2711c6464f1f3c
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local * @emails oncall+draft_js */ 'use strict'; import type DraftEditor from 'DraftEditor.react'; const UserAgent = require('UserAgent'); const onBeforeInput = require('editOnBeforeInput'); const onBlur = require('editOnBlur'); const onCompositionStart = require('editOnCompositionStart'); const onCopy = require('editOnCopy'); const onCut = require('editOnCut'); const onDragOver = require('editOnDragOver'); const onDragStart = require('editOnDragStart'); const onFocus = require('editOnFocus'); const onInput = require('editOnInput'); const onKeyDown = require('editOnKeyDown'); const onPaste = require('editOnPaste'); const onSelect = require('editOnSelect'); const isChrome = UserAgent.isBrowser('Chrome'); const selectionHandler: (e: DraftEditor) => void = isChrome ? onSelect : e => {}; const DraftEditorEditHandler = { onBeforeInput, onBlur, onCompositionStart, onCopy, onCut, onDragOver, onDragStart, onFocus, onInput, onKeyDown, onPaste, onSelect, // In certain cases, contenteditable on chrome does not fire the onSelect // event, causing problems with cursor positioning. Therefore, the selection // state update handler is added to more events to ensure that the selection // state is always synced with the actual cursor positions. onMouseUp: selectionHandler, onKeyUp: selectionHandler, }; module.exports = DraftEditorEditHandler;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local * @emails oncall+draft_js */ 'use strict'; const onBeforeInput = require('editOnBeforeInput'); const onBlur = require('editOnBlur'); const onCompositionStart = require('editOnCompositionStart'); const onCopy = require('editOnCopy'); const onCut = require('editOnCut'); const onDragOver = require('editOnDragOver'); const onDragStart = require('editOnDragStart'); const onFocus = require('editOnFocus'); const onInput = require('editOnInput'); const onKeyDown = require('editOnKeyDown'); const onPaste = require('editOnPaste'); const onSelect = require('editOnSelect'); const DraftEditorEditHandler = { onBeforeInput, onBlur, onCompositionStart, onCopy, onCut, onDragOver, onDragStart, onFocus, onInput, onKeyDown, onPaste, onSelect, }; module.exports = DraftEditorEditHandler;
Fix(Svg): Revert SVG path to node style [#139510959] Signed-off-by: Tom Chen <9312ec496e168e4c213960a1ffbcd1eb1a0db9d1@pivotal.io>
import React from 'react'; const types = React.PropTypes; export class Svg extends React.Component { static propTypes = { src: types.string.isRequired } constructor(props, context) { super(props, context); this.state = {Component: null}; } componentDidMount() { const {src} = this.props; this.setState({Component: this.svgPathLoader(src)}); } svgPathLoader(src) { try { return require(`!!babel!svg-react!../../app/svg/${src}.svg`); } catch (e) { } } render() { const {src, ...props} = this.props; const {Component} = this.state; if (Component) return <Component {...props}/>; return <svg {...props}/>; } }
import React from 'react'; const types = React.PropTypes; export class Svg extends React.Component { static propTypes = { src: types.string.isRequired } constructor(props, context) { super(props, context); this.state = {Component: null}; } componentDidMount() { const {src} = this.props; this.setState({Component: this.svgPathLoader(src)}); } svgPathLoader(src) { try { return require(`!!babel-loader!svg-react-loader!../pui-css-iconography/svgs/${src}.svg`); } catch (e) { } } render() { const {src, ...props} = this.props; const {Component} = this.state; if (Component) return <Component {...props}/>; return <svg {...props}/>; } }
Use `with` syntax to open file
import base64, os def get_content(texts): if isinstance(texts, str) or isinstance(texts, unicode): file_path = texts with open(file_path, 'r') as f: return list(f.read().decode("utf-8")) f.close() else: return texts def write_file( path, data ): with open( path, "w" ) as f: f.write(data) f.close() def read_by_base64(path): with open(path, "r") as f: data = f.read() f.close() return base64.b64encode(data) def delete_file(path): os.remove(path) def delete_files(paths): for path in paths: delete_file(path)
import base64, os def get_content(texts): if isinstance(texts, str) or isinstance(texts, unicode): file_path = texts with open(file_path, 'r') as f: return list(f.read().decode("utf-8")) f.close() else: return texts def write_file( path, data ): with open( path, "w" ) as f: f.write(data) f.close() def read_by_base64(path): f = open(path, "r") data = f.read() f.close() return base64.b64encode(data) def delete_file(path): os.remove(path) def delete_files(paths): for path in paths: delete_file(path)
Modify listview styles for search listview and general margin
// @flow import { StyleSheet } from 'react-native' import { ApplicationStyles, Metrics, Colors } from '../../Themes/' export default StyleSheet.create({ ...ApplicationStyles.screen, container: { flex: 1, marginTop: Metrics.navBarHeight, backgroundColor: Colors.background }, row: { flex: 1, backgroundColor: Colors.fire, marginVertical: Metrics.smallMargin, justifyContent: 'center' }, boldLabel: { fontWeight: 'bold', alignSelf: 'center', color: Colors.snow, textAlign: 'center', marginVertical: Metrics.smallMargin }, label: { textAlign: 'center', color: Colors.snow, marginBottom: Metrics.smallMargin }, listContent: { marginTop: Metrics.baseMargin } })
// @flow import { StyleSheet } from 'react-native' import { ApplicationStyles, Metrics, Colors } from '../../Themes/' export default StyleSheet.create({ ...ApplicationStyles.screen, container: { flex: 1, marginTop: Metrics.navBarHeight, backgroundColor: Colors.background }, row: { flex: 1, backgroundColor: Colors.fire, marginVertical: Metrics.smallMargin, justifyContent: 'center' }, boldLabel: { fontWeight: 'bold', alignSelf: 'center', color: Colors.snow, textAlign: 'center', marginBottom: Metrics.smallMargin }, label: { textAlign: 'center', color: Colors.snow }, listContent: { marginTop: Metrics.baseMargin } })
Test modified to check for exception in lack of ffmpeg in travis
#ToDo : Write tests for application interface import pytest import os from PyQt4.QtGui import * from PyQt4.QtCore import * from mp3wav.application import Mp3WavApp from mp3wav.exceptions.fileexception import FileTypeException from mp3wav.exceptions.libraryexception import LibraryException from mp3wav.exceptions.filenotexistexception import FileNotExistException from mp3wav.exceptions.samefileexception import SameFileException from mp3wav.exceptions.overwriteexception import OverWriteException def windowTest(qtbot): testapp = Mp3WavApp() testapp.show() qtbot.addWidget(testapp) assert testapp.isVisible() assert testapp.close() def fileTypeTest(qtbot, tmpdir): testapp = Mp3WavApp() qtbot.addWidget(testapp) infile = tmpdir.mkdir("files").join("demo.mp3") infile.write("something") testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3"))) testapp.outputFileLine.setText(str(tmpdir.join('files'))) testapp.outputFileLineName.setText('demo.wave') with pytest.raises(FileTypeException): qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
#ToDo : Write tests for application interface import pytest import os from PyQt4.QtGui import * from PyQt4.QtCore import * from mp3wav.application import Mp3WavApp from mp3wav.exceptions.fileexception import FileTypeException from mp3wav.exceptions.libraryexception import LibraryException from mp3wav.exceptions.filenotexistexception import FileNotExistException from mp3wav.exceptions.samefileexception import SameFileException from mp3wav.exceptions.overwriteexception import OverWriteException def windowTest(qtbot): testapp = Mp3WavApp() testapp.show() qtbot.addWidget(testapp) assert testapp.isVisible() assert testapp.close() def correctConvertTest(qtbot, tmpdir): testapp = Mp3WavApp() qtbot.addWidget(testapp) infile = tmpdir.mkdir("files").join("demo.mp3") infile.write("something") testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3"))) testapp.outputFileLine.setText(str(tmpdir.join('files'))) testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav'))) qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton) assert os.path.exists(str(tmpdir.join('files', 'demo.wav')))
feat(redux-module-mercury): Set mercury to connected if already connected from instance
export const SET_CONNECTING = `mercury/SET_CONNECTING`; export const SET_CONNECTED = `mercury/SET_CONNECTED`; export function updateStatusConnecting(value) { return { type: SET_CONNECTING, payload: value }; } export function updateStatusConnected(value) { return { type: SET_CONNECTED, payload: value }; } export function connectToMercury(sparkInstance) { return (dispatch) => { if (sparkInstance) { const { canAuthorize, device, mercury } = sparkInstance; if (canAuthorize && device.registered && !mercury.connected && !mercury.connecting) { dispatch(updateStatusConnecting(true)); sparkInstance.mercury.connect().then(() => { sparkInstance.listenToAndRun(mercury, `change:connected`, () => { dispatch(updateStatusConnected(mercury.connected)); }); }); } // Handle if mercury is already connected from previous instance else if (mercury.connected) { dispatch(updateStatusConnected(mercury.connected)); } } }; }
export const SET_CONNECTING = `mercury/SET_CONNECTING`; export const SET_CONNECTED = `mercury/SET_CONNECTED`; export function updateStatusConnecting(value) { return { type: SET_CONNECTING, payload: value }; } export function updateStatusConnected(value) { return { type: SET_CONNECTED, payload: value }; } export function connectToMercury(sparkInstance) { return (dispatch) => { if (sparkInstance) { const { canAuthorize, device, mercury } = sparkInstance; if (canAuthorize && device.registered && !mercury.connected && !mercury.connecting) { dispatch(updateStatusConnecting(true)); sparkInstance.mercury.connect().then(() => { sparkInstance.listenToAndRun(mercury, `change:connected`, () => { dispatch(updateStatusConnected(mercury.connected)); }); }); } } }; }
Replace send_request and request methods with send_obj
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self.name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format.data_type self._handler = handler_class(self, **handler_options) self._connected = False def _assert_not_connected(self): assert not self._connected, 'transport connection already created' def _assert_connected(self): assert self._connected, 'transport connection has not created' def _encode_obj(self, obj): return self._data_format.encode(obj) def _decode_data(self, data): return self._data_format.decode(data) def _call_handler_method(self, name, *args): getattr(self._handler, name)(*args) def is_connected(self): return self._connected def connect(self, url, **options): raise NotImplementedError def send_obj(self, obj, receive_obj=True, **params): raise NotImplementedError def close(self): raise NotImplementedError def join(self, timeout=None): raise NotImplementedError
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self.name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format.data_type self._handler = handler_class(self, **handler_options) self._connected = False def _assert_not_connected(self): assert not self._connected, 'transport connection already created' def _assert_connected(self): assert self._connected, 'transport connection has not created' def _encode_obj(self, obj): return self._data_format.encode(obj) def _decode_data(self, data): return self._data_format.decode(data) def _call_handler_method(self, name, *args): getattr(self._handler, name)(*args) def is_connected(self): return self._connected def connect(self, url, **options): raise NotImplementedError def send_request(self, obj, **params): raise NotImplementedError def request(self, obj, **params): raise NotImplementedError def close(self): raise NotImplementedError def join(self, timeout=None): raise NotImplementedError
Add comments explaining why methods do nothing
#! usr/bin/env python3 from docopt import docopt from matplotlib import pyplot class Schema: """ Wraps the SQL source code for a schema and provides methods to get information about that schema. """ def __init__(self, source): """ Creates a new instance of Schema for the specified source code string. """ self.source = source def n_tables(self): """ Returns the number of tables defined in the schema """ pass #TODO: not yet implementend def n_keys(self): """ Returns the number of keys defined in the schema """ pass #TODO: not yet implementend def n_datatypes(self): """ Returns the number of each data type in the schema. """ pass #TODO: not yet implementend def lengths(self): """ Returns a dictionary mapping each data type in the schema to a list of the lengths of those data types. """ pass #TODO: not yet implementend
#! usr/bin/env python3 from docopt import docopt from matplotlib import pyplot class Schema: """ Wraps the SQL source code for a schema and provides methods to get information about that schema. """ def __init__(self, source): """ Creates a new instance of Schema for the specified source code string. """ self.source = source def n_tables(self): """ Returns the number of tables defined in the schema """ pass def n_keys(self): """ Returns the number of keys defined in the schema """ pass def n_datatypes(self): """ Returns the number of each data type in the schema. """ pass def lengths(self): """ Returns a dictionary mapping each data type in the schema to a list of the lengths of those data types. """ pass
[CS] Add missing space in email template.
var baseUrl = process.env.BASE_URI || "localdocker:4000"; module.exports = { approveFeed: function(message, recipient, group) { return "<p>" + message["user"]["userName"] + " has approved the feed for their " + message["election"].date.substring(0,10) + " " + message["election"].election_type + " election for publication. It was approved by " + message["user"]["userName"] + " (" + message["user"]["email"] + ").</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>"; }, processedFeed: function(message, recipient, group) { return "<p>" + recipient.givenName + ",</p>" + "<p>The data you provided for " + group.description + "'s election is available for you to review on the VIP Data Dashboard.</p>" + "<p>Please click the link below to review your feed.</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>" + "<p>If you have any questions, please contact <a href='mailto:vip@democracy.works'>vip@democracy.works</a>.</p>" + "<p>Thank you!</p>"; }, errorDuringProcessing: function(message) { return 'It looks like a feed failed during processing. Here\'s the information we got: \ \nMessage we got: ' + JSON.stringify(message); } }
var baseUrl = process.env.BASE_URI || "localdocker:4000"; module.exports = { approveFeed: function(message, recipient, group) { return "<p>" + message["user"]["userName"] + " has approved the feed for their " + message["election"].date.substring(0,10) + " " + message["election"].election_type + " election for publication. It was approved by" + message["user"]["userName"] + " (" + message["user"]["email"] + ").</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>"; }, processedFeed: function(message, recipient, group) { return "<p>" + recipient.givenName + ",</p>" + "<p>The data you provided for " + group.description + "'s election is available for you to review on the VIP Data Dashboard.</p>" + "<p>Please click the link below to review your feed.</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>" + "<p>If you have any questions, please contact <a href='mailto:vip@democracy.works'>vip@democracy.works</a>.</p>" + "<p>Thank you!</p>"; }, errorDuringProcessing: function(message) { return 'It looks like a feed failed during processing. Here\'s the information we got: \ \nMessage we got: ' + JSON.stringify(message); } }
Make find() less sensitive to the arguments
'use strict'; // iterates through array calling iterator on each element. // stops as soon as iterator return non-falsy value, and returns this value // module.exports.find = function find(arr, iter) { var i, l, result; // make sure arr is an array arr = arr || []; for (i = 0, l = arr.length; i < l && !result; i++) { result = iter(arr[i]); } return result; }; // returns object's keys sorted alphabeticaly in descending order // // getSortedKeys({ a: 1, cba: 2, ba: 3 }); // // -> [ 'cba', 'ba', 'a' ] // module.exports.getSortedKeys = function getSortedKeys(obj) { var keys = [], k; for (k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys.sort(function (a, b) { a = String(a).length; b = String(b).length; if (a === b) { return 0; } // longest strings comes first return (a > b) ? -1 : 1; }); };
'use strict'; // iterates through array calling iterator on each element. // stops as soon as iterator return non-falsy value, and returns this value // module.exports.find = function find(arr, iter) { var i, l, result; for (i = 0, l = arr.length; i < l && !result; i++) { result = iter(arr[i]); } return result; }; // returns object's keys sorted alphabeticaly in descending order // // getSortedKeys({ a: 1, cba: 2, ba: 3 }); // // -> [ 'cba', 'ba', 'a' ] // module.exports.getSortedKeys = function getSortedKeys(obj) { var keys = [], k; for (k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys.sort(function (a, b) { a = String(a).length; b = String(b).length; if (a === b) { return 0; } // longest strings comes first return (a > b) ? -1 : 1; }); };
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/')) # print dbs dblist = [] for db in dbs: dblist.append(db) print dblist # dbs = dbs.split('(')[0] # print dbs # dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check # # for db in dbs: # t1 = ibmcnx.functions.getDSId( db ) # AdminConfig.show( t1 ) # print '\n\n' # AdminConfig.showall( t1 ) # AdminConfig.showAttribute(t1,'statementCacheSize' ) # AdminConfig.showAttribute(t1,'[statementCacheSize]' )
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/')) print dbs dbs = dbs.split('(')[0] print dbs # dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check # # for db in dbs: # t1 = ibmcnx.functions.getDSId( db ) # AdminConfig.show( t1 ) # print '\n\n' # AdminConfig.showall( t1 ) # AdminConfig.showAttribute(t1,'statementCacheSize' ) # AdminConfig.showAttribute(t1,'[statementCacheSize]' )
Set new minimum pytz version
from setuptools import setup, find_packages import account setup( name="django-user-accounts", version=account.__version__, author="Brian Rosner", author_email="brosner@gmail.com", description="a Django user account app", long_description=open("README.rst").read(), license="MIT", url="http://github.com/pinax/django-user-accounts", packages=find_packages(), install_requires=[ "django-appconf>=0.6", "pytz>=2015.6" ], zip_safe=False, package_data={ "account": [ "locale/*/LC_MESSAGES/*", ], }, test_suite="runtests.runtests", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Framework :: Django", ] )
from setuptools import setup, find_packages import account setup( name="django-user-accounts", version=account.__version__, author="Brian Rosner", author_email="brosner@gmail.com", description="a Django user account app", long_description=open("README.rst").read(), license="MIT", url="http://github.com/pinax/django-user-accounts", packages=find_packages(), install_requires=[ "django-appconf>=0.6", "pytz>=2013.9" ], zip_safe=False, package_data={ "account": [ "locale/*/LC_MESSAGES/*", ], }, test_suite="runtests.runtests", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Framework :: Django", ] )
Fix deprecation warnings - RemovedInDjango19Warning Extend fix in review #9160 for subsequent changes. Change-Id: I25fbe759cfd28ac683ef94b58a8da098141e8d48
# Copyright (C) 2015 Linaro Limited # # Author: Stevan Radakovic <stevan.radakovic@linaro.org> # # This file is part of Lava Server. # # Lava Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License version 3 # as published by the Free Software Foundation # # Lava Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Lava Dashboard. If not, see <http://www.gnu.org/licenses/>. """ Administration interface of the LAVA Results application. """ from django import forms from django.contrib import admin from django.contrib.admin.actions import delete_selected from django.contrib.contenttypes import fields from django.utils.translation import ugettext_lazy as _ from lava_results_app.models import ( Query ) class QueryAdmin(admin.ModelAdmin): save_as = True admin.site.register(Query, QueryAdmin)
# Copyright (C) 2015 Linaro Limited # # Author: Stevan Radakovic <stevan.radakovic@linaro.org> # # This file is part of Lava Server. # # Lava Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License version 3 # as published by the Free Software Foundation # # Lava Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Lava Dashboard. If not, see <http://www.gnu.org/licenses/>. """ Administration interface of the LAVA Results application. """ from django import forms from django.contrib import admin from django.contrib.admin.actions import delete_selected from django.contrib.contenttypes import generic from django.utils.translation import ugettext_lazy as _ from lava_results_app.models import ( Query ) class QueryAdmin(admin.ModelAdmin): save_as = True admin.site.register(Query, QueryAdmin)
[WebProfilerBundle] Fix tests about web profiler icons
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\WebProfilerBundle\Tests\Resources; use PHPUnit\Framework\TestCase; class IconTest extends TestCase { /** * @dataProvider provideIconFilePaths */ public function testIconFileContents($iconFilePath) { $this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+"[^>]*+>.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath)); } public function provideIconFilePaths() { return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg')); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\WebProfilerBundle\Tests\Resources; use PHPUnit\Framework\TestCase; class IconTest extends TestCase { /** * @dataProvider provideIconFilePaths */ public function testIconFileContents($iconFilePath) { $this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+">.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath)); } public function provideIconFilePaths() { return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg')); } }
Refactor promises implementation to use ES2017 async/await syntax
const passport = require("passport"); const mongoose = require("mongoose"); const GoogleStrategy = require("passport-google-oauth20").Strategy; const keys = require("../config/keys"); const User = mongoose.model("users"); passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser((id, done) => { User.findById(id).then(user => { done(null, user); }); }); passport.use( new GoogleStrategy( { clientID: keys.googleClientID, clientSecret: keys.googleClientSecret, callbackURL: "/auth/google/callback" }, async (accessToken, refreshToken, profile, done) => { const existingUser = await User.findOne({ profileId: profile.id }); if (existingUser) { console.log("user already exists"); done(null, existingUser); } else { console.log("saving new user with profileId: ", profile.id); const user = await new User({ profileId: profile.id }).save(); done(null, user); } } ) );
const passport = require("passport"); const mongoose = require("mongoose"); const GoogleStrategy = require("passport-google-oauth20").Strategy; const keys = require("../config/keys"); const User = mongoose.model("users"); passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser((id, done) => { User.findById(id).then(user => { done(null, user); }); }); passport.use( new GoogleStrategy( { clientID: keys.googleClientID, clientSecret: keys.googleClientSecret, callbackURL: "/auth/google/callback" }, (accessToken, refreshToken, profile, done) => { User.findOne({ profileId: profile.id }).then(existingUser => { if (existingUser) { console.log("user already exists"); done(null, existingUser); } else { console.log("saving new user with profileId: ", profile.id); new User({ profileId: profile.id }).save().then(user => { done(null, user); }); } }); } ) );
Add additional log message to Player setState
package com.pm.server.player; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import com.pm.server.datatype.Coordinate; import com.pm.server.datatype.PlayerState; import com.pm.server.utils.JsonUtils; @Component public abstract class PlayerImpl implements Player { protected Integer id = 0; protected Coordinate location; protected PlayerState state = PlayerState.UNINITIALIZED; private final static Logger log = LogManager.getLogger(PlayerImpl.class.getName()); public void setId(Integer id) { log.trace("Setting id to {}", id); this.id = id; } public int getId() { return id; } public void setLocation(Coordinate location) { String locationString = JsonUtils.objectToJson(location); if(locationString != null) { log.trace("Setting location to {}", locationString); } this.location = location; } public Coordinate getLocation() { return location; } public void setState(PlayerState state) throws NullPointerException { if(state == null) { String errorMessage = "setState() was given a null state."; log.warn(errorMessage); throw new NullPointerException(errorMessage); } log.trace("Setting location to {}", state); this.state = state; } public PlayerState getState() { return state; } }
package com.pm.server.player; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import com.pm.server.datatype.Coordinate; import com.pm.server.datatype.PlayerState; import com.pm.server.utils.JsonUtils; @Component public abstract class PlayerImpl implements Player { protected Integer id = 0; protected Coordinate location; protected PlayerState state = PlayerState.UNINITIALIZED; private final static Logger log = LogManager.getLogger(PlayerImpl.class.getName()); public void setId(Integer id) { log.trace("Setting id to {}", id); this.id = id; } public int getId() { return id; } public void setLocation(Coordinate location) { String locationString = JsonUtils.objectToJson(location); if(locationString != null) { log.trace("Setting location to {}", locationString); } this.location = location; } public Coordinate getLocation() { return location; } public void setState(PlayerState state) throws NullPointerException { if(state == null) { String errorMessage = "setState() was given a null state."; log.warn(errorMessage); throw new NullPointerException(errorMessage); } this.state = state; } public PlayerState getState() { return state; } }
Add ENABLE_VARNISH setting to travis settings
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None TEST_DB_NAME = DB_NAME = 'osf_test' VARNISH_SERVERS = ['http://localhost:8080'] ENABLE_VARNISH = True
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None TEST_DB_NAME = DB_NAME = 'osf_test' VARNISH_SERVERS = ['http://localhost:8080']
[Φ] Add Tensor to standard imports
# pylint: disable-msg = unused-import """ *Main PhiFlow import:* `from phi.flow import *` Imports important functions and classes from `math`, `geom`, `field`, `physics` and `vis` (including sub-modules) as well as the modules and sub-modules themselves. See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`. """ # Modules import numpy import numpy as np import phi from . import math, geom, field, physics, vis from .math import extrapolation, backend from .physics import fluid, flip, advect, diffuse # Classes from .math import Tensor, DType, Solve from .geom import Geometry, Sphere, Box, Cuboid from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene from .vis import view, Viewer, control from .physics._boundaries import Obstacle # Constants from .math import PI, INF, NAN # Functions from .math import wrap, tensor, spatial, channel, batch, instance from .geom import union from .vis import show # Exceptions from .math import ConvergenceException, NotConverged, Diverged
# pylint: disable-msg = unused-import """ *Main PhiFlow import:* `from phi.flow import *` Imports important functions and classes from `math`, `geom`, `field`, `physics` and `vis` (including sub-modules) as well as the modules and sub-modules themselves. See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`. """ # Modules import numpy import numpy as np import phi from . import math, geom, field, physics, vis from .math import extrapolation, backend from .physics import fluid, flip, advect, diffuse # Classes from .math import DType, Solve from .geom import Geometry, Sphere, Box, Cuboid from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene from .vis import view, Viewer, control from .physics._boundaries import Obstacle # Constants from .math import PI, INF, NAN # Functions from .math import wrap, tensor, spatial, channel, batch, instance from .geom import union from .vis import show # Exceptions from .math import ConvergenceException, NotConverged, Diverged
Fix maybe_sv, 0 is a valid digit
#!/usr/bin/env node 'use strict'; var sv2bts = require('./').sv2bts; var bts2sv = require('./').bts2sv; var n2sv = require('./').n2sv; var sv2n = require('./').sv2n; var bts2n = require('balanced-ternary').bts2n; var n2bts = require('balanced-ternary').n2bts; function maybe_sv(s) { return !!s.match(/^[0A-Z]+$/); } function maybe_bts(s) { return !!s.match(/^[0i1]+$/); } function maybe_n(s) { return !!s.match(/^[-+]?[0-9]+$/); } process.argv.slice(2).forEach(function(arg) { // bts -> n -> sv if (maybe_sv(arg)) { console.log(sv2bts(arg)+' = '+n2sv(arg)+' = '+arg); } if (maybe_n(arg)) { console.log(n2bts(arg)+' = '+arg+' = '+n2sv(arg)); } if (maybe_bts(arg)) { console.log(arg+' = '+bts2n(arg)+' = '+bts2sv(arg)); } });
#!/usr/bin/env node 'use strict'; var sv2bts = require('./').sv2bts; var bts2sv = require('./').bts2sv; var n2sv = require('./').n2sv; var sv2n = require('./').sv2n; var bts2n = require('balanced-ternary').bts2n; var n2bts = require('balanced-ternary').n2bts; function maybe_sv(s) { return !!s.match(/^[A-Z]+$/); } function maybe_bts(s) { return !!s.match(/^[0i1]+$/); } function maybe_n(s) { return !!s.match(/^[-+]?[0-9]+$/); } process.argv.slice(2).forEach(function(arg) { // bts -> n -> sv if (maybe_sv(arg)) { console.log(sv2bts(arg)+' = '+n2sv(arg)+' = '+arg); } if (maybe_n(arg)) { console.log(n2bts(arg)+' = '+arg+' = '+n2sv(arg)); } if (maybe_bts(arg)) { console.log(arg+' = '+bts2n(arg)+' = '+bts2sv(arg)); } });
Fix issue with uninitialised response
import collections import click def admin_command(fn): fn.__doc__ += ' [Admin only]' return fn class PyutrackContext(object): def __init__(self, connection, config, debug=False): self.connection = connection self.config = config self.debug = debug self.format = None def render(self, data, format=None): format = self.format or format oneline = format == 'oneline' line_sep = '\n' if format else '\n\n' resp = '' if isinstance(data, six.string_types): resp = data elif isinstance(data, collections.Iterable): resp = line_sep.join( k.format(format, oneline=oneline) for k in data ) if len(data) > 0 else click.style( 'No results', fg='yellow' ) elif data: resp = data.format(format, oneline=oneline) click.echo(resp)
import collections import click def admin_command(fn): fn.__doc__ += ' [Admin only]' return fn class PyutrackContext(object): def __init__(self, connection, config, debug=False): self.connection = connection self.config = config self.debug = debug self.format = None def render(self, data, format=None): format = self.format or format oneline = format == 'oneline' line_sep = '\n' if format else '\n\n' if isinstance(data, collections.Iterable): resp = line_sep.join( k.format(format, oneline=oneline) for k in data ) if len(data) > 0 else click.style( 'No results', fg='yellow' ) elif data: resp = data.format(format, oneline=oneline) click.echo(resp)
Introduce better error reporting for getter errors
'use strict'; var resolve = require('esniff/accessed-properties')('this') , memoize = require('memoizee/plain') , ignored = require('./meta-property-names') , re = new RegExp('^\\s*function\\s*(?:[\\0-\'\\)-\\uffff]+)*\\s*\\(\\s*' + '(_observe)?[\\/*\\s]*\\)\\s*\\{([\\0-\\uffff]*)\\}\\s*$') , isFn = RegExp.prototype.test.bind(/^\s*\(/); module.exports = memoize(function (fn) { var body = String(fn).match(re)[2], shift = 0; resolve(body).forEach(function (data) { var name = data.name, start; if (name[0] === '_') return; if (ignored[name]) return; if (isFn(body.slice(data.end + shift))) return; start = data.start - 5 + shift; body = body.slice(0, start) + '_observe(this._get(\'' + name + '\'))' + body.slice(data.end + shift); shift += 18; }); if (!shift) return fn; body = 'try {\n' + body + '\n;} catch (e) { throw new Error("Dbjs getter error:\\n\\n" + e.stack + ' + '"\\n\\nGetter Body:\\n' + JSON.stringify(body).slice(1) + '); }'; return new Function('_observe', body); });
'use strict'; var resolve = require('esniff/accessed-properties')('this') , memoize = require('memoizee/plain') , ignored = require('./meta-property-names') , re = new RegExp('^\\s*function\\s*(?:[\\0-\'\\)-\\uffff]+)*\\s*\\(\\s*' + '(_observe)?[\\/*\\s]*\\)\\s*\\{([\\0-\\uffff]*)\\}\\s*$') , isFn = RegExp.prototype.test.bind(/^\s*\(/); module.exports = memoize(function (fn) { var body = String(fn).match(re)[2], shift = 0; resolve(body).forEach(function (data) { var name = data.name, start; if (name[0] === '_') return; if (ignored[name]) return; if (isFn(body.slice(data.end + shift))) return; start = data.start - 5 + shift; body = body.slice(0, start) + '_observe(this._get(\'' + name + '\'))' + body.slice(data.end + shift); shift += 18; }); if (!shift) return fn; return new Function('_observe', body); });
Reduce amounts of runs for fast test analysis
import unittest try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_hymod_python import spot_setup class TestFast(unittest.TestCase): def setUp(self): self.spot_setup = spot_setup() self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod self.timeout = 10 # Given in Seconds def test_fast(self): sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram", sim_timeout=self.timeout) results = [] sampler.sample(self.rep) results = sampler.getdata() self.assertEqual(200,len(results)) if __name__ == '__main__': unittest.main()
import unittest try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_hymod_python import spot_setup class TestFast(unittest.TestCase): def setUp(self): self.spot_setup = spot_setup() self.rep = 800 # REP must be a multiply of amount of parameters which are in 7 if using hymod self.timeout = 10 # Given in Seconds def test_fast(self): sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram", sim_timeout=self.timeout) results = [] sampler.sample(self.rep) results = sampler.getdata() self.assertEqual(800,len(results)) if __name__ == '__main__': unittest.main()
Check to see if recurrence type path provided exists as a class.
<?php namespace Plummer\Calendarful\Recurrence; class RecurrenceFactory implements RecurrenceFactoryInterface { protected $recurrenceTypes = []; public function addRecurrenceType($type, $recurrenceType) { if(is_string($recurrenceType) and !class_exists($recurrenceType)) { throw new \InvalidArgumentException("Class {$recurrenceType} des not exist."); } else if(!in_array('Plummer\Calendarful\Recurrence\RecurrenceInterface', class_implements($recurrenceType))) { throw new \InvalidArgumentException('File or File path required.'); } $this->recurrenceTypes[$type] = is_string($recurrenceType) ? $recurrenceType : get_class($recurrenceType); } public function getRecurrenceTypes() { return $this->recurrenceTypes; } public function createRecurrenceType($type) { if(!isset($this->recurrenceTypes[$type])) { throw new \Exception('The type passed does not exist.'); } return $this->recurrenceTypes[$type]; } }
<?php namespace Plummer\Calendarful\Recurrence; class RecurrenceFactory implements RecurrenceFactoryInterface { protected $recurrenceTypes = []; public function addRecurrenceType($type, $recurrenceType) { if(!in_array('Plummer\Calendarful\Recurrence\RecurrenceInterface', class_implements($recurrenceType))) { throw new \InvalidArgumentException('File or File path required.'); } $this->recurrenceTypes[$type] = is_string($recurrenceType) ? $recurrenceType : get_class($recurrenceType); } public function getRecurrenceTypes() { return $this->recurrenceTypes; } public function createRecurrenceType($type) { if(!isset($this->recurrenceTypes[$type])) { throw new \Exception('The type passed does not exist.'); } return $this->recurrenceTypes[$type]; } }
Update random forest face example to use several cores
""" ======================================= Pixel importances with forests of trees ======================================= This example shows the use of forests of trees to evaluate the importance of the pixels in an image classification task (faces). The hotter the pixel, the more important. """ print __doc__ from time import time import pylab as pl from sklearn.datasets import fetch_olivetti_faces from sklearn.ensemble import ExtraTreesClassifier # Number of cores to use to perform parallel fitting of the forest model n_jobs=2 # Loading the digits dataset data = fetch_olivetti_faces() X = data.images.reshape((len(data.images), -1)) y = data.target mask = y < 5 # Limit to 5 classes X = X[mask] y = y[mask] # Build a forest and compute the pixel importances print "Fitting ExtraTreesClassifier on faces data with %d cores..." % n_jobs t0 = time() forest = ExtraTreesClassifier(n_estimators=1000, max_features=128, compute_importances=True, random_state=0, n_jobs=n_jobs) forest.fit(X, y) print "done in %0.3fs" % (time() - t0) importances = forest.feature_importances_ importances = importances.reshape(data.images[0].shape) # Plot pixel importances pl.matshow(importances, cmap=pl.cm.hot) pl.title("Pixel importances with forests of trees") pl.show()
""" ======================================= Pixel importances with forests of trees ======================================= This example shows the use of forests of trees to evaluate the importance of the pixels in an image classification task (faces). The hotter the pixel, the more important. """ print __doc__ import pylab as pl from sklearn.datasets import fetch_olivetti_faces from sklearn.ensemble import ExtraTreesClassifier # Loading the digits dataset data = fetch_olivetti_faces() X = data.images.reshape((len(data.images), -1)) y = data.target mask = y < 5 # Limit to 5 classes X = X[mask] y = y[mask] # Build a forest and compute the pixel importances forest = ExtraTreesClassifier(n_estimators=1000, max_features=128, compute_importances=True, random_state=0) forest.fit(X, y) importances = forest.feature_importances_ importances = importances.reshape(data.images[0].shape) # Plot pixel importances pl.matshow(importances, cmap=pl.cm.hot) pl.title("Pixel importances with forests of trees") pl.show()
Add square generator to prototypes array.
package framework.generators; /** * Abstract class to represent a wave generator. */ public abstract class Generator { /** * Generates the signal with the given frequency and duration. * @param f the frequency of the sample in hertzs * @param d the duration of the sample in seconds * @param a the amplitude of the sample * @return the generated sample as an array of Doubles */ public abstract Double[] generate(Double f, Double d, Double a); /** * Get the prototypes of the generators. * @return an array containing prototypes */ public static Generator[] getPrototypes() { Generator[] prototypes = new Generator[2]; prototypes[0] = new SineGenerator(); prototypes[1] = new SquareGenerator(); return prototypes; } public abstract String toString(); // Constants public static final int SAMPLE_RATE = 44100; // CD quality audio }
package framework.generators; /** * Abstract class to represent a wave generator. */ public abstract class Generator { /** * Generates the signal with the given frequency and duration. * @param f the frequency of the sample in hertzs * @param d the duration of the sample in seconds * @param a the amplitude of the sample * @return the generated sample as an array of Doubles */ public abstract Double[] generate(Double f, Double d, Double a); /** * Get the prototypes of the generators. * @return an array containing prototypes */ public static Generator[] getPrototypes() { Generator[] prototypes = new Generator[1]; prototypes[0] = new SineGenerator(); return prototypes; } public abstract String toString(); // Constants public static final int SAMPLE_RATE = 44100; // CD quality audio }
Clarify httpResponse check with ===
"use strict"; const Item = require('./item'); const Handler = require('./handler'); const Plugin = require('../plugin'); const url = require('url'); const {coroutine: co} = require('bluebird'); class Router extends Plugin { constructor(engine) { super(engine); engine.registry.http.incoming.set({id: 'http', incoming: (...args) => this.incoming(...args)}); this.router = new Item(); return this; } incoming(context) { // TODO: Proper favicon.ico handling. if (context.request.url == '/favicon.ico') {return Promise.resolve();} let handlers = Item.sortHandlers(this.router.collectHandlers(context.request._parsedUrl.pathname)); return co(function*() { for (let key in handlers) { if (context.httpResponse === undefined) { context.handler = handlers[key]; yield (new context.handler()).init(context); } } })(); } } module.exports = Router;
"use strict"; const Item = require('./item'); const Handler = require('./handler'); const Plugin = require('../plugin'); const url = require('url'); const {coroutine: co} = require('bluebird'); class Router extends Plugin { constructor(engine) { super(engine); engine.registry.http.incoming.set({id: 'http', incoming: (...args) => this.incoming(...args)}); this.router = new Item(); return this; } incoming(context) { // TODO: Proper favicon.ico handling. if (context.request.url == '/favicon.ico') {return Promise.resolve();} let handlers = Item.sortHandlers(this.router.collectHandlers(context.request._parsedUrl.pathname)); return co(function*() { for (let key in handlers) { if (context.httpResponse == undefined) { context.handler = handlers[key]; yield (new context.handler()).init(context); } } })(); } } module.exports = Router;
Add option to enable loose mode
const {BABEL_ENV, NODE_ENV} = process.env const defaultOptions = { lodash: true, loose: false, modules: BABEL_ENV === 'cjs' || NODE_ENV === 'test' ? 'commonjs' : false, targets: { browsers: ['IE 11', 'last 2 Edge versions', 'Firefox >= 45', 'last 2 Chrome versions'], node: 8, }, } module.exports = (context, userOptions) => { const {lodash, loose, modules, targets} = Object.assign({}, defaultOptions, userOptions) const plugins = [require('babel-plugin-react-require').default] if (lodash) plugins.push(require('babel-plugin-lodash')) const presets = [ [require('@babel/preset-env'), {loose, modules, targets}], [require('@babel/preset-stage-1'), {loose, useBuiltIns: true}], [require('@babel/preset-react'), {useBuiltIns: true}], ] return {plugins, presets} }
const {BABEL_ENV, NODE_ENV} = process.env const defaultOptions = { lodash: true, modules: BABEL_ENV === 'cjs' || NODE_ENV === 'test' ? 'commonjs' : false, targets: { browsers: ['IE 11', 'last 2 Edge versions', 'Firefox >= 45', 'last 2 Chrome versions'], node: 8, }, } module.exports = (context, userOptions) => { const options = Object.assign({}, defaultOptions, userOptions) const plugins = [ // ensure that React is imported if JSX is used require('babel-plugin-react-require').default, ] if (options.lodash) plugins.push(require('babel-plugin-lodash')) const presets = [ [require('@babel/preset-env'), {modules: options.modules, targets: options.targets}], [require('@babel/preset-stage-1'), {useBuiltIns: true}], [require('@babel/preset-react'), {useBuiltIns: true}], ] return {plugins, presets} }
Update Express config environmental file name
/** * Copyright 2014 IBM Corp. 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. */ 'use strict'; var express = require('express'), app = express(), bluemix = require('./config/bluemix'), watson = require('watson-developer-cloud'), // environmental variable points to demo's json config file config = require(process.env.WATSON_CONFIG_FILE), extend = require('util')._extend; // if bluemix credentials exists, then override local var credentials = extend(config, bluemix.getServiceCreds('text_to_speech')); // Create the service wrapper var textToSpeech = new watson.text_to_speech(config); // Configure express require('./config/express')(app, textToSpeech); var port = process.env.VCAP_APP_PORT || 3000; app.listen(port); console.log('listening at:', port);
/** * Copyright 2014 IBM Corp. 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. */ 'use strict'; var express = require('express'), app = express(), bluemix = require('./config/bluemix'), watson = require('watson-developer-cloud'), // environmental variable points to demo's json config file config = require(process.env.WATSON_OPTIONS_FILE), extend = require('util')._extend; // if bluemix credentials exists, then override local var credentials = extend(config, bluemix.getServiceCreds('text_to_speech')); // Create the service wrapper var textToSpeech = new watson.text_to_speech(credentials); // Configure express require('./config/express')(app, textToSpeech); var port = process.env.VCAP_APP_PORT || 3000; app.listen(port); console.log('listening at:', port);
Change version number to 0.1 ...in preparation for the upcoming release.
# Copyright 2013-2014 Massachusetts Open Cloud Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS # IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language # governing permissions and limitations under the License. from setuptools import setup, find_packages from pip.req import parse_requirements requirements = [str(r.req) for r in parse_requirements('requirements.txt')] setup(name='moc-rest', version='0.1', url='https://github.com/CCI-MOC/moc-rest', packages=find_packages(), install_requires=requirements, )
# Copyright 2013-2014 Massachusetts Open Cloud Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS # IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language # governing permissions and limitations under the License. from setuptools import setup, find_packages from pip.req import parse_requirements requirements = [str(r.req) for r in parse_requirements('requirements.txt')] setup(name='moc-rest', version='1.0', url='https://github.com/CCI-MOC/moc-rest', packages=find_packages(), install_requires=requirements, )
Change exception name to CosmicRayTestingException
import ast import builtins from .operator import Operator class CosmicRayTestingException(Exception): pass setattr(builtins, CosmicRayTestingException.__name__, CosmicRayTestingException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = CosmicRayTestingException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
import ast import builtins from .operator import Operator class OutOfNoWhereException(Exception): pass setattr(builtins, OutOfNoWhereException.__name__, OutOfNoWhereException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = OutOfNoWhereException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
Put all the Accessibility property tests in a single function We already had machinery for that, anyway.
# Pytest will pick up this module automatically when running just "pytest". # # Each test_*() function gets passed test fixtures, which are defined # in conftest.py. So, a function "def test_foo(bar)" will get a bar() # fixture created for it. PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry_root, session_manager): values = [ ('Name', 'main'), ('Description', ''), ('Parent', ('', '/org/a11y/atspi/null')), ('ChildCount', 0), ] for prop_name, expected in values: assert get_property(registry_root, ACCESSIBLE_IFACE, prop_name) == expected
# Pytest will pick up this module automatically when running just "pytest". # # Each test_*() function gets passed test fixtures, which are defined # in conftest.py. So, a function "def test_foo(bar)" will get a bar() # fixture created for it. PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry_root, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry_root, ACCESSIBLE_IFACE, prop_name) == expected def test_registry_root_has_null_parent(registry_root, session_manager): assert get_property(registry_root, ACCESSIBLE_IFACE, 'Parent') == ('', '/org/a11y/atspi/null') def test_empty_registry_has_zero_children(registry_root, session_manager): assert get_property(registry_root, ACCESSIBLE_IFACE, 'ChildCount') == 0
Convert liefeeds to Unix style
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Enable/Disable Migrations |-------------------------------------------------------------------------- | | Migrations are disabled by default but should be enabled | whenever you intend to do a schema migration. | */ $config['migration_enabled'] = FALSE; /* |-------------------------------------------------------------------------- | Migrations version |-------------------------------------------------------------------------- | | This is used to set migration version that the file system should be on. | If you run $this->migration->latest() this is the version that schema will | be upgraded / downgraded to. | */ $config['migration_version'] = 0; /* |-------------------------------------------------------------------------- | Migrations Path |-------------------------------------------------------------------------- | | Path to your migrations folder. | Typically, it will be within your application path. | Also, writing permission is required within the migrations path. | */ $config['migration_path'] = APPPATH . 'migrations/'; /* End of file migration.php */ /* Location: ./application/config/migration.php */
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Enable/Disable Migrations |-------------------------------------------------------------------------- | | Migrations are disabled by default but should be enabled | whenever you intend to do a schema migration. | */ $config['migration_enabled'] = FALSE; /* |-------------------------------------------------------------------------- | Migrations version |-------------------------------------------------------------------------- | | This is used to set migration version that the file system should be on. | If you run $this->migration->latest() this is the version that schema will | be upgraded / downgraded to. | */ $config['migration_version'] = 0; /* |-------------------------------------------------------------------------- | Migrations Path |-------------------------------------------------------------------------- | | Path to your migrations folder. | Typically, it will be within your application path. | Also, writing permission is required within the migrations path. | */ $config['migration_path'] = APPPATH . 'migrations/'; /* End of file migration.php */ /* Location: ./application/config/migration.php */
Fix for if token is valid format, but user with that token does not exist
from rest_framework.authentication import BaseAuthentication from models import Token from seahub.base.accounts import User class TokenAuthentication(BaseAuthentication): """ Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ model = Token """ A custom token model may be used, but must have the following properties. * key -- The string identifying the token * user -- The user to which the token belongs """ def authenticate(self, request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2 and auth[0].lower() == "token": key = auth[1] try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: return None try: user = User.objects.get(email=token.user) except User.DoesNotExist: return None if user.is_active: return (user, token)
from rest_framework.authentication import BaseAuthentication from models import Token from seahub.base.accounts import User class TokenAuthentication(BaseAuthentication): """ Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ model = Token """ A custom token model may be used, but must have the following properties. * key -- The string identifying the token * user -- The user to which the token belongs """ def authenticate(self, request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2 and auth[0].lower() == "token": key = auth[1] try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: return None user = User.objects.get(email=token.user) if user.is_active: return (user, token)
Fix mock to update both cursor and selection
import { Point } from "../lib/point.js"; import { ITextEditor } from "../lib/text-editor.js"; // This is a mock class of the ITextEditor interface export class TextEditor extends ITextEditor { constructor(lines) { super(); this._lines = lines.slice(); this._cursorPos = new Point(0, 0); this._selectionRange = null; } getCursorPosition() { return this._cursorPos; } setCursorPosition(pos) { this._cursorPos = pos; this._selectionRange = null; } getSelectionRange() { return this._selectionRange; } setSelectionRange(range) { this._cursorPos = range.end; this._selectionRange = range; } getLastRow() { return this._lines.length - 1; } getLine(row) { return this._lines[row]; } getLines() { return this._lines.slice(); } insertLine(row, line) { this._lines.splice(row, 0, line); } deleteLine(row) { this._lines.splice(row, 1); } replaceLines(startRow, endRow, lines) { this._lines.splice(startRow, endRow - startRow, ...lines); } transact(func) { func(); } }
import { Point } from "../lib/point.js"; import { ITextEditor } from "../lib/text-editor.js"; // This is a mock class of the ITextEditor interface export class TextEditor extends ITextEditor { constructor(lines) { super(); this._lines = lines.slice(); this._cursorPos = new Point(0, 0); this._selectionRange = null; } getCursorPosition() { return this._cursorPos; } setCursorPosition(pos) { this._cursorPos = pos; } getSelectionRange() { return this._selectionRange; } setSelectionRange(range) { this._selectionRange = range; } getLastRow() { return this._lines.length - 1; } getLine(row) { return this._lines[row]; } getLines() { return this._lines.slice(); } insertLine(row, line) { this._lines.splice(row, 0, line); } deleteLine(row) { this._lines.splice(row, 1); } replaceLines(startRow, endRow, lines) { this._lines.splice(startRow, endRow - startRow, ...lines); } transact(func) { func(); } }
Make sure _set_lxd_dir_env is always called in monitor loop Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
import asyncio from juju.utils import run_with_interrupt from conjureup import events from conjureup.models.provider import LocalhostError, LocalhostJSONError class BaseCloudController: cancel_monitor = asyncio.Event() async def _monitor_localhost(self, provider, cb): """ Checks that localhost/lxd is available and listening, updates widget accordingly """ while not self.cancel_monitor.is_set(): try: provider._set_lxd_dir_env() compatible = await provider.is_server_compatible() if compatible: events.LXDAvailable.set() self.cancel_monitor.set() cb() return except (LocalhostError, LocalhostJSONError, FileNotFoundError): pass await run_with_interrupt(asyncio.sleep(2), self.cancel_monitor)
import asyncio from juju.utils import run_with_interrupt from conjureup import events from conjureup.models.provider import LocalhostError, LocalhostJSONError class BaseCloudController: cancel_monitor = asyncio.Event() async def _monitor_localhost(self, provider, cb): """ Checks that localhost/lxd is available and listening, updates widget accordingly """ while not self.cancel_monitor.is_set(): try: compatible = await provider.is_server_compatible() if compatible: events.LXDAvailable.set() self.cancel_monitor.set() cb() return except (LocalhostError, LocalhostJSONError): provider._set_lxd_dir_env() except FileNotFoundError: pass await run_with_interrupt(asyncio.sleep(2), self.cancel_monitor)
Fix accidental oauth/v1 route rename in bitbucket test
package server_test import ( "github.com/concourse/skymarshal/bitbucket/server" "github.com/concourse/skymarshal/provider" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Bitbucket Server Provider", func() { Describe("AuthMethod", func() { var ( authMethod provider.AuthMethod authConfig *server.AuthConfig ) BeforeEach(func() { authConfig = &server.AuthConfig{} authMethod = authConfig.AuthMethod("http://bum-bum-bum.com", "dudududum") }) It("creates a path for route", func() { Expect(authMethod).To(Equal(provider.AuthMethod{ Type: provider.AuthTypeOAuth, DisplayName: "Bitbucket Server", AuthURL: "http://bum-bum-bum.com/oauth/v1/bitbucket-server?team_name=dudududum", })) }) }) })
package server_test import ( "github.com/concourse/skymarshal/bitbucket/server" "github.com/concourse/skymarshal/provider" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Bitbucket Server Provider", func() { Describe("AuthMethod", func() { var ( authMethod provider.AuthMethod authConfig *server.AuthConfig ) BeforeEach(func() { authConfig = &server.AuthConfig{} authMethod = authConfig.AuthMethod("http://bum-bum-bum.com", "dudududum") }) It("creates a path for route", func() { Expect(authMethod).To(Equal(provider.AuthMethod{ Type: provider.AuthTypeOAuth, DisplayName: "Bitbucket Server", AuthURL: "http://bum-bum-bum.com/auth/v1/bitbucket-server?team_name=dudududum", })) }) }) })