text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix where clause in getPublishedPost
<?php namespace SymfonyDay\Bundle\BlogBundle\Entity; use Doctrine\ORM\EntityRepository; /** * PostRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class PostRepository extends EntityRepository { public function getPublishedPost($id) { return $this ->createQueryBuilder('p') ->where('p.id = :id') ->andWhere('p.publishedAt IS NULL OR p.publishedAt <= :date') ->setParameter('id', $id) ->setParameter('date', date('Y-m-d H:i')) ->getQuery() ->getSingleResult() ; } public function getMostRecentPosts() { return $this ->createQueryBuilder('p') ->where('p.publishedAt IS NULL') ->orWhere('p.publishedAt <= :date') ->orderBy('p.publishedAt', 'DESC') ->setParameter('date', date('Y-m-d H:i')) ->getQuery() ->execute() ; } }
<?php namespace SymfonyDay\Bundle\BlogBundle\Entity; use Doctrine\ORM\EntityRepository; /** * PostRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class PostRepository extends EntityRepository { public function getPublishedPost($id) { return $this ->createQueryBuilder('p') ->where('p.id = :id') ->andWhere('p.publishedAt IS NULL') ->orWhere('p.publishedAt <= :date') ->setParameter('id', $id) ->setParameter('date', date('Y-m-d H:i')) ->getQuery() ->getSingleResult() ; } public function getMostRecentPosts() { return $this ->createQueryBuilder('p') ->where('p.publishedAt IS NULL') ->orWhere('p.publishedAt <= :date') ->orderBy('p.publishedAt', 'DESC') ->setParameter('date', date('Y-m-d H:i')) ->getQuery() ->execute() ; } }
Raise the number of iterations in empty session benchmarks
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.benchmarks.session; import java.util.concurrent.TimeUnit; import org.drools.benchmarks.common.AbstractBenchmark; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.Warmup; @Warmup(iterations = 200000) @Measurement(iterations = 100000) @OutputTimeUnit(TimeUnit.MICROSECONDS) public abstract class AbstractEmptySessionBenchmark extends AbstractBenchmark { @Setup @Override public void setup() { createEmptyKieBase(); } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.benchmarks.session; import java.util.concurrent.TimeUnit; import org.drools.benchmarks.common.AbstractBenchmark; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.Warmup; @Warmup(iterations = 4000) @Measurement(iterations = 2000) @OutputTimeUnit(TimeUnit.MICROSECONDS) public abstract class AbstractEmptySessionBenchmark extends AbstractBenchmark { @Setup @Override public void setup() { createEmptyKieBase(); } }
Delete an empty line again...
'use strict'; /* Configurable navbar * * The following variables can be declared in a conf file * disable - Boolean * search - Boolean * navigation - Boolean * notifier - Boolean * template - String * * Example; * * { * "navbar" : { * "search" : true, * "navigation" : true, * "template" : "templates/navbar.html" * } * */ angular.module('arethusa.core').directive('arethusaNavbar', [ 'configurator', function (configurator) { return { restrict: 'AE', scope: true, link: function (scope, element, attrs) { var conf = configurator.configurationFor('navbar'); scope.template = conf.template; scope.disable = conf.disable; scope.showSearch = function () { return conf.search; }; scope.showNavigation = function () { return conf.navigation; }; scope.showNotifier = function () { return conf.notifier; }; }, template: '<div ng-if="! disable" ng-include="template"></div>' }; } ]);
'use strict'; /* Configurable navbar * * The following variables can be declared in a conf file * disable - Boolean * search - Boolean * navigation - Boolean * notifier - Boolean * template - String * * Example; * * { * "navbar" : { * "search" : true, * "navigation" : true, * "template" : "templates/navbar.html" * } * */ angular.module('arethusa.core').directive('arethusaNavbar', [ 'configurator', function (configurator) { return { restrict: 'AE', scope: true, link: function (scope, element, attrs) { var conf = configurator.configurationFor('navbar'); scope.template = conf.template; scope.disable = conf.disable; scope.showSearch = function () { return conf.search; }; scope.showNavigation = function () { return conf.navigation; }; scope.showNotifier = function () { return conf.notifier; }; }, template: '<div ng-if="! disable" ng-include="template"></div>' }; } ]);
Rename "escapeRow" method to just "escape"
<?php declare(strict_types=1); namespace Rinvex\Support\Traits; trait Escaper { /** * Escape all values. * * @param array $data * * @return array */ protected function escape(array $data): array { $arrayDot = array_filter(array_dot($data)); foreach ($arrayDot as $key => $value) { $arrayDot[$key] = e($value); } foreach ($arrayDot as $key => $value) { array_set($data, $key, $value); } return $data; } }
<?php declare(strict_types=1); namespace Rinvex\Support\Traits; trait Escaper { /** * Escape all values of row. * * @param array $row * * @return array */ protected function escapeRow(array $row): array { $arrayDot = array_filter(array_dot($row)); foreach ($arrayDot as $key => $value) { $arrayDot[$key] = e($value); } foreach ($arrayDot as $key => $value) { array_set($row, $key, $value); } return $row; } }
Fix a Python lint error
# -*- encoding: utf-8 import pytest from reindex_shard_config import create_reindex_shard @pytest.mark.parametrize( 'source_name, source_id, expected_reindex_shard', [ ('sierra', 'b0000001', 'sierra/2441'), ('miro', 'A0000001', 'miro/128') ]) def test_create_reindex_shard(source_name, source_id, expected_reindex_shard): reindex_shard = create_reindex_shard( source_name=source_name, source_id=source_id ) assert reindex_shard == expected_reindex_shard @pytest.mark.parametrize('source_name', ['foo', 13, None]) def test_unrecognised_source_name_is_ValueError(source_name): with pytest.raises(ValueError) as err: create_reindex_shard( source_name=source_name, source_id='0001' ) assert err.value.args[0].startswith('Unrecognised source name') assert repr(source_name) in err.value.args[0]
# -*- encoding: utf-8 import pytest from reindex_shard_config import create_reindex_shard @pytest.mark.parametrize( 'source_name, source_id, expected_reindex_shard', [ ('sierra', 'b0000001', 'sierra/2441'), ('miro', 'A0000001', 'miro/128') ]) def test_create_reindex_shard(source_name, source_id, expected_reindex_shard): reindex_shard = create_reindex_shard( source_name=source_name, source_id=source_id ) assert reindex_shard == expected_reindex_shard @pytest.mark.parametrize('source_name', ['foo', 13, None]) def test_unrecognised_source_name_is_ValueError(source_name): with pytest.raises(ValueError) as err: reindex_shard = create_reindex_shard( source_name=source_name, source_id='0001' ) assert err.value.args[0].startswith('Unrecognised source name') assert repr(source_name) in err.value.args[0]
Revert to secure DEV environment
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information umask(0002); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information umask(0002); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. //if (isset($_SERVER['HTTP_CLIENT_IP']) // || isset($_SERVER['HTTP_X_FORWARDED_FOR']) // || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) //) { // header('HTTP/1.0 403 Forbidden'); // exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); //} $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Make use of __DEV__ environment variable
import React from 'react' import { createStore, applyMiddleware, compose } from 'redux' import { Provider } from 'react-redux' import thunk from 'redux-thunk' import devTools from 'remote-redux-devtools' import Tabs from './component/Tabs' import {reducer, initialise} from './store/reducer' class App extends React.Component { store = undefined constructor(){ super() const enhancer = __DEV__ ? applyMiddleware(thunk) : compose( applyMiddleware(thunk), devTools() ) this.store = createStore(reducer, enhancer) if (!process.env.PROD) { devTools.updateStore(this.store) } initialise(this.store) } render() { return ( <Provider store={this.store}> <Tabs /> </Provider> ) } } export default App
import React from 'react' import { createStore, applyMiddleware, compose } from 'redux' import { Provider } from 'react-redux' import thunk from 'redux-thunk' import devTools from 'remote-redux-devtools' import Tabs from './component/Tabs' import {reducer, initialise} from './store/reducer' class App extends React.Component { store = undefined constructor(){ super() const enhancer = process.env.PROD ? applyMiddleware(thunk) : compose( applyMiddleware(thunk), devTools() ) this.store = createStore(reducer, enhancer) if (!process.env.PROD) { devTools.updateStore(this.store) } initialise(this.store) } render() { return ( <Provider store={this.store}> <Tabs /> </Provider> ) } } export default App
Add test for detailed listformatter.
package graval import ( . "github.com/smartystreets/goconvey/convey" "os" "testing" "time" ) type TestFileInfo struct{} func (t *TestFileInfo) Name() string { return "file1.txt" } func (t *TestFileInfo) Size() int64 { return 99 } func (t *TestFileInfo) Mode() os.FileMode { return os.ModeSymlink } func (t *TestFileInfo) IsDir() bool { return false } func (t *TestFileInfo) ModTime() time.Time { return time.Unix(1, 0) } func (t *TestFileInfo) Sys() interface{} { return nil } var files []os.FileInfo = []os.FileInfo{ &TestFileInfo{}, &TestFileInfo{}, } func TestShortFormat(t *testing.T) { formatter := newListFormatter(files) Convey("The Short listing format", t, func() { Convey("Will display correctly", func() { So(formatter.Short(), ShouldEqual, "file1.txt\r\nfile1.txt\r\n\r\n") }) }) } func TestDetailedFormat(t *testing.T) { formatter := newListFormatter(files) Convey("The Detailed listing format", t, func() { Convey("Will display correctly", func() { So(formatter.Detailed(), ShouldEqual, "L--------- 1 owner group 99 Jan 01 10:00 file1.txt\r\nL--------- 1 owner group 99 Jan 01 10:00 file1.txt\r\n\r\n") }) }) }
package graval import ( . "github.com/smartystreets/goconvey/convey" "os" "testing" "time" ) type TestFileInfo struct{} func (t *TestFileInfo) Name() string { return "file1.txt" } func (t *TestFileInfo) Size() int64 { return 99 } func (t *TestFileInfo) Mode() os.FileMode { return os.ModeSymlink } func (t *TestFileInfo) IsDir() bool { return false } func (t *TestFileInfo) ModTime() time.Time { return time.Now() } func (t *TestFileInfo) Sys() interface{} { return nil } var files []os.FileInfo = []os.FileInfo{ &TestFileInfo{}, &TestFileInfo{}, } func TestShortFormat(t *testing.T) { formatter := newListFormatter(files) Convey("The Short listing format", t, func() { Convey("Will display correctly", func() { So(formatter.Short(), ShouldEqual, "file1.txt\r\nfile1.txt\r\n\r\n") }) }) }
Store variables for signal status
/** * Get the network speed from zebedee/ping endpoint and output the network health **/ function networkStatus(ping) { var $good = $('.icon-status--good'), $ok = $('.icon-status--ok'), $poor = $('.icon-status--poor'), $veryPoor = $('.icon-status--very-poor'); if (ping > 0 && ping < 100) { $('.icon-status div').css({"opacity": "1.0"}); } else if (ping >= 100 && ping < 200) { $good.css({"opacity": "0.2"}); $ok.css({"opacity": "1.0"}); $poor.css({"opacity": "1.0"}); $veryPoor.css({"opacity": "1.0"}); } else if (ping >= 200 && ping < 300) { $good.css({"opacity": "0.2"}); $ok.css({"opacity": "0.2"}); $poor.css({"opacity": "1.0"}); $veryPoor.css({"opacity": "1.0"}); } else if (ping >= 300) { $good.css({"opacity": "0.2"}); $ok.css({"opacity": "0.2"}); $poor.css({"opacity": "0.2"}); $veryPoor.css({"opacity": "1.0"}); } }
/** * Get the network speed from zebedee/ping endpoint and output the network health **/ function networkStatus(ping) { if (ping > 0 && ping < 100) { $('.icon-status div').css({"opacity": "1.0"}); } else if (ping >= 100 && ping < 200) { $('.icon-status--good').css({"opacity": "0.2"}); $('.icon-status--ok').css({"opacity": "1.0"}); $('.icon-status--poor').css({"opacity": "1.0"}); $('.icon-status--very-poor').css({"opacity": "1.0"}); } else if (ping >= 200 && ping < 300) { $('.icon-status--good').css({"opacity": "0.2"}); $('.icon-status--ok').css({"opacity": "0.2"}); $('.icon-status--poor').css({"opacity": "1.0"}); $('.icon-status--very-poor').css({"opacity": "1.0"}); } else if (ping >= 300) { $('.icon-status--good').css({"opacity": "0.2"}); $('.icon-status--ok').css({"opacity": "0.2"}); $('.icon-status--poor').css({"opacity": "0.2"}); $('.icon-status--very-poor').css({"opacity": "1.0"}); } }
Fix 'Uncaught ReferenceError: d is not defined'
var Line = require('./line'); var simplifyGeometry = function(points, tolerance){ var dmax = 0; var index = 0; for (var i = 1; i <= points.length - 2; i++){ var d = new Line(points[0], points[points.length - 1]).perpendicularDistance(points[i]); if (d > dmax){ index = i; dmax = d; } } if (dmax > tolerance){ var results_one = simplifyGeometry(points.slice(0, index), tolerance); var results_two = simplifyGeometry(points.slice(index, points.length), tolerance); var results = results_one.concat(results_two); } else if (points.length > 1) { results = [points[0], points[points.length - 1]]; } else { results = [points[0]]; } return results; } module.exports = simplifyGeometry;
var Line = require('./line'); var simplifyGeometry = function(points, tolerance){ var dmax = 0; var index = 0; for (var i = 1; i <= points.length - 2; i++){ d = new Line(points[0], points[points.length - 1]).perpendicularDistance(points[i]); if (d > dmax){ index = i; dmax = d; } } if (dmax > tolerance){ var results_one = simplifyGeometry(points.slice(0, index), tolerance); var results_two = simplifyGeometry(points.slice(index, points.length), tolerance); var results = results_one.concat(results_two); } else if (points.length > 1) { results = [points[0], points[points.length - 1]]; } else { results = [points[0]]; } return results; } module.exports = simplifyGeometry;
Update to new multiauthor taxonomy name
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_fj_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
Test for API url's without path parameters.
package org.trello4j; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.trello4j.model.Action; /** * Created with IntelliJ IDEA. * User: joel * Date: 2012-04-15 * Time: 11:00 AM */ public class TrelloURLTest { /** * Should build url with filter. * * @throws Exception the exception */ @Test public void shouldBuildURLWithFilter() throws Exception { String url = TrelloURL.create("API_KEY", TrelloURL.ACTION_URL, "ID") .token("TOKEN") .filter(Action.TYPE.ADD_ATTACHMENT, Action.TYPE.ADD_CHECKLIST) .build(); String expectedUrl = "https://api.trello.com/1/actions/ID?key=API_KEY&token=TOKEN&filter=" + Action.TYPE.ADD_ATTACHMENT + "," + Action.TYPE.ADD_CHECKLIST; assertEquals(expectedUrl, url); } @Test public void shouldNotReturnNullBaseURL() { String url = TrelloURL .create("API_KEY", TrelloURL.CARD_POST_URL) .token("TOKEN") .build(); String expectedUrl = "https://api.trello.com/1/cards?key=API_KEY&token=TOKEN"; assertEquals(expectedUrl, url); } }
package org.trello4j; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.trello4j.model.Action; /** * Created with IntelliJ IDEA. * User: joel * Date: 2012-04-15 * Time: 11:00 AM */ public class TrelloURLTest { /** * Should build url with filter. * * @throws Exception the exception */ @Test public void shouldBuildURLWithFilter() throws Exception { String url = TrelloURL.create("API_KEY", TrelloURL.ACTION_URL, "ID") .token("TOKEN") .filter(Action.TYPE.ADD_ATTACHMENT, Action.TYPE.ADD_CHECKLIST) .build(); String expectedUrl = "https://api.trello.com/1/actions/ID?key=API_KEY&token=TOKEN&filter=" + Action.TYPE.ADD_ATTACHMENT + "," + Action.TYPE.ADD_CHECKLIST; assertEquals(expectedUrl, url); } }
Move the pragma: nocover to except block
import gym import pytest # Import for side-effect of registering environment import imitation.examples.airl_envs # noqa: F401 import imitation.examples.model_envs # noqa: F401 ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all() if env_spec.id.startswith('imitation/')] @pytest.mark.parametrize("env_name", ENV_NAMES) def test_envs(env_name): """Check that our custom environments don't crash on `step`, and `reset`.""" try: env = gym.make(env_name) except gym.error.DependencyNotInstalled as e: # pragma: nocover if e.args[0].find('mujoco_py') != -1: pytest.skip("Requires `mujoco_py`, which isn't installed.") else: raise env.reset() obs_space = env.observation_space for _ in range(4): act = env.action_space.sample() obs, rew, done, info = env.step(act) assert obs in obs_space
import gym import pytest # Import for side-effect of registering environment import imitation.examples.airl_envs # noqa: F401 import imitation.examples.model_envs # noqa: F401 ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all() if env_spec.id.startswith('imitation/')] @pytest.mark.parametrize("env_name", ENV_NAMES) def test_envs(env_name): # pragma: no cover """Check that our custom environments don't crash on `step`, and `reset`.""" try: env = gym.make(env_name) except gym.error.DependencyNotInstalled as e: if e.args[0].find('mujoco_py') != -1: pytest.skip("Requires `mujoco_py`, which isn't installed.") else: raise env.reset() obs_space = env.observation_space for _ in range(4): act = env.action_space.sample() obs, rew, done, info = env.step(act) assert obs in obs_space
Improve tests for Path methods Replicates graphql/graphql-js@f42cee922d13576b1452bb5bf6c7b155bf0e2ecd
from graphql.pyutils import Path def describe_path(): def can_create_a_path(): first = Path(None, 1, "First") assert first.prev is None assert first.key == 1 assert first.typename == "First" def can_add_a_new_key_to_an_existing_path(): first = Path(None, 1, "First") second = first.add_key("two", "Second") assert second.prev is first assert second.key == "two" assert second.typename == "Second" def can_convert_a_path_to_a_list_of_its_keys(): root = Path(None, 0, "Root") assert root.as_list() == [0] first = root.add_key("one", "First") assert first.as_list() == [0, "one"] second = first.add_key(2, "Second") assert second.as_list() == [0, "one", 2]
from graphql.pyutils import Path def describe_path(): def add_path(): path = Path(None, 0, None) assert path.prev is None assert path.key == 0 prev, path = path, Path(path, 1, None) assert path.prev is prev assert path.key == 1 prev, path = path, Path(path, "two", None) assert path.prev is prev assert path.key == "two" def add_key(): prev = Path(None, 0, None) path = prev.add_key("one") assert path.prev is prev assert path.key == "one" def as_list(): path = Path(None, 1, None) assert path.as_list() == [1] path = path.add_key("two") assert path.as_list() == [1, "two"] path = path.add_key(3) assert path.as_list() == [1, "two", 3]
Change large example to use streaming
package main import ( "bufio" "github.com/sean-duffy/xlsx" "os" "strconv" ) func main() { outputfile, err := os.Create("test.xlsx") w := bufio.NewWriter(outputfile) ww := xlsx.NewWorkbookWriter(w) c := []xlsx.Column{ xlsx.Column{Name: "Col1", Width: 10}, xlsx.Column{Name: "Col2", Width: 10}, } sh := xlsx.NewSheetWithColumns(c) sh.Title = "MySheet" sw, err := ww.NewSheetWriter(&sh) for i := 0; i < 1000000; i++ { r := sh.NewRow() r.Cells[0] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: strconv.Itoa(i + 1), } r.Cells[1] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: "1", } err = sw.WriteRows([]xlsx.Row{r}) } err = ww.Close() defer w.Flush() if err != nil { panic(err) } }
package main import ( "github.com/sean-duffy/xlsx" "strconv" ) func main() { c := []xlsx.Column{ xlsx.Column{Name: "Col1", Width: 10}, xlsx.Column{Name: "Col2", Width: 10}, } sh := xlsx.NewSheetWithColumns(c) sh.Title = "MySheet" for i := 0; i < 10; i++ { r := sh.NewRow() r.Cells[0] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: strconv.Itoa(i + 1), } r.Cells[1] = xlsx.Cell{ Type: xlsx.CellTypeNumber, Value: "1", } sh.AppendRow(r) } err := sh.SaveToFile("test.xlsx") _ = err }
Fix entity index aggregator argument error
import logging from followthemoney import model from servicelayer.worker import Worker from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, task, entities): next_stage = task.context.get('next_stage') if next_stage is None: return stage = task.job.get_stage(next_stage) log.info("Sending %s entities to: %s", len(entities), next_stage) stage.queue({'entity_ids': entities}, task.context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task, manager.emitted)
import logging from followthemoney import model from servicelayer.worker import Worker from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, task, entities): next_stage = task.context.get('next_stage') if next_stage is None: return stage = task.job.get_stage(next_stage) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: stage.queue({'entity_id': entity_id}, task.context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task, manager.emitted)
Make an error go to stderr and remove net 1 LOC
""" This file provides a single interface to unittest objects for our tests while supporting python < 2.7 via unittest2. If you need something from the unittest namespace it should be imported here from the relevant module and then imported into your test from here """ # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: raise SystemExit("You need to install unittest2 to run the salt tests") else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
""" This file provides a single interface to unittest objects for our tests while supporting python < 2.7 via unittest2. If you need something from the unittest namespace it should be imported here from the relevant module and then imported into your test from here """ # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: print("You need to install unittest2 to run the salt tests") sys.exit(1) else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
Allow to retrieve the service manager object using $this->getService()
<?php /** * @version $Id$ * @package Koowa_Object * @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved. * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> */ /** * Object Serviceable Interface * * @author Johan Janssens <johan@nooku.org> * @package Koowa_Object */ interface KObjectServiceable { /** * Get an instance of a class based on a class identifier only creating it if it doesn't exist yet. * * @param string|object $identifier The class identifier or identifier object * @param array $config An optional associative array of configuration settings. * @throws KObjectException * @return object Return object on success, throws exception on failure */ public function getService($identifier = null, array $config = array()); /** * Get a service identifier. * * @param string|object $identifier The class identifier or identifier object * @return KServiceIdentifier */ public function getIdentifier($identifier = null); }
<?php /** * @version $Id$ * @package Koowa_Object * @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved. * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> */ /** * Object Serviceable Interface * * @author Johan Janssens <johan@nooku.org> * @package Koowa_Object */ interface KObjectServiceable { /** * Get an instance of a class based on a class identifier only creating it * if it doesn't exist yet. * * @param string|object $identifier The class identifier or identifier object * @param array $config An optional associative array of configuration settings. * @throws KObjectException * @return object Return object on success, throws exception on failure */ public function getService($identifier, array $config = array()); /** * Get a service identifier. * * @param string|object $identifier The class identifier or identifier object * @return KServiceIdentifier */ public function getIdentifier($identifier = null); }
Use ThreadUtils instead of its own executor
package mil.nga.mapcache.io.network; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import mil.nga.mapcache.utils.ThreadUtils; /** * Makes http requests asynchronously. */ public class HttpClient { /** * The instance of this class. */ private static final HttpClient instance = new HttpClient(); /** * Gets the instance of this class. * * @return This class instance. */ public static HttpClient getInstance() { return instance; } /** * Sends a http get to the specified url. * * @param url The url to send a get request to. * @param handler The response handler, called when request is complete. */ public void sendGet(String url, IResponseHandler handler) { HttpGetRequest request = new HttpGetRequest(url, handler); ThreadUtils.getInstance().runBackground(request); } /** * Private constructor, keep it a singleton. */ private HttpClient() { } }
package mil.nga.mapcache.io.network; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Makes http requests asynchronously. */ public class HttpClient { /** * The instance of this class. */ private static final HttpClient instance = new HttpClient(); /** * The thread pool. */ private ExecutorService executor = Executors.newFixedThreadPool(4); /** * Gets the instance of this class. * * @return This class instance. */ public static HttpClient getInstance() { return instance; } /** * Sends a http get to the specified url. * * @param url The url to send a get request to. * @param handler The response handler, called when request is complete. */ public void sendGet(String url, IResponseHandler handler) { HttpGetRequest request = new HttpGetRequest(url, handler); executor.execute(request); } /** * Private constructor, keep it a singleton. */ private HttpClient() { } }
Make the tree of classes.
<?php namespace App\Http\Controllers; use DB; use App\Http\Requests; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { //$this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { $classes = DB::select('SELECT name, classnumber FROM `classes` WHERE char_length(classnumber)<=3 AND char_length(classnumber)>=1'); $classes_tree = array(); foreach ($classes as $class) { $classes_tree[substr($class->classnumber, 0, 1)][substr($class->classnumber, 0, 2)][$class->classnumber][] = $class->name; } return view('home', ['classes_tree' => $classes_tree]); } }
<?php namespace App\Http\Controllers; use DB; use App\Http\Requests; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { //$this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { $classes = DB::select('SELECT name, classnumber FROM `classes` WHERE char_length(classnumber)<=3 AND char_length(classnumber)>=1'); return view('home', ['classes' => $classes]); } }
Add option to provide callback for request, ok and error actions The callbacks are passed dispatch and getState along with the other arguments.
import {createAction} from 'redux-act' import _defaults from 'lodash.defaults'; const defaultOption = { request:{}, ok:{}, error:{} } export default function createActionAsync(description, api, options = defaultOption) { _defaults(options, defaultOption); let actions = { request: createAction(`${description}_REQUEST`, options.request.payloadReducer, options.request.metaReducer), ok: createAction(`${description}_OK`, options.ok.payloadReducer, options.ok.metaReducer), error: createAction(`${description}_ERROR`, options.error.payloadReducer, options.error.metaReducer) } let actionAsync = (...args) => { return (dispatch) => { dispatch(actions.request(...args)); if(options.request.callback) options.request.callback(dispatch, getState, ...args) return api(...args) .then(res => { dispatch(actions.ok(res, ...args)) if(options.ok.callback) options.ok.callback(dispatch, getState, res, ...args) }) .catch(err => { dispatch(actions.error(err, ...args)) if(options.error.callback) options.error.callback(dispatch, getState, err, ...args) if(options.rethrow) throw err; }) } } actionAsync.request = actions.request; actionAsync.ok = actions.ok; actionAsync.error = actions.error; return actionAsync; };
import {createAction} from 'redux-act' import _defaults from 'lodash.defaults'; const defaultOption = { request:{}, ok:{}, error:{} } export default function createActionAsync(description, api, options = defaultOption) { _defaults(options, defaultOption); let actions = { request: createAction(`${description}_REQUEST`, options.request.payloadReducer, options.request.metaReducer), ok: createAction(`${description}_OK`, options.ok.payloadReducer, options.ok.metaReducer), error: createAction(`${description}_ERROR`, options.error.payloadReducer, options.error.metaReducer) } let actionAsync = (...args) => { return (dispatch) => { dispatch(actions.request(...args)); return api(...args) .then(res => { dispatch(actions.ok(res, ...args)) }) .catch(err => { dispatch(actions.error(err, ...args)) if(options.rethrow) throw err; }) } } actionAsync.request = actions.request; actionAsync.ok = actions.ok; actionAsync.error = actions.error; return actionAsync; };
Add flowtype back in with valid structure for prod
// @flow import React from 'react' import classNames from 'classnames' type Props = { isAuthenticationView: boolean, isDiscoverView: boolean, isNavbarHidden: boolean, isNotificationsActive: boolean, isOnboardingView: boolean, isProfileMenuActive: boolean, userDetailPathClassName?: string, } export const Viewport = (props: Props) => <div className={classNames( 'Viewport', { isAuthenticationView: props.isAuthenticationView }, { isDiscoverView: props.isDiscoverView }, { isNavbarHidden: props.isNavbarHidden }, { isNotificationsActive: props.isNotificationsActive }, { isOnboardingView: props.isOnboardingView }, { isProfileMenuActive: props.isProfileMenuActive }, props.userDetailPathClassName, )} role="presentation" /> export default Viewport
import React, { PropTypes } from 'react' import classNames from 'classnames' // type Props = { // isAuthenticationView: boolean, // isDiscoverView: boolean, // isNavbarHidden: boolean, // isNotificationsActive: boolean, // isOnboardingView: boolean, // isProfileMenuActive: boolean, // userDetailPathClassName?: string, // } // export default(props: Props) => export const Viewport = props => <div className={classNames( 'Viewport', { isAuthenticationView: props.isAuthenticationView }, { isDiscoverView: props.isDiscoverView }, { isNavbarHidden: props.isNavbarHidden }, { isNotificationsActive: props.isNotificationsActive }, { isOnboardingView: props.isOnboardingView }, { isProfileMenuActive: props.isProfileMenuActive }, props.userDetailPathClassName, )} role="presentation" /> Viewport.propTypes = { isAuthenticationView: PropTypes.bool.isRequired, isDiscoverView: PropTypes.bool.isRequired, isNavbarHidden: PropTypes.bool.isRequired, isNotificationsActive: PropTypes.bool.isRequired, isOnboardingView: PropTypes.bool.isRequired, isProfileMenuActive: PropTypes.bool.isRequired, userDetailPathClassName: PropTypes.string, } export default Viewport
Fix default container limit issue https://github.com/rancher/rancher/issues/21664
import { get, set, setProperties } from '@ember/object'; import { hash } from 'rsvp'; import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; export default Route.extend({ globalStore: service(), clusterStore: service(), scope: service(), model(params) { const clusterStore = get(this, 'clusterStore'); const namespace = clusterStore.createRecord({ type: 'namespace', name: '', clusterId: get(this, 'scope.currentCluster.id'), }); if (params.addTo) { set(namespace, 'projectId', get(params, 'addTo')); const containerDefaultResourceLimit = get(namespace, 'project.containerDefaultResourceLimit'); if ( containerDefaultResourceLimit ) { set(namespace, 'containerDefaultResourceLimit', containerDefaultResourceLimit); } } return hash({ namespace, namespaces: get(this, 'clusterStore').findAll('namespace'), allProjects: get(this, 'globalStore').findAll('project'), }); }, resetController(controller, isExiting/* , transition*/) { if ( isExiting ) { setProperties(controller, { errors: null, istioInjection: false }); } }, queryParams: { addTo: { refreshModel: true }, from: { refreshModel: false } }, });
import { get, set, setProperties } from '@ember/object'; import { hash } from 'rsvp'; import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; export default Route.extend({ globalStore: service(), clusterStore: service(), scope: service(), model(params) { const clusterStore = get(this, 'clusterStore'); const namespace = clusterStore.createRecord({ type: 'namespace', name: '', clusterId: get(this, 'scope.currentCluster.id'), }); if (params.addTo) { set(namespace, 'projectId', get(params, 'addTo')); } return hash({ namespace, namespaces: get(this, 'clusterStore').findAll('namespace'), allProjects: get(this, 'globalStore').findAll('project'), }); }, resetController(controller, isExiting/* , transition*/) { if ( isExiting ) { setProperties(controller, { errors: null, istioInjection: false }); } }, queryParams: { addTo: { refreshModel: true }, from: { refreshModel: false } }, });
Introduce factory for email config fixture This allows to create local fixtures that use email config with a broader scope than 'function'.
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest from byceps.services.email import service as email_service from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture(scope='session') def make_email_config(): def _wrapper(): config_id = 'email-config-01' sender_address = 'info@shop.example' email_service.set_config(config_id, sender_address) return email_service.get_config(config_id) return _wrapper @pytest.fixture def email_config(make_email_config): return make_email_config() @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(normal_user): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest from byceps.services.email import service as email_service from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def email_config(): config_id = 'email-config-01' sender_address = 'info@shop.example' email_service.set_config(config_id, sender_address) return email_service.get_config(config_id) @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(normal_user): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
Allow to use not with general conditions
/* * (C) YANDEX LLC, 2014-2015 * * The Source Code called "YoctoDB" available at * https://bitbucket.org/yandex/yoctodb is subject to the terms of the * Mozilla Public License, v. 2.0 (hereinafter referred to as the "License"). * * A copy of the License is also available at http://mozilla.org/MPL/2.0/. */ package com.yandex.yoctodb.query.simple; import com.yandex.yoctodb.query.Condition; import com.yandex.yoctodb.query.QueryContext; import com.yandex.yoctodb.util.mutable.BitSet; import net.jcip.annotations.Immutable; import org.jetbrains.annotations.NotNull; /** * Condition negation * * @author incubos */ @Immutable public final class SimpleNotCondition implements Condition { @NotNull private final Condition delegate; public SimpleNotCondition( @NotNull final Condition delegate) { this.delegate = delegate; } @Override public boolean set( @NotNull final QueryContext ctx, @NotNull final BitSet to) { delegate.set(ctx, to); return to.inverse(); } }
/* * (C) YANDEX LLC, 2014-2015 * * The Source Code called "YoctoDB" available at * https://bitbucket.org/yandex/yoctodb is subject to the terms of the * Mozilla Public License, v. 2.0 (hereinafter referred to as the "License"). * * A copy of the License is also available at http://mozilla.org/MPL/2.0/. */ package com.yandex.yoctodb.query.simple; import com.yandex.yoctodb.query.Condition; import com.yandex.yoctodb.query.QueryContext; import com.yandex.yoctodb.query.TermCondition; import com.yandex.yoctodb.util.mutable.BitSet; import net.jcip.annotations.Immutable; import org.jetbrains.annotations.NotNull; /** * Condition negation * * @author incubos */ @Immutable public final class SimpleNotCondition implements Condition { @NotNull private final TermCondition delegate; public SimpleNotCondition( @NotNull final TermCondition delegate) { this.delegate = delegate; } @Override public boolean set( @NotNull final QueryContext ctx, @NotNull final BitSet to) { delegate.set(ctx, to); return to.inverse(); } }
Disable braekpad automatic registration while we figure out stuff Review URL: http://codereview.chromium.org/462022 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33686 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb)))
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') @atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb)))
Fix event name being returned instead of description in API
<?php namespace Zeropingheroes\Lanager\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class Event extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'description' => $this->description, 'start' => $this->start->toIso8601String(), 'end' => $this->end->toIso8601String(), 'type' => new EventType($this->type), 'lan' => new Lan($this->whenLoaded('lan')), 'links' => [ 'self' => route('api.events.show', $this->id), 'self_gui' => route('lans.events.show', ['lan' => $this->lan_id, 'event' => $this->id]), ], ]; } }
<?php namespace Zeropingheroes\Lanager\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class Event extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'description' => $this->name, 'start' => $this->start->toIso8601String(), 'end' => $this->end->toIso8601String(), 'type' => new EventType($this->type), 'lan' => new Lan($this->whenLoaded('lan')), 'links' => [ 'self' => route('api.events.show', $this->id), 'self_gui' => route('lans.events.show', ['lan' => $this->lan_id, 'event' => $this->id]), ], ]; } }
Add codeception framework for E2E tests [wip]
<?php /** @var \Codeception\Scenario $scenario $I */ $I = new FunctionalTester($scenario); $I->wantTo('perform analysis and see svg results'); @mkdir(codecept_output_dir() . 'svg'); $configFolder = codecept_data_dir('svg' . DIRECTORY_SEPARATOR . 'config'); $expectationFolder = codecept_data_dir('svg' . DIRECTORY_SEPARATOR . 'expectation'); $outputFolder = codecept_output_dir('svg'); array_map('unlink', glob($outputFolder . DIRECTORY_SEPARATOR . '*.svg')); $dir = new \DirectoryIterator($configFolder); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { exec('./bin/phpda analyze ' . $fileinfo->getRealPath(), $output); $result = sha1_file($outputFolder . DIRECTORY_SEPARATOR . $fileinfo->getBasename('yml') . 'svg'); $expectation = sha1_file($expectationFolder . DIRECTORY_SEPARATOR . $fileinfo->getBasename('yml') . 'svg'); if ($expectation !== $result) { //throw new \Exception($fileinfo->getBasename('yml') . ' not working'); } } }
<?php /** @var \Codeception\Scenario $scenario $I */ $I = new FunctionalTester($scenario); $I->wantTo('perform analysis and see svg results'); $configFolder = codecept_data_dir('svg' . DIRECTORY_SEPARATOR . 'config'); $expectationFolder = codecept_data_dir('svg' . DIRECTORY_SEPARATOR . 'expectation'); $outputFolder = codecept_output_dir('svg'); array_map('unlink', glob($outputFolder . DIRECTORY_SEPARATOR . '*.svg')); $dir = new \DirectoryIterator($configFolder); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { exec('./bin/phpda analyze ' . $fileinfo->getRealPath(), $output); $result = sha1_file($outputFolder . DIRECTORY_SEPARATOR . $fileinfo->getBasename('yml') . 'svg'); $expectation = sha1_file($expectationFolder . DIRECTORY_SEPARATOR . $fileinfo->getBasename('yml') . 'svg'); if ($expectation !== $result) { //throw new \Exception($fileinfo->getBasename('yml') . ' not working'); } } }
Fix a bug to specify a script resource name.
package com.github.dakusui.scriptunit.core; import com.github.dakusui.scriptunit.annotations.Load; import java.util.Properties; import static com.github.dakusui.scriptunit.exceptions.ConfigurationException.scriptNotSpecified; import static java.util.Objects.requireNonNull; public interface Config { String getScriptSystemPropertyKey(); String getScriptResourceName(); static Config create(Class<?> testClass, Properties properties) { requireNonNull(testClass); requireNonNull(properties); return new Config() { final Load loadAnnotation = Utils.getAnnotation(testClass, Load.class, Load.DEFAULT_INSTANCE); @Override public String getScriptSystemPropertyKey() { return loadAnnotation.scriptSystemPropertyKey(); } @Override public String getScriptResourceName() { return Utils.check( properties.getProperty(getScriptSystemPropertyKey(), this.loadAnnotation.defaultScriptName()), (in) -> !in.equals(Load.SCRIPT_NOT_SPECIFIED), () -> scriptNotSpecified(getScriptSystemPropertyKey()) ); } }; } }
package com.github.dakusui.scriptunit.core; import com.github.dakusui.scriptunit.annotations.Load; import java.util.Properties; import static com.github.dakusui.scriptunit.exceptions.ConfigurationException.scriptNotSpecified; import static java.util.Objects.requireNonNull; public interface Config { String getScriptSystemPropertyKey(); String getScriptResourceName(); static Config create(Class<?> testClass, Properties properties) { requireNonNull(testClass); requireNonNull(properties); return new Config() { final Load loadAnnotation = Utils.getAnnotation(testClass, Load.class, Load.DEFAULT_INSTANCE); @Override public String getScriptSystemPropertyKey() { return loadAnnotation.scriptSystemPropertyKey(); } @Override public String getScriptResourceName() { return Utils.check( properties.getProperty(getScriptSystemPropertyKey(), this.loadAnnotation.defaultScriptName()), Load.SCRIPT_NOT_SPECIFIED::equals, () -> scriptNotSpecified(getScriptSystemPropertyKey()) ); } }; } }
Use out with out, err with err.
/** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.java; import playn.core.LogImpl; class JavaLog extends LogImpl { @Override protected void logImpl(Level level, String msg, Throwable e) { switch (level) { default: System.out.println(msg); if (e != null) e.printStackTrace(System.out); break; case WARN: case ERROR: System.err.println(msg); if (e != null) e.printStackTrace(System.err); break; } } }
/** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.java; import playn.core.LogImpl; class JavaLog extends LogImpl { @Override protected void logImpl(Level level, String msg, Throwable e) { switch (level) { default: System.out.println(msg); if (e != null) e.printStackTrace(System.err); break; case WARN: case ERROR: System.err.println(msg); if (e != null) e.printStackTrace(System.out); break; } } }
Remove debug of ui router state changes.
(function (module) { module.controller('projectListProcess', projectListProcess); projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"]; function projectListProcess(processes, project, $state, mcmodal, $filter) { var ctrl = this; ctrl.viewProcess = viewProcess; ctrl.chooseTemplate = chooseTemplate; ctrl.processes = processes; ctrl.project = project; if (ctrl.processes.length !== 0) { ctrl.processes = $filter('orderBy')(ctrl.processes, 'name'); ctrl.current = ctrl.processes[0]; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } /////////////////////////////////// function viewProcess(process) { ctrl.current = process; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project); } } }(angular.module('materialscommons')));
(function (module) { module.controller('projectListProcess', projectListProcess); projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"]; function projectListProcess(processes, project, $state, mcmodal, $filter) { console.log('projectListProcess'); var ctrl = this; ctrl.viewProcess = viewProcess; ctrl.chooseTemplate = chooseTemplate; ctrl.processes = processes; ctrl.project = project; if (ctrl.processes.length !== 0) { console.log(' ctrl.processes.length !== 0'); ctrl.processes = $filter('orderBy')(ctrl.processes, 'name'); ctrl.current = ctrl.processes[0]; //$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } /////////////////////////////////// function viewProcess(process) { ctrl.current = process; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project); } } }(angular.module('materialscommons')));
Remove error message when using MAQ module
from impacket.ldap import ldapasn1 as ldapasn1_impacket class CMEModule: ''' Module by Shutdown and Podalirius Initial module: https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota Authors: Shutdown: @_nwodtuhs Podalirius: @podalirius_ ''' def options(self, context, module_options): pass name = 'MAQ' description = 'Retrieves the MachineAccountQuota domain-level attribute' supported_protocols = ['ldap'] opsec_safe = True multiple_hosts = False def on_login(self, context, connection): result = [] context.log.info('Getting the MachineAccountQuota') searchFilter = '(objectClass=*)' attributes = ['ms-DS-MachineAccountQuota'] result = connection.search(searchFilter, attributes) context.log.highlight("MachineAccountQuota: %d" % result[0]['attributes'][0]['vals'][0])
from impacket.ldap import ldapasn1 as ldapasn1_impacket class CMEModule: ''' Module by Shutdown and Podalirius Initial module: https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota Authors: Shutdown: @_nwodtuhs Podalirius: @podalirius_ ''' def options(self, context, module_options): pass name = 'MAQ' description = 'Retrieves the MachineAccountQuota domain-level attribute' supported_protocols = ['ldap'] opsec_safe = True multiple_hosts = False def on_login(self, context, connection): result = [] context.log.info('Getting the MachineAccountQuota') searchFilter = '(objectClass=*)' attributes = ['ms-DS-MachineAccountQuota'] result = connection.search(searchFilter, attributes, 1) for item in result: if isinstance(item, ldapasn1_impacket.SearchResultEntry) is not True: continue context.log.highlight("MachineAccountQuota: %d" % item['attributes'][0]['vals'][0])
Add ability to match input field's height
import classNames from 'classnames/dedupe'; import React from 'react'; import {omit} from '../../utils/Util'; const FieldLabel = (props) => { let {children, className, matchInputHeight, required} = props; let isToggle = false; React.Children.forEach(children, (child) => { let {props = {}} = child; if (['radio', 'checkbox'].includes(props.type)) { isToggle = true; } }); let classes = classNames( {'form-control-toggle form-control-toggle-custom': isToggle}, className ); let requiredNode; if (required) { requiredNode = <span className="text-danger"> *</span>; } let label = ( <label className={classes} {...omit(props, Object.keys(FieldLabel.propTypes))}> {children} {requiredNode} </label> ); if (!matchInputHeight) { return label; } return ( <div className="form-control-input-height"> {label} </div> ); }; FieldLabel.propTypes = { children: React.PropTypes.node, // Vertically center the element based on the height of input fields matchInputHeight: React.PropTypes.bool, // Optional boolean to show a required indicator required: React.PropTypes.bool, // Classes className: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object, React.PropTypes.string ]) }; module.exports = FieldLabel;
import classNames from 'classnames/dedupe'; import React from 'react'; import {omit} from '../../utils/Util'; const FieldLabel = (props) => { let {children, className, required} = props; let isToggle = false; React.Children.forEach(children, (child) => { let {props = {}} = child; if (['radio', 'checkbox'].includes(props.type)) { isToggle = true; } }); let classes = classNames( {'form-control-toggle form-control-toggle-custom': isToggle}, className ); let requiredNode; if (required) { requiredNode = <span className="text-danger"> *</span>; } return ( <label className={classes} {...omit(props, Object.keys(FieldLabel.propTypes))}> {children} {requiredNode} </label> ); }; FieldLabel.propTypes = { children: React.PropTypes.node, // Optional boolean to show a required indicator required: React.PropTypes.bool, // Classes className: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object, React.PropTypes.string ]) }; module.exports = FieldLabel;
Add test case for search term without hits
<?php namespace fennecweb\ajax\listing; use \fennecweb\WebService as WebService; class TraitsTest extends \PHPUnit_Framework_TestCase { public function testExecute() { list($service) = WebService::factory('listing/Traits'); $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => ''))); $expected = array( array( "name" => "PlantHabit", "trait_type_id" => 1, "frequency" => 48916 ) ); $this->assertEquals($expected, $results, 'Search without term and limit, result should be a list of all traits'); $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => 'SomethingThatWillNeverBeATraitType'))); $expected = array(); $this->assertEquals($expected, $results, 'Search term does not hit, result should be an empty array'); } }
<?php namespace fennecweb\ajax\listing; use \fennecweb\WebService as WebService; class TraitsTest extends \PHPUnit_Framework_TestCase { public function testExecute() { //Test for traits without search term or limit list($service) = WebService::factory('listing/Traits'); $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => ''))); $expected = array( array( "name" => "PlantHabit", "trait_type_id" => 1, "frequency" => 48916 ) ); $this->assertEquals($expected, $results); } }
Add a URL to the whitelist
IRG.constants = (function(){ var approvedDomains = function(){ return ["imgur.com", "flickr.com", "cdn.diycozyhome.com", "pbs.twimg.com", "msnbc.com", "fbcdn-sphotos-f-a.akamaihd.net", "flic.kr", "instagram.com", "deviantart.com", "s-media-cache-ak0.pinimg.com", "gfycat.com", "gifbeam.com", "staticflickr.com", "imgflip.com", "upload.wikimedia.org", "livememe.com", "tumblr.com", "wikipedia.org", "archive.is", "imgrush.com", "deviantart.net", "awwni.me", "i.", "fbcdn.net"]; }; var messages = { error: { aProblem : "There's been a problem!", noImagesFound: "No images were found." }, info: { enterSubreddits: "Please enter your subreddits." } }; return{ approvedDomains: approvedDomains(), messages: messages }; })(); IRG.config = (function(){ var redditLocation = "https://www.reddit.com"; return{ redditLocation: redditLocation }; })();
IRG.constants = (function(){ var approvedDomains = function(){ return ["imgur.com", "flickr.com", "cdn.diycozyhome.com", "pbs.twimg.com", "msnbc.com", "fbcdn-sphotos-f-a.akamaihd.net", "flic.kr", "instagram.com", "deviantart.com", "s-media-cache-ak0.pinimg.com", "gfycat.com", "gifbeam.com", "staticflickr.com", "imgflip.com", "upload.wikimedia.org", "livememe.com", "tumblr.com", "wikipedia.org", "archive.is", "imgrush.com", "deviantart.net", "awwni.me", "i."]; }; var messages = { error: { aProblem : "There's been a problem!", noImagesFound: "No images were found." }, info: { enterSubreddits: "Please enter your subreddits." } }; return{ approvedDomains: approvedDomains(), messages: messages }; })(); IRG.config = (function(){ var redditLocation = "https://www.reddit.com"; return{ redditLocation: redditLocation }; })();
Add autoHide prop to pass down
import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbox extends Component { constructor(props) { super(props) } static defaultProps = { autoHide: true, } render() { const {autoHide, children, className} = this.props return ( <Scrollbars className={classnames('fancy-scroll--container', {[className]: className})} autoHide={autoHide} autoHideTimeout={1000} autoHideDuration={250} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h"/>} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v"/>} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h"/>} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v"/>} > {children} </Scrollbars> ) } } const {bool, node, string} = PropTypes FancyScrollbox.propTypes = { children: node.isRequired, className: string, autoHide: bool, } export default FancyScrollbox
import React, {Component, PropTypes} from 'react' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbox extends Component { constructor(props) { super(props) } render() { const {children, className} = this.props return ( <Scrollbars className={`fancy-scroll--container ${className}`} autoHide={true} autoHideTimeout={1000} autoHideDuration={250} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h"/>} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v"/>} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h"/>} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v"/>} > {children} </Scrollbars> ) } } const {node, string} = PropTypes FancyScrollbox.propTypes = { children: node.isRequired, className: string.isRequired, } export default FancyScrollbox
Use PHP 8 union types
<?php declare(strict_types = 1); /** * /src/Entity/Interfaces/UserGroupAwareInterface.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Entity\Interfaces; use App\Entity\UserGroup; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; /** * Interface UserGroupAwareInterface * * @package App\Entity * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ interface UserGroupAwareInterface extends EntityInterface { /** * @return Collection<int, UserGroup>|ArrayCollection<int, UserGroup> */ public function getUserGroups(): Collection|ArrayCollection; /** * Method to attach new userGroup to current user OR api key. */ public function addUserGroup(UserGroup $userGroup): self; /** * Method to remove specified userGroup from current user OR api key. */ public function removeUserGroup(UserGroup $userGroup): self; /** * Method to remove all many-to-many userGroup relations from current user * OR api key. */ public function clearUserGroups(): self; }
<?php declare(strict_types = 1); /** * /src/Entity/Interfaces/UserGroupAwareInterface.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Entity\Interfaces; use App\Entity\UserGroup; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; /** * Interface UserGroupAwareInterface * * @package App\Entity * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ interface UserGroupAwareInterface extends EntityInterface { /** * @return Collection<int, UserGroup>|ArrayCollection<int, UserGroup> */ public function getUserGroups(): Collection; /** * Method to attach new userGroup to current user OR api key. */ public function addUserGroup(UserGroup $userGroup): self; /** * Method to remove specified userGroup from current user OR api key. */ public function removeUserGroup(UserGroup $userGroup): self; /** * Method to remove all many-to-many userGroup relations from current user * OR api key. */ public function clearUserGroups(): self; }
Refactor test to use user
from django.test import TestCase, Client from django.contrib.auth.models import User from billjobs.models import Bill, Service from billjobs.settings import BILLJOBS_BILL_ISSUER class BillingTestCase(TestCase): ''' Test billing creation and modification ''' fixtures = ['dev_data.json'] def setUp(self): self.user = User.objects.get(username='bill') def tearDown(self): pass def test_create_bill_with_one_line(self): ''' Test when user is created a bill with a single service ''' #response = self.client.get('/admin/billjobs/bill/add/', follow_redirect=True) #self.assertEqual(response.status_code, 200) self.assertTrue(True) def test_create_bill(self): bill = Bill(user=self.user) bill.save() self.assertEqual(bill.user.username, self.user.username) self.assertEqual(bill.issuer_address, BILLJOBS_BILL_ISSUER) self.assertEqual( bill.billing_address, self.user.userprofile.billing_address) def test_user_change_billing_address(self): ''' Test when user is changing is billing address Previous bill is with old address New bill is with new address ''' pass
from django.test import TestCase, Client from django.contrib.auth.models import User from billjobs.models import Bill, Service from billjobs.settings import BILLJOBS_BILL_ISSUER class BillingTestCase(TestCase): ''' Test billing creation and modification ''' fixtures = ['dev_data.json'] def setUp(self): self.client = Client() self.client.login(username='bill', password='jobs') def tearDown(self): self.client.logout() def test_create_bill_with_one_line(self): ''' Test when user is created a bill with a single service ''' #response = self.client.get('/admin/billjobs/bill/add/', follow_redirect=True) #self.assertEqual(response.status_code, 200) self.assertTrue(True) def test_create_bill(self): user = User.objects.get(username='bill') bill = Bill(user=user) bill.save() self.assertEqual(bill.user.username, 'bill') self.assertEqual(bill.issuer_address, BILLJOBS_BILL_ISSUER) self.assertEqual( bill.billing_address, user.userprofile.billing_address)
Add missing value check to Rating model's beforeBulkCreate
const _ = require('lodash') const createError = require('http-errors') module.exports = function (sequelize, DataTypes) { const Rating = sequelize.define('Rating', { id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, value: { type: DataTypes.INTEGER, allowNull: false, validate: { min: 0 } }, BikeId: { type: DataTypes.UUID, allowNull: false }, VoteId: { type: DataTypes.UUID, allowNull: false } }, { hooks: { async beforeBulkCreate (ratings, opts) { // Check for missing values const missingValues = _.difference( _.range(1, ratings.length), _.pluck(ratings, 'value') ) if (missingValues.length !== 0) throw createError(422, `Missing values ${JSON.stringify(missingValues)}`, {expose: true}) } }, classMethods: { associate (models) { Rating.belongsTo(models.Bike) Rating.belongsTo(models.Vote) } } }) return Rating }
module.exports = function (sequelize, DataTypes) { const Rating = sequelize.define('Rating', { id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, value: { type: DataTypes.INTEGER, allowNull: false, validate: { min: 0 } }, BikeId: { type: DataTypes.UUID, allowNull: false }, VoteId: { type: DataTypes.UUID, allowNull: false } }, { classMethods: { associate (models) { Rating.belongsTo(models.Bike) Rating.belongsTo(models.Vote) } } }) return Rating }
Disable groups update until next year
'use strict'; var tablesUpdater = require('./tablesUpdater'); var resultsUpdater = require('./resultsUpdater'); var tournamentsUpdater = require('./tournamentsUpdater'); // var groupsUpdater = require('./groupsUpdater'); var scorersUpdater = require('./scorersUpdater'); var assistsUpdater = require('./assistsUpdater'); // Updates league data function updateLeague(leagueArg) { leagueArg = leagueArg || true; tablesUpdater.update(leagueArg); resultsUpdater.update(leagueArg); scorersUpdater.update(leagueArg, null); assistsUpdater.update(leagueArg, null); } // Updates competition data function updateCompetition(competitionArg) { competitionArg = competitionArg || true; tournamentsUpdater.update(competitionArg); // groupsUpdater.update(competitionArg); Disable groups update until next year scorersUpdater.update(null, competitionArg); assistsUpdater.update(null, competitionArg); } module.exports = { updateLeague: updateLeague, updateCompetition: updateCompetition };
'use strict'; var tablesUpdater = require('./tablesUpdater'); var resultsUpdater = require('./resultsUpdater'); var tournamentsUpdater = require('./tournamentsUpdater'); var groupsUpdater = require('./groupsUpdater'); var scorersUpdater = require('./scorersUpdater'); var assistsUpdater = require('./assistsUpdater'); // Updates league data function updateLeague(leagueArg) { leagueArg = leagueArg || true; tablesUpdater.update(leagueArg); resultsUpdater.update(leagueArg); scorersUpdater.update(leagueArg, null); assistsUpdater.update(leagueArg, null); } // Updates competition data function updateCompetition(competitionArg) { competitionArg = competitionArg || true; tournamentsUpdater.update(competitionArg); groupsUpdater.update(competitionArg); scorersUpdater.update(null, competitionArg); assistsUpdater.update(null, competitionArg); } module.exports = { updateLeague: updateLeague, updateCompetition: updateCompetition };
Fix test_tk under OS X with Tk 8.4. Patch by Ned Deily. This should fix some buildbot failures.
import unittest import tkinter from tkinter import font from test.support import requires, run_unittest import tkinter.test.support as support requires('gui') class FontTest(unittest.TestCase): def setUp(self): support.root_deiconify() def tearDown(self): support.root_withdraw() def test_font_eq(self): fontname = "TkDefaultFont" try: f = font.Font(name=fontname, exists=True) except tkinter._tkinter.TclError: f = font.Font(name=fontname, exists=False) font1 = font.nametofont(fontname) font2 = font.nametofont(fontname) self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) self.assertNotEqual(font1, 0) tests_gui = (FontTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
import unittest import tkinter from tkinter import font from test.support import requires, run_unittest import tkinter.test.support as support requires('gui') class FontTest(unittest.TestCase): def setUp(self): support.root_deiconify() def tearDown(self): support.root_withdraw() def test_font_eq(self): font1 = font.nametofont("TkDefaultFont") font2 = font.nametofont("TkDefaultFont") self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) self.assertNotEqual(font1, 0) tests_gui = (FontTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
Fix logging for system commands in CI
''' Provide common utils to validators ''' import subprocess import sys # Run cli command. By default, exit when an error occurs def run_cli_cmd(cmd, exit_on_fail=True): '''Run a command and return its output''' print "Running system command: " + " ".join(cmd) proc = subprocess.Popen(cmd, bufsize=-1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False) stdout, stderr = proc.communicate() if proc.returncode != 0: if exit_on_fail: print stdout print "Unable to run " + " ".join(cmd) + " due to error: " + stderr sys.exit(proc.returncode) else: return False, stdout else: return True, stdout
''' Provide common utils to validators ''' import subprocess import sys # Run cli command. By default, exit when an error occurs def run_cli_cmd(cmd, exit_on_fail=True): '''Run a command and return its output''' print "Running system command: " + cmd proc = subprocess.Popen(cmd, bufsize=-1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False) stdout, stderr = proc.communicate() if proc.returncode != 0: if exit_on_fail: print stdout print "Unable to run " + " ".join(cmd) + " due to error: " + stderr sys.exit(proc.returncode) else: return False, stdout else: return True, stdout
Set the stride to scale
"""Example experiment.""" from functools import partial from toolbox.data import load_set from toolbox.models import compile from toolbox.models import fsrcnn from toolbox.experiment import FSRCNNExperiment # Model scale = 3 model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=scale)) model.summary() # Data train_set = '91-image' val_set = 'Set5' test_sets = ['Set5', 'Set14'] load_set = partial(load_set, sub_size=20, sub_stride=100, scale=scale) # Training experiment = FSRCNNExperiment(scale=scale, model=model, load_set=load_set, save_dir='.') experiment.train(train_set=train_set, val_set=val_set, epochs=2, resume=True) # Evaluation for test_set in test_sets: experiment.test(test_set=test_set)
"""Example experiment.""" from functools import partial from toolbox.data import load_set from toolbox.models import compile from toolbox.models import fsrcnn from toolbox.experiment import FSRCNNExperiment # Model scale = 3 model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=3)) model.summary() # Data train_set = '91-image' val_set = 'Set5' test_sets = ['Set5', 'Set14'] load_set = partial(load_set, sub_size=20, sub_stride=100, scale=scale) # Training experiment = FSRCNNExperiment(scale=scale, model=model, load_set=load_set, save_dir='.') experiment.train(train_set=train_set, val_set=val_set, epochs=2, resume=True) # Evaluation for test_set in test_sets: experiment.test(test_set=test_set)
Fix imports for renamed transformations
from .compute import (sum, product, scale, orthogonalize, threshold, and_, or_, not_, demean, convolve) from .munge import (split, rename, assign, copy, factor, filter, select, delete, replace, to_dense) __all__ = [ 'and_', 'assign', 'convolve', 'copy', 'demean', 'delete', 'factor', 'filter', 'not_', 'or_', 'orthogonalize', 'product', 'rename', 'replace', 'scale', 'select', 'split', 'sum', 'threshold', 'to_dense' ]
from .compute import (sum, product, scale, orthogonalize, threshold, and_, or_, not_, demean, convolve_HRF) from .munge import (split, rename, assign, copy, factor, filter, select, remove, replace, to_dense) __all__ = [ 'and_', 'assign', 'convolve_HRF', 'copy', 'demean', 'factor', 'filter', 'not_', 'or_', 'orthogonalize', 'product', 'remove', 'rename', 'replace', 'scale', 'select', 'split', 'sum', 'threshold', 'to_dense' ]
Clean up method names, variable names, and refine methods.
module.exports = (function(){ function collectParams(url) { return require("../../helpers").paramsForUrl(url); } function constructUrl(params) { url = "http://twitter-capsul.herokuapp.com/tweets?"; url += "lat" + "=" + params["lat"] + "&"; url += "lng" + "=" + params["lng"] + "&"; url += "time" + "=" + params["time"]; return url; } function tweetResponse(res) { return JSON.parse(res.toString('utf8')).tweets } return TwitterManager = { search: function (url) { var qHTTP = require("q-io/http"); var params = collectParams(url); var constructedUrl = constructUrl(params); return qHTTP.read(constructedUrl) .then(tweetResponse, console.error) } }; })();
module.exports = (function(){ function collectParams(url) { var helper = require("../../helpers"); var params = helper.paramsForUrl(url); return params } function constructUrl(params) { url = "http://twitter-capsul.herokuapp.com/tweets?"; url += "lat" + "=" + params["lat"] + "&"; url += "lng" + "=" + params["lng"] + "&"; url += "time" + "=" + params["time"]; return url; } function responseToJson(responseString) { return JSON.parse(responseString).tweets } function convertBuffer(buffer) { return buffer.toString('utf8') } return TwitterManager = { search: function (url) { var qHTTP = require("q-io/http"); var params = collectParams(url); var url = constructUrl(params); return qHTTP.read(url) .then(convertBuffer, console.error) .then(responseToJson, console.error) } }; })();
Add explicit use strict for node v4
/** * @file stat.js * @license MIT * @copyright 2017 Karim Alibhai. */ 'use strict' const fs = require('fs') const chalk = require('chalk') const solver = require('solver') const tools = process.env.TOOLS.split(',') const results = {} const colors = { gulp: 'magenta', grunt: 'yellow', fly: 'blue', brunch: 'green' } let max = [Infinity, [undefined]] function bold(str, should) { if (should) { return chalk.underline(chalk.bold(str)) } return str } tools .map(tool => { results[tool] = solver.data( fs.readFileSync(`${__dirname}/${tool}/bench.log`, 'utf8') .split(/\r?\n/g) .filter(n => !isNaN(+n)) .map(n => +n) ) return tool }) .sort((a, b) => (+results[a].average() > +results[b].average())) .map(tool => { console.log(' ' + chalk[colors[tool]](tool) + ' ' + bold('average: %s ns', max[1].indexOf(tool) !== -1), results[tool].average()) console.log(' ' + chalk[colors[tool]](tool) + ' ' + bold('deviation: %s%', max[1].indexOf(tool) !== -1), results[tool].deviation().relative * 100) console.log('') })
/** * @file stat.js * @license MIT * @copyright 2017 Karim Alibhai. */ const fs = require('fs') const chalk = require('chalk') const solver = require('solver') const tools = process.env.TOOLS.split(',') const results = {} const colors = { gulp: 'magenta', grunt: 'yellow', fly: 'blue', brunch: 'green' } let max = [Infinity, [undefined]] function bold(str, should) { if (should) { return chalk.underline(chalk.bold(str)) } return str } tools .map(tool => { results[tool] = solver.data( fs.readFileSync(`${__dirname}/${tool}/bench.log`, 'utf8') .split(/\r?\n/g) .filter(n => !isNaN(+n)) .map(n => +n) ) return tool }) .sort((a, b) => (+results[a].average() > +results[b].average())) .map(tool => { console.log(' ' + chalk[colors[tool]](tool) + ' ' + bold('average: %s ns', max[1].indexOf(tool) !== -1), results[tool].average()) console.log(' ' + chalk[colors[tool]](tool) + ' ' + bold('deviation: %s%', max[1].indexOf(tool) !== -1), results[tool].deviation().relative * 100) console.log('') })
Prepare for 0.0.1 release to PyPI
#!/usr/bin/env python from setuptools import setup setup(name='tap-awin', version='0.0.1', description='Singer.io tap for extracting data from the Affiliate Window API', author='Onedox', url='https://github.com/onedox/tap-awin', download_url = 'https://github.com/onedox/tap-awin/archive/0.0.1.tar.gz', classifiers=['Programming Language :: Python :: 3 :: Only'], py_modules=['tap_awin'], install_requires=[ 'zeep>=1.4.1', 'singer-python>=1.4.2', 'tzlocal>=1.3', ], entry_points=''' [console_scripts] tap-awin=tap_awin:main ''', packages=['tap_awin'], package_data = { 'tap_awin/schemas': [ "transactions.json", "merchants.json", ], }, include_package_data=True, )
#!/usr/bin/env python from setuptools import setup setup(name='tap-awin', version='0.0.1', description='Singer.io tap for extracting data from the Affiliate Window API', author='Onedox', url='https://onedox.com', classifiers=['Programming Language :: Python :: 3 :: Only'], py_modules=['tap_awin'], install_requires=[ 'zeep>=1.4.1', 'singer-python>=1.4.2', 'tzlocal>=1.3', ], entry_points=''' [console_scripts] tap-awin=tap_awin:main ''', packages=['tap_awin'], package_data = { 'tap_awin/schemas': [ "transactions.json", "merchants.json", ], }, include_package_data=True, )
Resolve URLs in Stylus files
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { context: __dirname + '/src', entry: './bootstrapper', output: { path: __dirname + '/public', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [ { test: /\.(png|jpg)$/, loader: 'url-loader?limit=100000' }, { test: /\.styl$/, loader: 'style-loader!css-loader!stylus-loader?resolve url', }, { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx?$/, loader: 'eslint-loader', exclude: /node_modules/ } ] }, plugins: [ new HtmlWebpackPlugin({ hash: true, inject: true, template: 'src/index.html' }) ], devServer: { contentBase: __dirname + '/public' } };
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { context: __dirname + '/src', entry: './bootstrapper', output: { path: __dirname + '/public', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [ { test: /\.(png|jpg)$/, loader: 'url-loader?limit=100000' }, { test: /\.styl$/, loader: 'style-loader!css-loader!stylus-loader', exclude: /node_modules/ }, { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx?$/, loader: 'eslint-loader', exclude: /node_modules/ } ] }, plugins: [ new HtmlWebpackPlugin({ hash: true, inject: true, template: 'src/index.html' }) ], devServer: { contentBase: __dirname + '/public' } };
Fix page ID for sanity check page... git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@1730 44740490-163a-0410-bde0-09ae8108e29a
<?php $config = SimpleSAML_Configuration::getInstance(); $sconfig = SimpleSAML_Configuration::getConfig('config-sanitycheck.php'); $info = array(); $errors = array(); $hookinfo = array( 'info' => &$info, 'errors' => &$errors, ); SimpleSAML_Module::callHooks('sanitycheck', $hookinfo); if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'text') { if (count($errors) === 0) { echo 'OK'; } else { echo 'FAIL'; } exit; } $t = new SimpleSAML_XHTML_Template($config, 'sanitycheck:check-tpl.php'); $t->data['pageid'] = 'sanitycheck'; $t->data['errors'] = $errors; $t->data['info'] = $info; $t->data['jquery'] = $jquery; $t->show();
<?php $config = SimpleSAML_Configuration::getInstance(); $sconfig = SimpleSAML_Configuration::getConfig('config-sanitycheck.php'); $info = array(); $errors = array(); $hookinfo = array( 'info' => &$info, 'errors' => &$errors, ); SimpleSAML_Module::callHooks('sanitycheck', $hookinfo); if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'text') { if (count($errors) === 0) { echo 'OK'; } else { echo 'FAIL'; } exit; } $t = new SimpleSAML_XHTML_Template($config, 'sanitycheck:check-tpl.php'); $t->data['pageid'] = 'statistics'; $t->data['errors'] = $errors; $t->data['info'] = $info; $t->data['jquery'] = $jquery; $t->show();
Add indication of what None means
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = None # all available interfaces port = portend.find_available_local_port() family = socket.AF_UNSPEC socktype = socket.SOCK_STREAM return socket.getaddrinfo(host, port, family, socktype) def id_for_info(info): af, = info[:1] return str(af) def build_addr_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() @pytest.fixture(**build_addr_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() @pytest.fixture(**build_addr_infos()) def nonlistening_addr(request): af, socktype, proto, canonname, sa = request.param return sa class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2]) def test_check_port_nonlistening(self, nonlistening_addr): portend._check_port(*nonlistening_addr[:2])
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = None port = portend.find_available_local_port() family = socket.AF_UNSPEC socktype = socket.SOCK_STREAM return socket.getaddrinfo(host, port, family, socktype) def id_for_info(info): af, = info[:1] return str(af) def build_addr_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() @pytest.fixture(**build_addr_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() @pytest.fixture(**build_addr_infos()) def nonlistening_addr(request): af, socktype, proto, canonname, sa = request.param return sa class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2]) def test_check_port_nonlistening(self, nonlistening_addr): portend._check_port(*nonlistening_addr[:2])
Use the BRANCH property in the built-in class template
/** * Generated by Mavanagaiata ${MAVANAGAIATA_VERSION} at ${TIMESTAMP} */ package ${PACKAGE_NAME}; public final class ${CLASS_NAME} { public static final String BRANCH = "${BRANCH}"; public static final String COMMIT_ABBREV = "${COMMIT_ABBREV}"; public static final String COMMIT_SHA = "${COMMIT_SHA}"; public static final String DESCRIBE = "${DESCRIBE}"; public static final boolean DIRTY = ${DIRTY}; public static final String TAG = "${TAG_NAME}"; public static final String VERSION = "${VERSION}"; public static String getVersion() { if (TAG.equals(VERSION) && TAG.equals(DESCRIBE)) { return TAG; } return String.format("%s (%s)", VERSION, DESCRIBE); } }
/** * Generated by Mavanagaiata ${MAVANAGAIATA_VERSION} at ${TIMESTAMP} */ package ${PACKAGE_NAME}; public final class ${CLASS_NAME} { public static final String COMMIT_ABBREV = "${COMMIT_ABBREV}"; public static final String COMMIT_SHA = "${COMMIT_SHA}"; public static final String DESCRIBE = "${DESCRIBE}"; public static final boolean DIRTY = ${DIRTY}; public static final String TAG = "${TAG_NAME}"; public static final String VERSION = "${VERSION}"; public static String getVersion() { if (TAG.equals(VERSION) && TAG.equals(DESCRIBE)) { return TAG; } return String.format("%s (%s)", VERSION, DESCRIBE); } }
fix: Use filename for Pipeline name See also: #72
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True
Fix for broken job submission in apache
# Copyright (C) 2015, University of Notre Dame # All rights reserved from django.utils import timezone from django.conf import settings import subprocess import sys import os from data_services import models as data_models def submit(simulation_group): """ Run a simulation group on a local machine in background. Raises RuntimeError if the submission fails for some reason. """ assert isinstance(simulation_group, data_models.SimulationGroup) base_dir = os.path.dirname(os.path.abspath(__file__)) run_script_filename = os.path.join(base_dir, "run.py") for simulation in simulation_group.simulations.all(): executable = sys.executable if hasattr(settings, "PYTHON_EXECUTABLE"): executable = settings.PYTHON_EXECUTABLE subprocess.Popen(executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) simulation_group.submitted_when = timezone.now() simulation_group.save()
# Copyright (C) 2015, University of Notre Dame # All rights reserved from django.utils import timezone import subprocess import sys import os from data_services import models as data_models def submit(simulation_group): """ Run a simulation group on a local machine in background. Raises RuntimeError if the submission fails for some reason. """ assert isinstance(simulation_group, data_models.SimulationGroup) base_dir = os.path.dirname(os.path.abspath(__file__)) run_script_filename = os.path.join(base_dir, "run.py") for simulation in simulation_group.simulations.all(): subprocess.Popen(sys.executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) simulation_group.submitted_when = timezone.now() simulation_group.save()
Fix in toTitle to allow heroku deploy
import Ember from 'ember'; import layout from '../templates/components/uni-horizontal-tabs'; const { Component, computed, isEmpty, observer } = Ember; export default Component.extend({ layout, classNames: ['uni-horizontal-tabs'], options: [], currentTab: 0, /** * @public * @param {Option} option The option data provided to the component * * This method can be redefined if you need to create a custom title */ toTitle(option) { return option; }, onOptionsChanged: observer('options.[]', function() { this.set('currentTab', Math.min(this.get('currentTab'), this.get('options.length') - 1)); }), optionSelected: computed('options.[]', 'currentTab', function() { if (isEmpty(this.get('options'))) { return; } return this.get('options')[this.get('currentTab')]; }), titles: computed('options.@each.title', function() { return this.get('options').map(this.get('toTitle')); }), actions: { setTab(index) { this.set('currentTab', index); } } });
import Ember from 'ember'; import layout from '../templates/components/uni-horizontal-tabs'; const { Component, computed, isEmpty, observer } = Ember; export default Component.extend({ layout, classNames: ['uni-horizontal-tabs'], options: [], currentTab: 0, /** * @public * @param {Option} option The option data provided to the component * * This method can be redefined if you need to create a custom title */ toTitle(option) { return option; }, onOptionsChanged: observer('options.[]', function() { this.set('currentTab', Math.min(this.get('currentTab'), this.get('options.length') - 1)); }), optionSelected: computed('options.[]', 'currentTab', function() { if (isEmpty(this.get('options'))) { return; } return this.get('options')[this.get('currentTab')]; }), titles: computed('options.@each.title', function() { return this.get('options').map(this.toTitle); }), actions: { setTab(index) { this.set('currentTab', index); } } });
Remove blank space at beginning
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER from vim_turing_machine.constants import BLANK_CHARACTER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return BLANK_CHARACTER + result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
Update the default twitter query since it's been flooded by movie tweets.
""" Default settings for the ``mezzanine.twitter`` app. Each of these can be overridden in your project's settings module, just like regular Django settings. The ``editable`` argument for each controls whether the setting is editable via Django's admin. Thought should be given to how a setting is actually used before making it editable, as it may be inappropriate - for example settings that are only read during startup shouldn't be editable, since changing them would require an application reload. """ from django.utils.translation import ugettext_lazy as _ from mezzanine.conf import register_setting from mezzanine.twitter import QUERY_TYPE_CHOICES, QUERY_TYPE_SEARCH register_setting( name="TWITTER_DEFAULT_QUERY_TYPE", label=_("Default Twitter Query Type"), description=_("Type of query that will be used to retrieve tweets for " "the default Twitter feed."), editable=True, default=QUERY_TYPE_SEARCH, choices=QUERY_TYPE_CHOICES, ) register_setting( name="TWITTER_DEFAULT_QUERY", label=_("Default Twitter Query"), description=_("Twitter query to use for the default query type."), editable=True, default="django mezzanine", ) register_setting( name="TWITTER_DEFAULT_NUM_TWEETS", label=_("Default Number of Tweets"), description=_("Number of tweets to display in the default Twitter feed."), editable=True, default=3, )
""" Default settings for the ``mezzanine.twitter`` app. Each of these can be overridden in your project's settings module, just like regular Django settings. The ``editable`` argument for each controls whether the setting is editable via Django's admin. Thought should be given to how a setting is actually used before making it editable, as it may be inappropriate - for example settings that are only read during startup shouldn't be editable, since changing them would require an application reload. """ from django.utils.translation import ugettext_lazy as _ from mezzanine.conf import register_setting from mezzanine.twitter import QUERY_TYPE_CHOICES, QUERY_TYPE_SEARCH register_setting( name="TWITTER_DEFAULT_QUERY_TYPE", label=_("Default Twitter Query Type"), description=_("Type of query that will be used to retrieve tweets for " "the default Twitter feed."), editable=True, default=QUERY_TYPE_SEARCH, choices=QUERY_TYPE_CHOICES, ) register_setting( name="TWITTER_DEFAULT_QUERY", label=_("Default Twitter Query"), description=_("Twitter query to use for the default query type."), editable=True, default="#django", ) register_setting( name="TWITTER_DEFAULT_NUM_TWEETS", label=_("Default Number of Tweets"), description=_("Number of tweets to display in the default Twitter feed."), editable=True, default=3, )
Add a space before install command see https://github.com/ForbesLindesay/spawn-sync/commit/b3d17f770571bd38fb66 f0206d9bf549e165e58c#commitcomment-11172494
'use strict'; var fs = require('fs'); var cp = require('child_process'); var assert = require('assert'); var partialDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2" }; var fullDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2", "try-thread-sleep": "^1.0.0" }; var REQUIRES_UPDATE = false; var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')); if (cp.spawnSync || __dirname.indexOf('node_modules') === -1) { try { assert.deepEqual(pkg.dependencies, partialDependencies); } catch (ex) { pkg.dependencies = partialDependencies; REQUIRES_UPDATE = true; } } else { try { assert.deepEqual(pkg.dependencies, fullDependencies); } catch (ex) { pkg.dependencies = fullDependencies; REQUIRES_UPDATE = true; } } if (REQUIRES_UPDATE && __dirname.indexOf('node_modules') !== -1) { fs.writeFileSync(__dirname + '/package.json', JSON.stringify(pkg, null, ' ')); cp.exec((process.env.npm_execpath || 'npm') + ' install --production', { cwd: __dirname }, function (err) { if (err) { throw err; } }); }
'use strict'; var fs = require('fs'); var cp = require('child_process'); var assert = require('assert'); var partialDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2" }; var fullDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2", "try-thread-sleep": "^1.0.0" }; var REQUIRES_UPDATE = false; var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')); if (cp.spawnSync || __dirname.indexOf('node_modules') === -1) { try { assert.deepEqual(pkg.dependencies, partialDependencies); } catch (ex) { pkg.dependencies = partialDependencies; REQUIRES_UPDATE = true; } } else { try { assert.deepEqual(pkg.dependencies, fullDependencies); } catch (ex) { pkg.dependencies = fullDependencies; REQUIRES_UPDATE = true; } } if (REQUIRES_UPDATE && __dirname.indexOf('node_modules') !== -1) { fs.writeFileSync(__dirname + '/package.json', JSON.stringify(pkg, null, ' ')); cp.exec((process.env.npm_execpath || 'npm') + 'install --production', { cwd: __dirname }, function (err) { if (err) { throw err; } }); }
Remove cancelled from default status
/* * Copyright 2016 Timothy Brooks * * 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 net.uncontended.precipice; public enum Status implements Failable { SUCCESS(false), ERROR(true), TIMEOUT(true); private final boolean isFailed; Status(boolean isFailed) { this.isFailed = isFailed; } @Override public boolean isFailure() { return isFailed; } @Override public boolean isSuccess() { return this == SUCCESS; } }
/* * Copyright 2016 Timothy Brooks * * 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 net.uncontended.precipice; public enum Status implements Failable { SUCCESS(false), ERROR(true), TIMEOUT(true), CANCELLED(false); private final boolean isFailed; Status(boolean isFailed) { this.isFailed = isFailed; } @Override public boolean isFailure() { return isFailed; } @Override public boolean isSuccess() { return this == SUCCESS; } }
Add alternative undefined season which some media has
package com.proxerme.library.parameters; import android.support.annotation.IntDef; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class of the SeasonParameter. This includes the possible yearly seasons. * * @author Desnoo */ public final class SeasonParameter { public static final int UNSPECIFIED_ALT = 0; public static final int WINTER = 1; public static final int SPRING = 2; public static final int SUMMER = 3; public static final int AUTUMN = 4; public static final int UNSPECIFIED = 5; private SeasonParameter() { } /** * An annotation that represents the possible seasons. */ @IntDef({UNSPECIFIED_ALT, SPRING, SUMMER, AUTUMN, WINTER, UNSPECIFIED}) @Retention(value = RetentionPolicy.SOURCE) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) public @interface SeasonConstraint { } }
package com.proxerme.library.parameters; import android.support.annotation.IntDef; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class of the SeasonParameter. This includes the possible yearly seasons. * * @author Desnoo */ public final class SeasonParameter { public static final int WINTER = 1; public static final int SPRING = 2; public static final int SUMMER = 3; public static final int AUTUMN = 4; public static final int UNSPECIFIED = 5; private SeasonParameter() { } /** * An annotation that represents the possible season. */ @IntDef({SPRING, SUMMER, AUTUMN, WINTER, UNSPECIFIED}) @Retention(value = RetentionPolicy.SOURCE) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) public @interface SeasonConstraint { } }
Add pagination link for previous page
<?php $url = app('Flarum\Http\UrlGenerator'); ?> <div class="container"> <h2>{{ $translator->trans('core.views.index.all_discussions_heading') }}</h2> <ul> @foreach ($document->data as $discussion) <li> <a href="{{ $url->to('forum')->route('discussion', [ 'id' => $discussion->id . '-' . $discussion->attributes->slug ]) }}"> {{ $discussion->attributes->title }} </a> </li> @endforeach </ul> @if (isset($document->links->prev)) <a href="{{ $url->to('forum')->route('index') }}?page={{ $page - 1 }}">&laquo; {{ $translator->trans('core.views.index.previous_page_button') }}</a> @endif @if (isset($document->links->next)) <a href="{{ $url->to('forum')->route('index') }}?page={{ $page + 1 }}">{{ $translator->trans('core.views.index.next_page_button') }} &raquo;</a> @endif </div>
<?php $url = app('Flarum\Http\UrlGenerator'); ?> <div class="container"> <h2>{{ $translator->trans('core.views.index.all_discussions_heading') }}</h2> <ul> @foreach ($document->data as $discussion) <li> <a href="{{ $url->to('forum')->route('discussion', [ 'id' => $discussion->id . '-' . $discussion->attributes->slug ]) }}"> {{ $discussion->attributes->title }} </a> </li> @endforeach </ul> @if (isset($document->links->next)) <a href="{{ $url->to('forum')->route('index') }}?page={{ $page + 1 }}">{{ $translator->trans('core.views.index.next_page_button') }} &raquo;</a> @endif </div>
Fix api usage in script parse test.
'use strict'; let assert = require('assert'), path = require('path'), parser = require('../lib/support/browserScript'); const TEST_SCRIPTS_FOLDER = path.resolve(__dirname, 'browserscripts', 'testscripts'); describe('#parseBrowserScripts', function() { it('should parse valid scripts', function() { return parser.findAndParseScripts(TEST_SCRIPTS_FOLDER, 'custom') .then((scriptsByCategory) => { const categoryNames = Object.keys(scriptsByCategory); assert.deepEqual(categoryNames, ['testscripts']); const testscriptsCategory = scriptsByCategory.testscripts; const scriptNames = Object.keys(testscriptsCategory); assert.deepEqual(scriptNames, ['scriptTags']); assert.notEqual(testscriptsCategory.script, ''); }); }); it('should get scripts for all categories', function() { return parser.getScriptsForCategories(parser.allScriptCategories) .then((scriptsByCategory) => { const categoryNames = Object.keys(scriptsByCategory); assert.deepEqual(categoryNames, ['browser', 'pageinfo', 'timings']); }); }); });
'use strict'; let assert = require('assert'), path = require('path'), parser = require('../lib/support/browserScript'); const TEST_SCRIPTS_FOLDER = path.resolve(__dirname, 'browserscripts', 'testscripts'); describe('#parseBrowserScripts', function() { it('should parse valid scripts', function() { return parser.findAndParseScripts(TEST_SCRIPTS_FOLDER) .then((scriptsByCategory) => { const categoryNames = Object.keys(scriptsByCategory); assert.deepEqual(categoryNames, ['testscripts']); const testscriptsCategory = scriptsByCategory.testscripts; const scriptNames = Object.keys(testscriptsCategory); assert.deepEqual(scriptNames, ['scriptTags']); assert.notEqual(testscriptsCategory.script, ''); }); }); it('should get scripts for all categories', function() { return parser.getScriptsForCategories(parser.allScriptCategories) .then((scriptsByCategory) => { const categoryNames = Object.keys(scriptsByCategory); assert.deepEqual(categoryNames, ['browser', 'pageinfo', 'timings']); }); }); });
Add paragraphIds method to Item model.
define([ 'underscore', 'jquery', 'models/resource', 'collections/bullet', 'collections/paragraph' ], function (_, $, Resource, BulletCollection, ParagraphCollection) { 'use strict'; var ItemModel = Resource.extend({ defaults: { name: '', title: '', heading: '' }, resource: 'item', hasMany: ['bullets', 'paragraphs'], initialize: function(attributes, options) { this.set('bullets', new BulletCollection( attributes.bullets )); this.set('paragraphs', new ParagraphCollection( attributes.paragraphs )); }, bulletIds: function() { return this.get('bullets').map(function(bullet) { return bullet.id; }); }, paragraphIds: function() { return this.get('paragraphs').map(function(paragraph) { return paragraph.id; }); }, parse: function(response) { if (response.item) { return response.item; } else { return response; } } }); return ItemModel; });
define([ 'underscore', 'jquery', 'models/resource', 'collections/bullet', 'collections/paragraph' ], function (_, $, Resource, BulletCollection, ParagraphCollection) { 'use strict'; var ItemModel = Resource.extend({ defaults: { name: '', title: '', heading: '' }, resource: 'item', hasMany: ['bullets', 'paragraphs'], initialize: function(attributes, options) { this.set('bullets', new BulletCollection( attributes.bullets )); this.set('paragraphs', new ParagraphCollection( attributes.paragraphs )); }, bulletIds: function() { return this.get('bullets').map(function(bullet) { return bullet.id; }); }, parse: function(response) { if (response.item) { return response.item; } else { return response; } } }); return ItemModel; });
Fix PHPDoc wrong type annotation
<?php /* * This file is part of the PhpTabs package. * * Copyright (c) landrok at github.com/landrok * * For the full copyright and license information, please see * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>. */ namespace PhpTabs\Music; class Scale { private $notes = array(); // 12 private $key; public function __construct() { $this->clear(); } /** * @param int $key */ public function setKey($key) { $this->key = $key; } /** * @return int */ public function getKey() { return $this->key; } /** * @param int $note * @param int|boolean $on */ public function setNote($note, $on) { $this->notes[$note] = $on; } /** * @param int $note * * @return int */ public function getNote($note) { return $this->notes[(($note + (12 - $this->key)) % 12)]; } public function clear() { $this->setKey(0); for ($i = 0; $i < count($this->notes); $i++) { $this->setNote($i, false); } } }
<?php /* * This file is part of the PhpTabs package. * * Copyright (c) landrok at github.com/landrok * * For the full copyright and license information, please see * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>. */ namespace PhpTabs\Music; class Scale { private $notes = array(); // 12 private $key; public function __construct() { $this->clear(); } /** * @param int $key */ public function setKey($key) { $this->key = $key; } /** * @return int */ public function getKey() { return $this->key; } /** * @param int $note * @param int $on */ public function setNote($note, $on) { $this->notes[$note] = $on; } /** * @param int $note * * @return int */ public function getNote($note) { return $this->notes[(($note + (12 - $this->key)) % 12)]; } public function clear() { $this->setKey(0); for ($i = 0; $i < count($this->notes); $i++) { $this->setNote($i, false); } } }
Add PATROL and RAID entity spawn reasons
package com.laytonsmith.abstraction.enums; import com.laytonsmith.annotations.MEnum; @MEnum("com.commandhelper.SpawnReason") public enum MCSpawnReason { BREEDING, BUILD_IRONGOLEM, BUILD_SNOWMAN, BUILD_WITHER, /** * Deprecated as of 1.14, no longer used. */ CHUNK_GEN, /** * Spawned by plugins */ CUSTOM, /** * Missing spawn reason */ DEFAULT, /** * The kind of egg you throw */ EGG, JOCKEY, LIGHTNING, NATURAL, PATROL, RAID, REINFORCEMENTS, SHOULDER_ENTITY, SLIME_SPLIT, SPAWNER, SPAWNER_EGG, VILLAGE_DEFENSE, VILLAGE_INVASION, NETHER_PORTAL, DISPENSE_EGG, INFECTION, CURED, OCELOT_BABY, SILVERFISH_BLOCK, MOUNT, TRAP, ENDER_PEARL, DROWNED, SHEARED, EXPLOSION }
package com.laytonsmith.abstraction.enums; import com.laytonsmith.annotations.MEnum; @MEnum("com.commandhelper.SpawnReason") public enum MCSpawnReason { BREEDING, BUILD_IRONGOLEM, BUILD_SNOWMAN, BUILD_WITHER, /** * Deprecated as of 1.14, no longer used. */ CHUNK_GEN, /** * Spawned by plugins */ CUSTOM, /** * Missing spawn reason */ DEFAULT, /** * The kind of egg you throw */ EGG, JOCKEY, LIGHTNING, NATURAL, REINFORCEMENTS, SHOULDER_ENTITY, SLIME_SPLIT, SPAWNER, SPAWNER_EGG, VILLAGE_DEFENSE, VILLAGE_INVASION, NETHER_PORTAL, DISPENSE_EGG, INFECTION, CURED, OCELOT_BABY, SILVERFISH_BLOCK, MOUNT, TRAP, ENDER_PEARL, DROWNED, SHEARED, EXPLOSION }
Use multibyte str functions in maxlength filter
<?php class CM_Usertext_Filter_MaxLength implements CM_Usertext_Filter_Interface { /** @var int|null */ private $_lengthMax = null; /** * @param int|null $lengthMax */ function __construct($lengthMax = null) { if (null !== $lengthMax) { $this->_lengthMax = (int) $lengthMax; } } public function transform($text, CM_Render $render) { $text = (string) $text; if (null === $this->_lengthMax) { return $text; } if (strlen($text) > $this->_lengthMax) { $text = mb_substr($text, 0, $this->_lengthMax); $lastBlank = mb_strrpos($text, ' '); if ($lastBlank > 0) { $text = mb_substr($text, 0, $lastBlank); } $text = $text . '…'; } return $text; } }
<?php class CM_Usertext_Filter_MaxLength implements CM_Usertext_Filter_Interface { /** @var int|null */ private $_lengthMax = null; /** * @param int|null $lengthMax */ function __construct($lengthMax = null) { if (null !== $lengthMax) { $this->_lengthMax = (int) $lengthMax; } } public function transform($text, CM_Render $render) { $text = (string) $text; if (null === $this->_lengthMax) { return $text; } if (strlen($text) > $this->_lengthMax) { $text = substr($text, 0, $this->_lengthMax); $lastBlank = strrpos($text, ' '); if ($lastBlank > 0) { $text = substr($text, 0, $lastBlank); } $text = $text . '…'; } return $text; } }
Return empty map if Json metadatafile does not exist
package org.rundeck.storage.data.file; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * $INTERFACE is ... User: greg Date: 2/18/14 Time: 11:12 AM */ public class JsonMetadataMapper implements MetadataMapper { private ObjectMapper objectMapper; public JsonMetadataMapper() { objectMapper = new ObjectMapper(); } public JsonMetadataMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void writeMetadata(Map<String, String> meta, File destination) throws IOException { if (!destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } objectMapper.writeValue(destination, meta); } @Override @SuppressWarnings("unchecked") public Map<String, String> readMetadata(File metadata) throws IOException { if(metadata.isFile()){ return objectMapper.readValue(metadata, Map.class); } else { return Collections.<String, String>emptyMap(); } } }
package org.rundeck.storage.data.file; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.util.Map; /** * $INTERFACE is ... User: greg Date: 2/18/14 Time: 11:12 AM */ public class JsonMetadataMapper implements MetadataMapper { private ObjectMapper objectMapper; public JsonMetadataMapper() { objectMapper = new ObjectMapper(); } public JsonMetadataMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void writeMetadata(Map<String, String> meta, File destination) throws IOException { if (!destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } objectMapper.writeValue(destination, meta); } @Override @SuppressWarnings("unchecked") public Map<String, String> readMetadata(File metadata) throws IOException { return objectMapper.readValue(metadata, Map.class); } }
Make the class package private
package info.u_team.u_team_core.data; import java.io.IOException; import java.util.Arrays; import net.minecraft.resources.*; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.fml.loading.FMLLoader; class ExistingFileHelperWithForge extends ExistingFileHelper { private final ExistingFileHelper existingFileHelper; protected ExistingFileHelperWithForge(ExistingFileHelper helper) { super(Arrays.asList(FMLLoader.getForgePath()), helper.isEnabled()); this.existingFileHelper = helper; } public boolean exists(ResourceLocation loc, ResourcePackType type, String pathSuffix, String pathPrefix) { final boolean exists = existingFileHelper.exists(loc, type, pathSuffix, pathPrefix); if (!exists) { return super.exists(loc, type, pathSuffix, pathPrefix); } return exists; } public IResource getResource(ResourceLocation loc, ResourcePackType type, String pathSuffix, String pathPrefix) throws IOException { try { return existingFileHelper.getResource(loc, type, pathSuffix, pathPrefix); } catch (IOException ex) { return super.getResource(loc, type, pathSuffix, pathPrefix); } } }
package info.u_team.u_team_core.data; import java.io.IOException; import java.util.Arrays; import net.minecraft.resources.*; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.fml.loading.FMLLoader; public class ExistingFileHelperWithForge extends ExistingFileHelper { private final ExistingFileHelper existingFileHelper; public ExistingFileHelperWithForge(ExistingFileHelper helper) { super(Arrays.asList(FMLLoader.getForgePath()), helper.isEnabled()); this.existingFileHelper = helper; } public boolean exists(ResourceLocation loc, ResourcePackType type, String pathSuffix, String pathPrefix) { final boolean exists = existingFileHelper.exists(loc, type, pathSuffix, pathPrefix); if (!exists) { return super.exists(loc, type, pathSuffix, pathPrefix); } return exists; } public IResource getResource(ResourceLocation loc, ResourcePackType type, String pathSuffix, String pathPrefix) throws IOException { try { return existingFileHelper.getResource(loc, type, pathSuffix, pathPrefix); } catch (IOException ex) { return super.getResource(loc, type, pathSuffix, pathPrefix); } } }
Add group fetching from AD
import ldap validEditAccessGroups = ['Office Assistants', 'Domain Admins'] def checkCredentials(username, password): if password == "": return 'Empty Password' controller = 'devdc' domainA = 'dev' domainB = 'devlcdi' domain = domainA + '.' + domainB ldapServer = 'ldap://' + controller + '.' + domain ldapUsername = username + '@' + domain ldapPassword = password base_dn = 'DC=' + domainA + ',DC=' + domainB ldap_filter = 'userPrincipalName=' + ldapUsername # Note: empty passwords WILL validate with ldap try: ldap_client = ldap.initialize(ldapServer) ldap_client.set_option(ldap.OPT_REFERRALS, 0) ldap_client.simple_bind_s(ldapUsername, ldapPassword) except ldap.INVALID_CREDENTIALS: ldap_client.unbind() return ('Wrong Credentials', False) except ldap.SERVER_DOWN: return ('Server Down', False) hasEditAccess = False dn = 'cn=Users,' + base_dn filter = 'cn=' + str(username) attrs = ['memberOf'] id = ldap_client.search(dn, ldap.SCOPE_SUBTREE, filter, attrs) groups = ldap_client.result(id)[1][0][1]['memberOf'] for group in groups: address - group.split(',') groupName = address[0].split('=')[1] if groupName in validEditAccessGroups: hasEditAccess = True break ldap_client.unbind() return (True, hasEditAccess)
import ldap def checkCredentials(username, password): if password == "": return 'Empty Password' controller = 'devdc' domainA = 'dev' domainB = 'devlcdi' domain = domainA + '.' + domainB ldapServer = 'ldap://' + controller + '.' + domain ldapUsername = username + '@' + domain ldapPassword = password base_dn = 'DC=' + domainA + ',DC=' + domainB ldap_filter = 'userPrincipalName=' + ldapUsername attrs = ['memberOf'] # Note: empty passwords WILL validate with ldap try: ldap_client = ldap.initialize(ldapServer) ldap_client.set_option(ldap.OPT_REFERRALS, 0) ldap_client.simple_bind_s(ldapUsername, ldapPassword) except ldap.INVALID_CREDENTIALS: ldap_client.unbind() return ('Wrong Credentials', False) except ldap.SERVER_DOWN: return ('Server Down', False) hasEditAccess = False search_dn = "ou=users," + base_dn scope = ldap.SCOPE_SUBTREE filterStr = '(objectclass=person)' attrs = ['sn'] res = ldap_client.search_s(search_dn, scope, filterStr, attrs) print(res) ldap_client.unbind() return (True, hasEditAccess)
Add error messages to the asserts
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files'] elif sys.platform.startswith('linux'): assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}, info['files'] if __name__ == '__main__': main()
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'} elif sys.platform.startswith('linux'): assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'} if __name__ == '__main__': main()
Make worker executor to FixedThreadPoolExecutor.
package com.amebame.triton.server; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.inject.Inject; import javax.inject.Singleton; import com.amebame.triton.config.TritonServerConfiguration; import com.amebame.triton.util.NamedThreadFactory; @Singleton public class TritonServerContext { private TritonServerMethodMap methodMap; private ExecutorService executor; @Inject public TritonServerContext(TritonServerConfiguration config) { methodMap = new TritonServerMethodMap(); executor = Executors.newFixedThreadPool( config.getNetty().getWorker(), new NamedThreadFactory("triton-worker-")); } /** * Add server methods from the target object * @param target */ public void addServerMethod(Object target) { methodMap.register(target); } /** * Get server method by name * @param name * @return */ public TritonServerMethod getServerMethod(String name) { return methodMap.getMethod(name); } /** * Get worker executor * @return */ public ExecutorService getWorkerExecutor() { return executor; } }
package com.amebame.triton.server; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import com.amebame.triton.config.TritonServerConfiguration; import com.amebame.triton.util.NamedThreadFactory; @Singleton public class TritonServerContext { private TritonServerMethodMap methodMap; private ExecutorService executor; @Inject public TritonServerContext(TritonServerConfiguration config) { methodMap = new TritonServerMethodMap(); executor = new ThreadPoolExecutor( 1, config.getNetty().getWorker(), 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("triton-worker-") ); } /** * Add server methods from the target object * @param target */ public void addServerMethod(Object target) { methodMap.register(target); } /** * Get server method by name * @param name * @return */ public TritonServerMethod getServerMethod(String name) { return methodMap.getMethod(name); } /** * Get worker executor * @return */ public ExecutorService getWorkerExecutor() { return executor; } }
Add example for sending a E-mail when a Error is logged by Application
<?php //-------------------------------------------------------------------------- // Application Error Logger //-------------------------------------------------------------------------- Log::useFiles(storage_path() .'Logs' .DS .'error.log'); // Send a E-Mail to administrator when a Error is logged by Application. /* Log::getMonolog()->pushHandler( new Monolog\Handler\SwiftMailerHandler( Mail::getSwiftMailer(), Swift_Message::newInstance('[Log] Some Subject')->setFrom('from@domain.dev')->setTo('to@domain.dev'), Logger::ERROR, // Set minimal Log Level for Mail true // Bubble to next handler? ) ); */ //-------------------------------------------------------------------------- // Application Error Handler //-------------------------------------------------------------------------- App::error(function(Exception $exception, $code) { Log::error($exception); }); //-------------------------------------------------------------------------- // Require The Events File //-------------------------------------------------------------------------- require app_path() .'Events.php'; // Load the Events defined on Modules. foreach ($modules as $module) { $path = app_path() .'Modules' .DS .$module .DS .'Events.php'; if (is_readable($path)) require $path; } //-------------------------------------------------------------------------- // Require The Filters File //-------------------------------------------------------------------------- require app_path() .'Filters.php'; // Load the Filters defined on Modules. foreach ($modules as $module) { $path = app_path() .'Modules' .DS .$module .DS .'Filters.php'; if (is_readable($path)) require $path; }
<?php //-------------------------------------------------------------------------- // Application Error Logger //-------------------------------------------------------------------------- Log::useFiles(storage_path() .'Logs' .DS .'error.log'); //-------------------------------------------------------------------------- // Application Error Handler //-------------------------------------------------------------------------- App::error(function(Exception $exception, $code) { Log::error($exception); }); //-------------------------------------------------------------------------- // Require The Events File //-------------------------------------------------------------------------- require app_path() .'Events.php'; // Load the Events defined on Modules. foreach ($modules as $module) { $path = app_path() .'Modules' .DS .$module .DS .'Events.php'; if (is_readable($path)) require $path; } //-------------------------------------------------------------------------- // Require The Filters File //-------------------------------------------------------------------------- require app_path() .'Filters.php'; // Load the Filters defined on Modules. foreach ($modules as $module) { $path = app_path() .'Modules' .DS .$module .DS .'Filters.php'; if (is_readable($path)) require $path; }
Add about/phpinfo for debugging (admin only)
<?php class aboutActions extends sfActions { public function executeIndex() { $this->forward('about', 'about'); } public function executeAbout() { $response = $this->getResponse(); // test et preuve pour HostGator après l'attaque 2014/02/19 $throttler = new RequestThrottler($this->getUser(), 'baduser'); $throttler->setInterval(2); if (!$throttler->isValid()) { $throttler->setTimeout(); // reset le timer // $response->setContentType('text/plain; charset=utf-8'); $response->setContentType('html'); return $this->renderPartial('misc/requestThrottleError'); } $throttler->setTimeout(); } public function executePhpinfo() { if ($this->getUser()->isAdministrator()) { phpinfo();exit; } // dont do a 404 + log on staging exit; } public function executeLicense() { } public function executeLearnmore() { } public function executeSupport() { } }
<?php class aboutActions extends sfActions { public function executeIndex() { $this->forward('about', 'about'); } public function executeAbout() { $response = $this->getResponse(); // test et preuve pour HostGator après l'attaque 2014/02/19 $throttler = new RequestThrottler($this->getUser(), 'baduser'); $throttler->setInterval(2); if (!$throttler->isValid()) { $throttler->setTimeout(); // reset le timer // $response->setContentType('text/plain; charset=utf-8'); $response->setContentType('html'); return $this->renderPartial('misc/requestThrottleError'); } $throttler->setTimeout(); } /* DISABLED public function executeAdvertise() { } */ public function executeLicense() { } public function executeLearnmore() { } public function executeSupport() { } }
Fix error - transparent not defined
var postcss = require('postcss'), color = require('color'); module.exports = postcss.plugin('postcss-lowvision', function () { return function (css) { css.walkDecls('color', function (decl) { var val = decl.value; var rgb = color(val); rgb = rgb.rgbArray(); decl.value = 'transparent'; decl.cloneAfter({ prop: 'text-shadow', value: '0 0 5px rgba(' + rgb[0] + ', ' + rgb[1] + ', '+ rgb[2] + ', ' + '0.5)' }); }); }; });
var postcss = require('postcss'), color = require('color'); module.exports = postcss.plugin('postcss-lowvision', function () { return function (css) { css.walkDecls('color', function (decl) { var val = decl.value; var rgb = color(val); rgb = rgb.rgbArray(); decl.value = transparent; decl.cloneAfter({ prop: 'text-shadow', value: '0 0 5px rgba(' + rgb[0] + ', ' + rgb[1] + ', '+ rgb[2] + ', ' + '0.5)' }); }); }; });
Read the intput file specified on the command line.
import argparse import sys import hybridJaccard as hj def main(): "Command line testinterface." parser = argparse.ArgumentParser() parser.add_argument('-c','--configFile', help="Configuration file (JSON).", required=False) parser.add_argument('-i','--input', help="Input file of phrases to test.", required=True) parser.add_argument('-r','--referenceFile', help="Reference file.", required=False) args = parser.parse_args() sm = hj.HybridJaccard(ref_path=args.referenceFile, config_path=args.configFile) with open(args.input) as input: for line in input: line = line.strip() match = sm.findBestMatchStringCached(line) if match is None: match = "(NONE)" print(line+" => "+match) # call main() if this is run as standalone if __name__ == "__main__": sys.exit(main())
import argparse import sys import hybridJaccard as hj def main(): "Command line testinterface." parser = argparse.ArgumentParser() parser.add_argument('-c','--configFile', help="Configuration file (JSON).", required=False) parser.add_argument('-i','--input', help="Input file of phrases to test.", required=True) parser.add_argument('-r','--referenceFile', help="Reference file.", required=False) args = parser.parse_args() sm = hj.HybridJaccard(ref_path=args.referenceFile, config_path=args.configFile) with open("input.txt") as input: for line in input: line = line.strip() match = sm.findBestMatchStringCached(line) if match is None: match = "(NONE)" print(line+" => "+match) # call main() if this is run as standalone if __name__ == "__main__": sys.exit(main())
Fix missing GitlabResourceOwner namespace use
<?php /* * OAuth2 Client Bundle * Copyright (c) KnpUniversity <http://knpuniversity.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace KnpU\OAuth2ClientBundle\Client\Provider; use KnpU\OAuth2ClientBundle\Client\OAuth2Client; use League\OAuth2\Client\Token\AccessToken; use Omines\OAuth2\Client\Provider\GitlabResourceOwner; /** * GitlabClient. * * @author Niels Keurentjes <niels.keurentjes@omines.com> */ class GitlabClient extends OAuth2Client { /** * @param AccessToken $accessToken * @return GitlabResourceOwner */ public function fetchUserFromToken(AccessToken $accessToken) { return parent::fetchUserFromToken($accessToken); } /** * @return GitlabResourceOwner */ public function fetchUser() { return parent::fetchUser(); } }
<?php /* * OAuth2 Client Bundle * Copyright (c) KnpUniversity <http://knpuniversity.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace KnpU\OAuth2ClientBundle\Client\Provider; use KnpU\OAuth2ClientBundle\Client\OAuth2Client; use League\OAuth2\Client\Token\AccessToken; /** * GitlabClient. * * @author Niels Keurentjes <niels.keurentjes@omines.com> */ class GitlabClient extends OAuth2Client { /** * @param AccessToken $accessToken * @return GitlabResourceOwner */ public function fetchUserFromToken(AccessToken $accessToken) { return parent::fetchUserFromToken($accessToken); } /** * @return GitlabResourceOwner */ public function fetchUser() { return parent::fetchUser(); } }
Use const and let keywords
'use strict'; const minimatch = require('minimatch'); module.exports = function(env, callback) { function list(contents) { let entries = []; for (let key in contents._) { if (contents._.hasOwnProperty(key)) { const value = contents._[key]; switch (key) { case 'directories': entries = Array.prototype.concat.apply(entries, value.map(list)); break; default: entries = entries.concat(value); } } } return entries.sort((a, b) => a.filename.localeCompare(b.filename)); } function filter(contents, pattern) { return list(contents).filter((entry) => minimatch(entry.filename, pattern)); } env.helpers.contents = { 'filter': filter, 'list': list, }; callback(); };
'use strict'; var minimatch = require('minimatch'); module.exports = function(env, callback) { function list(contents) { var entries = []; for (var key in contents._) { if (contents._.hasOwnProperty(key)) { var value = contents._[key]; switch (key) { case 'directories': entries = Array.prototype.concat.apply(entries, value.map(list)); break; default: entries = entries.concat(value); } } } return entries.sort((a, b) => a.filename.localeCompare(b.filename)); } function filter(contents, pattern) { return list(contents).filter((entry) => minimatch(entry.filename, pattern)); } env.helpers.contents = { 'filter': filter, 'list': list, }; callback(); };
Add .filter() call on this.props.children I was encountering a problem, where if a null value was passed as a child to Component, it threw a few errors. This .filter() removes all falsey values from this.props.children, preventing the errors, and returning the correct result.
/* @flow */ 'use strict'; import React from 'react'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; import ScrollableTabView from './../vendor/react-native-scrollable-tab-view'; export default class TabNB extends NativeBaseComponent { propTypes: { style : React.PropTypes.object } getInitialStyle() { return { tab: { flex: 1 } } } prepareRootProps() { var defaultProps = { style: this.getInitialStyle().tab }; return computeProps(this.props, defaultProps); } render() { return( <ScrollableTabView {...this.prepareRootProps()} > {this.props.children.filter(child => child)} </ScrollableTabView> ); } }
/* @flow */ 'use strict'; import React from 'react'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; import ScrollableTabView from './../vendor/react-native-scrollable-tab-view'; export default class TabNB extends NativeBaseComponent { propTypes: { style : React.PropTypes.object } getInitialStyle() { return { tab: { flex: 1 } } } prepareRootProps() { var defaultProps = { style: this.getInitialStyle().tab }; return computeProps(this.props, defaultProps); } render() { return( <ScrollableTabView {...this.prepareRootProps()} > {this.props.children} </ScrollableTabView> ); } }
Include a modification time on resource creation
package com.dtolabs.rundeck.core.storage; import com.dtolabs.rundeck.plugins.storage.StorageConverterPlugin; import org.rundeck.storage.api.HasInputStream; import org.rundeck.storage.api.Path; import java.util.Date; /** * StorageTimestamperConverter sets modification and creation timestamp metadata for updated/created resources. * * @author greg * @since 2014-03-16 */ public class StorageTimestamperConverter implements StorageConverterPlugin { @Override public HasInputStream readResource(Path path, ResourceMetaBuilder resourceMetaBuilder, HasInputStream hasInputStream) { return null; } @Override public HasInputStream createResource(Path path, ResourceMetaBuilder resourceMetaBuilder, HasInputStream hasInputStream) { resourceMetaBuilder.setCreationTime(new Date()); resourceMetaBuilder.setModificationTime(new Date()); return null; } @Override public HasInputStream updateResource(Path path, ResourceMetaBuilder resourceMetaBuilder, HasInputStream hasInputStream) { resourceMetaBuilder.setModificationTime(new Date()); return null; } }
package com.dtolabs.rundeck.core.storage; import com.dtolabs.rundeck.plugins.storage.StorageConverterPlugin; import org.rundeck.storage.api.HasInputStream; import org.rundeck.storage.api.Path; import java.util.Date; /** * StorageTimestamperConverter sets modification and creation timestamp metadata for updated/created resources. * * @author greg * @since 2014-03-16 */ public class StorageTimestamperConverter implements StorageConverterPlugin { @Override public HasInputStream readResource(Path path, ResourceMetaBuilder resourceMetaBuilder, HasInputStream hasInputStream) { return null; } @Override public HasInputStream createResource(Path path, ResourceMetaBuilder resourceMetaBuilder, HasInputStream hasInputStream) { resourceMetaBuilder.setCreationTime(new Date()); return null; } @Override public HasInputStream updateResource(Path path, ResourceMetaBuilder resourceMetaBuilder, HasInputStream hasInputStream) { resourceMetaBuilder.setModificationTime(new Date()); return null; } }
Add newline at end of file
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, ROOT_URLCONF="watchman.urls", INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "watchman", ], SITE_ID=1, NOSE_ARGS=['-s'], ) from django_nose import NoseTestSuiteRunner except ImportError: raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ['tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, ROOT_URLCONF="watchman.urls", INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "watchman", ], SITE_ID=1, NOSE_ARGS=['-s'], ) from django_nose import NoseTestSuiteRunner except ImportError: raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ['tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
Remove page, add offset and limit to filtered filters
import React, { Component } from 'react' import { isArray, forEach } from 'lodash' import qs from 'qs' import Datasets from './Datasets' const DISABLED_FILTERS = [ 'q', 'offset', 'limit' ] export function _extractFilters(query) { let filters = [] forEach(query, function(value, key) { if (DISABLED_FILTERS.includes(key)) { return } if (isArray(value)) { forEach(value, function(current) { filters.push({name: key, value: current}) }) } else { filters.push({name: key, value}) } }) return filters } export function parseQuery(query) { const parse = qs.parse(query) return { textInput: parse.q, page: parse.page, filters: _extractFilters(parse), } } class WrappedDatasets extends Component { constructor(props) { super(props) this.state = { query: parseQuery(this.props.location.query) } } render() { return <Datasets query={this.state.query}/> } } export default WrappedDatasets
import React, { Component } from 'react' import { isArray, forEach } from 'lodash' import qs from 'qs' import Datasets from './Datasets' const DISABLED_FILTERS = ['q', 'page', ] export function _extractFilters(query) { let filters = [] forEach(query, function(value, key) { if (DISABLED_FILTERS.includes(key)) { return } if (isArray(value)) { forEach(value, function(current) { filters.push({name: key, value: current}) }) } else { filters.push({name: key, value}) } }) return filters } export function parseQuery(query) { const parse = qs.parse(query) return { textInput: parse.q, page: parse.page, filters: _extractFilters(parse), } } class WrappedDatasets extends Component { constructor(props) { super(props) this.state = { query: parseQuery(this.props.location.query) } } render() { return <Datasets query={this.state.query}/> } } export default WrappedDatasets
Update error method to allow for new Error objects
var LogEmitter = function (source) { this.source = source; }; LogEmitter.prototype.info = function (message) { process.emit("gulp:log", { level: "info", message: message, source: this.source }); }; LogEmitter.prototype.warn = function (message) { process.emit("gulp:log", { level: "warn", message: message, source: this.source }); }; LogEmitter.prototype.error = function (message) { var data = {}; data.level = "error"; data.message = message; data.source = this.source; if (message instanceof Error) { data.message = message.message; data.error = message; } process.emit("gulp:log", data); }; LogEmitter.prototype.debug = function (message) { process.emit("gulp:log", { level: "debug", message: message, source: this.source }); }; module.exports = { Logger: function (source) { return new LogEmitter(source); } }; // var log = require('gulp-logemitter').Logger('my plugin'); // log.info("This is something to say");
var LogEmitter = function (source) { this.source = source; }; LogEmitter.prototype.info = function (message) { process.emit("gulp:log", { level: "info", message: message, source: this.source }); }; LogEmitter.prototype.warn = function (message) { process.emit("gulp:log", { level: "warn", message: message, source: this.source }); }; LogEmitter.prototype.error = function (message) { process.emit("gulp:log", { level: "error", message: message, source: this.source }); }; LogEmitter.prototype.debug = function (message) { process.emit("gulp:log", { level: "debug", message: message, source: this.source }); }; module.exports = { Logger: function (source) { return new LogEmitter(source); } }; // var log = require('gulp-logemitter').Logger('my plugin'); // log.info("This is something to say");
Comment did not make sense anymore
/* * Copyright (c) OSGi Alliance (2008, 2009). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.service.blueprint.reflect; import java.util.List; /** * A java.util.Properties based value. The properties are defined as string to * string. This means that the actual value can be returned. * * Defined in the <code>props</code> element. * */ public interface PropsMetadata extends NonNullMetadata { /** * Defined in <code>prop</code> sub elements. * * @return list of <code.MapEntry</code> objects, never <code>null</code> */ List/*<MapEntry>*/ getEntries(); }
/* * Copyright (c) OSGi Alliance (2008, 2009). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.service.blueprint.reflect; import java.util.List; /** * A java.util.Properties based value. The properties are defined as string to * string. This means that the actual value can be returned. * * Defined in the <code>props</code> element. * */ public interface PropsMetadata extends NonNullMetadata { /** * This is the same as getValuesMetadata but more type safe. * * Defined in <code>prop</code> sub elements. * * @return */ List/*<MapEntry>*/ getEntries(); }
Change timeout 55s to 30s
package controller import ( "net/http" "time" "github.com/utahta/momoclo-channel/appengine/lib/crawler" "github.com/utahta/momoclo-channel/appengine/lib/reminder" "github.com/utahta/momoclo-channel/appengine/lib/ustream" "golang.org/x/net/context" ) // Notify reminder func CronReminder(w http.ResponseWriter, req *http.Request) { ctx := getContext(req) if err := reminder.Notify(ctx); err != nil { newError(err, http.StatusInternalServerError).Handle(ctx, w) return } } // Notify ustream func CronUstream(w http.ResponseWriter, req *http.Request) { ctx := getContext(req) if err := ustream.Notify(ctx); err != nil { newError(err, http.StatusInternalServerError).Handle(ctx, w) return } } // Crawling func CronCrawl(w http.ResponseWriter, req *http.Request) { ctx, cancel := context.WithTimeout(getContext(req), 30*time.Second) defer cancel() if err := crawler.Crawl(ctx); err != nil { newError(err, http.StatusInternalServerError).Handle(ctx, w) return } }
package controller import ( "net/http" "time" "github.com/utahta/momoclo-channel/appengine/lib/crawler" "github.com/utahta/momoclo-channel/appengine/lib/reminder" "github.com/utahta/momoclo-channel/appengine/lib/ustream" "golang.org/x/net/context" ) // Notify reminder func CronReminder(w http.ResponseWriter, req *http.Request) { ctx := getContext(req) if err := reminder.Notify(ctx); err != nil { newError(err, http.StatusInternalServerError).Handle(ctx, w) return } } // Notify ustream func CronUstream(w http.ResponseWriter, req *http.Request) { ctx := getContext(req) if err := ustream.Notify(ctx); err != nil { newError(err, http.StatusInternalServerError).Handle(ctx, w) return } } // Crawling func CronCrawl(w http.ResponseWriter, req *http.Request) { ctx, cancel := context.WithTimeout(getContext(req), 55*time.Second) defer cancel() if err := crawler.Crawl(ctx); err != nil { newError(err, http.StatusInternalServerError).Handle(ctx, w) return } }
Clarify that options takes a database parameter Hi, First, many thanks for putting this together. I just got (stupidly) stuck on this for a bit until I read the docs a bit more closely and realized that the DB name is part of the options object. I figured I would add a couple of lines to this to clarify even further for developers down the road. Many thanks!
var Connection = require('../lib/tedious').Connection; var Request = require('../lib/tedious').Request; var config = { server: '192.168.1.212', userName: 'test', password: 'test' /* ,options: { debug: { packet: true, data: true, payload: true, token: false, log: true }, database: 'DBName', encrypt: true // for Azure users } */ }; var connection = new Connection(config); connection.on('connect', function(err) { // If no error, then good to go... executeStatement(); } ); connection.on('debug', function(text) { //console.log(text); } ); function executeStatement() { request = new Request("select 42, 'hello world'", function(err, rowCount) { if (err) { console.log(err); } else { console.log(rowCount + ' rows'); } connection.close(); }); request.on('row', function(columns) { columns.forEach(function(column) { if (column.value === null) { console.log('NULL'); } else { console.log(column.value); } }); }); request.on('done', function(rowCount, more) { console.log(rowCount + ' rows returned'); }); // In SQL Server 2000 you may need: connection.execSqlBatch(request); connection.execSql(request); }
var Connection = require('../lib/tedious').Connection; var Request = require('../lib/tedious').Request; var config = { server: '192.168.1.212', userName: 'test', password: 'test' /* ,options: { debug: { packet: true, data: true, payload: true, token: false, log: true } } */ }; var connection = new Connection(config); connection.on('connect', function(err) { // If no error, then good to go... executeStatement(); } ); connection.on('debug', function(text) { //console.log(text); } ); function executeStatement() { request = new Request("select 42, 'hello world'", function(err, rowCount) { if (err) { console.log(err); } else { console.log(rowCount + ' rows'); } connection.close(); }); request.on('row', function(columns) { columns.forEach(function(column) { if (column.value === null) { console.log('NULL'); } else { console.log(column.value); } }); }); request.on('done', function(rowCount, more) { console.log(rowCount + ' rows returned'); }); // In SQL Server 2000 you may need: connection.execSqlBatch(request); connection.execSql(request); }
Fix the assumption that options.vcf_file is a string.
#!/usr/bin/python import vcf import os from optparse import OptionParser parser = OptionParser() parser.add_option("--vcf", dest="vcf_file", help="Path to VCF to convert", default="") #parser.add_option("--conf", dest="config_file", help="Path to DataBase config file", default=False) (options, args) = parser.parse_args() if not os.path.exists(options.vcf_file): print "Invalid VCF file" exit(0) TABLE_NAME = os.path.basename(options.vcf_file).replace("_design.vcf","") VCF_READER = vcf.Reader(open(options.vcf_file, 'r')) SNP_TEMPLATE = """%s tinyint(3) NOT NULL""" SQL_TEMPLATE = """CREATE TABLE %s ( Sample varchar(100) NOT NULL, %s, PRIMARY KEY (Sample) ); """ SNPids = [] for vcf_record in VCF_READER: SNPids.append(vcf_record.ID) print SQL_TEMPLATE%(TABLE_NAME,",\n".join([SNP_TEMPLATE%(x) for x in SNPids]))
#!/usr/bin/python import vcf import os from optparse import OptionParser parser = OptionParser() parser.add_option("--vcf", dest="vcf_file", help="Path to VCF to convert", default=False) #parser.add_option("--conf", dest="config_file", help="Path to DataBase config file", default=False) (options, args) = parser.parse_args() if not os.path.exists(options.vcf_file): print "Invalid VCF file" exit(0) TABLE_NAME = os.path.basename(options.vcf_file).replace("_design.vcf","") VCF_READER = vcf.Reader(open(options.vcf_file, 'r')) SNP_TEMPLATE = """%s tinyint(3) NOT NULL""" SQL_TEMPLATE = """CREATE TABLE %s ( Sample varchar(100) NOT NULL, %s, PRIMARY KEY (Sample) ); """ SNPids = [] for vcf_record in VCF_READER: SNPids.append(vcf_record.ID) print SQL_TEMPLATE%(TABLE_NAME,",\n".join([SNP_TEMPLATE%(x) for x in SNPids]))
Remove port file on kill
#!/usr/bin/env node 'use strict'; var net = require('net'); var fs = require('fs'); var eslint = require('eslint'); var engine = new eslint.CLIEngine(); var formatter = engine.getFormatter('compact'); var server = net.createServer({ allowHalfOpen: true }, function (con) { var data = ''; con.on('data', function (chunk) { data += chunk; }); con.on('end', function () { var report = engine.executeOnFiles([data]); con.write(formatter(report.results)); con.end(); }); }); var portFile = process.env.HOME + '/.eslint_d_port'; server.listen(function () { var port = server.address().port; fs.writeFileSync(portFile, String(port)); }); process.on('exit', function () { fs.unlinkSync(portFile); }); process.on('SIGTERM', function () { process.exit(); }); process.on('SIGINT', function () { process.exit(); });
#!/usr/bin/env node 'use strict'; var net = require('net'); var fs = require('fs'); var eslint = require('eslint'); var engine = new eslint.CLIEngine(); var formatter = engine.getFormatter('compact'); var server = net.createServer({ allowHalfOpen: true }, function (con) { var data = ''; con.on('data', function (chunk) { data += chunk; }); con.on('end', function () { var report = engine.executeOnFiles([data]); con.write(formatter(report.results)); con.end(); }); }); var portFile = process.env.HOME + '/.eslint_d_port'; server.listen(function () { var port = server.address().port; fs.writeFileSync(portFile, String(port)); }); process.on('exit', function () { fs.unlinkSync(portFile); }); process.on('SIGINT', function () { process.exit(); });
Add a header to the movie reviews single file.
<div class="page-header"> <h1>Movie Reviews</h1> </div> <article <?php post_class('row'); ?>> <figure class="movie-review-poster col-md-3"> <?php the_post_thumbnail('movie-poster'); ?> </figure> <section class="movie-review-snippet col-md-9"> <header class="clearfix"> <div class="movie-review-rating col-sm-1 <?php the_field('movie_grade'); ?>"> <span class="rating-letter"><?php echo getTheRating(get_field('movie_grade')); ?></span> </div> <div class="header-text col-sm-11"> <h1 class="entry-title"><?php the_title(); ?></h1> <?php get_template_part('templates/entry-meta'); ?> </div> </header> <div class="entry-summary"> <?php the_content(); ?> </div> </section> </article>
<article <?php post_class('row'); ?>> <figure class="movie-review-poster col-md-3"> <?php the_post_thumbnail('movie-poster'); ?> </figure> <section class="movie-review-snippet col-md-9"> <header class="clearfix"> <div class="movie-review-rating col-sm-1 <?php the_field('movie_grade'); ?>"> <span class="rating-letter"><?php echo getTheRating(get_field('movie_grade')); ?></span> </div> <div class="header-text col-sm-11"> <h1 class="entry-title"><?php the_title(); ?></h1> <?php get_template_part('templates/entry-meta'); ?> </div> </header> <div class="entry-summary"> <?php the_content(); ?> </div> </section> </article>
Use a GET request instead
from flask import Flask, request import requests from urllib import urlencode app = Flask(__name__) @app.route("/") def meme(): slackbot = request.args["slackbot"] text = request.args["text"] channel = request.args["channel_name"] text = text[:-1] if text[-1] == ";" else text params = text.split(";") params = [x.strip().replace(" ", "-") for x in params] params = [urlencode(x) for x in params] if not len(params) == 3: response = "Your syntax should be in the form: /meme template; top; bottom;" else: template = params[0] top = params[1] bottom = params[2] response = "http://memegen.link/{0}/{1}/{2}.jpg".format(template, top, bottom) url = "https://neo4j.slack.com/services/hooks/slackbot?token={0}&channel=%23{1}".format(slackbot, channel) requests.post(url, data=response)
from flask import Flask, request import requests from urllib import urlencode app = Flask(__name__) @app.route("/", methods=['POST']) def meme(): form = request.form.to_dict() slackbot = form["slackbot"] text = form["text"] channel = form["channel_name"] text = text[:-1] if text[-1] == ";" else text params = text.split(";") params = [x.strip().replace(" ", "-") for x in params] params = [urlencode(x) for x in params] if not len(params) == 3: response = "Your syntax should be in the form: /meme template; top; bottom;" else: template = params[0] top = params[1] bottom = params[2] response = "http://memegen.link/{0}/{1}/{2}.jpg".format(template, top, bottom) url = "https://neo4j.slack.com/services/hooks/slackbot?token={0}&channel=%23{1}".format(slackbot, channel) requests.post(url, data=response)
Update player creation test to verify POST status code.
from webtest import TestApp import dropshot def test_create_player(): app = TestApp(dropshot.app) params = {'username': 'chapmang', 'password': 'deadparrot', 'email': 'chapmang@dropshot.com'} expected = {'count': 1, 'offset': 0, 'players': [ {'gamesPlayed': 0, 'username': 'chapmang'} ]} post_response = app.post('/players', params) assert post_response.status_int == 201 get_response = app.get('/players') assert get_response.status_int == 200 assert get_response.content_type == 'application/json' assert get_response.json == expected
from webtest import TestApp import dropshot def test_create_player(): app = TestApp(dropshot.app) params = {'username': 'chapmang', 'password': 'deadparrot', 'email': 'chapmang@dropshot.com'} expected = {'count': 1, 'offset': 0, 'players': [ {'gamesPlayed': 0, 'username': 'chapmang'} ]} app.post('/players', params) res = app.get('/players') assert res.status_int == 200 assert res.content_type == 'application/json' assert res.json == expected
Fix the cancelled key bug
domready(function() { var UP = "up"; var DOWN = "down"; var current = 0; var height = document.body.clientHeight; var number = document.querySelectorAll('body > section').length; var running = false; var duration = parseFloat(getComputedStyle(document.body).transitionDuration) * 1000; function slide(direction) { if (running) { return; } running = true; if (direction == UP) { current--; } else if (direction == DOWN) { current++; } current = current % number; if (current < 0) { current += number; } document.body.style.transform = 'translateY(' + (current * -height) + 'px)'; setTimeout(function() { running = false; }, duration); } window.addEventListener('wheel', function(event) { if(event.deltaY > 0) { slide(DOWN); } else { slide(UP); } }); window.addEventListener('keypress', function(event) { switch (event.keyCode) { case 38: slide(UP); event.preventDefault(); break; case 40: slide(DOWN); event.preventDefault(); break; } }); window.addEventListener('resize', function() { setHeight(); slide(); }); });
domready(function() { var UP = "up"; var DOWN = "down"; var current = 0; var height = document.body.clientHeight; var number = document.querySelectorAll('body > section').length; var running = false; var duration = parseFloat(getComputedStyle(document.body).transitionDuration) * 1000; function slide(direction) { if (running) { return; } running = true; if (direction == UP) { current--; } else if (direction == DOWN) { current++; } current = current % number; if (current < 0) { current += number; } document.body.style.transform = 'translateY(' + (current * -height) + 'px)'; setTimeout(function() { running = false; }, duration); } window.addEventListener('wheel', function(event) { if(event.deltaY > 0) { slide(DOWN); } else { slide(UP); } }); window.addEventListener('keypress', function(event) { switch (event.keyCode) { case 38: slide(UP); break; case 40: slide(DOWN); break; } event.preventDefault(); return false; }); window.addEventListener('resize', function() { setHeight(); slide(); }); });
Remove some nasty imports to avoid cyclic import issues.
# Licensed to the StackStorm, Inc ('StackStorm') 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. from st2common.transport import liveaction, actionexecutionstate, execution, publishers, reactor from st2common.transport import utils, connection_retry_wrapper # TODO(manas) : Exchanges, Queues and RoutingKey design discussion pending. __all__ = [ 'liveaction', 'actionexecutionstate', 'execution', 'publishers', 'reactor', 'utils', 'connection_retry_wrapper' ]
# Licensed to the StackStorm, Inc ('StackStorm') 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. from st2common.transport import liveaction, actionexecutionstate, execution, publishers, reactor from st2common.transport import bootstrap_utils, utils, connection_retry_wrapper # TODO(manas) : Exchanges, Queues and RoutingKey design discussion pending. __all__ = [ 'liveaction', 'actionexecutionstate', 'execution', 'publishers', 'reactor', 'bootstrap_utils', 'utils', 'connection_retry_wrapper' ]
Make lib/net.MeasuringDialer.Dial() conform to Dialer.Dial().
package net import ( "net" "time" ) func newMeasuringDialer(dialer Dialer) *MeasuringDialer { return &MeasuringDialer{dialer: dialer} } func (d *MeasuringDialer) Dial(network, address string) (net.Conn, error) { startTime := time.Now() netConn, err := d.dialer.Dial(network, address) d.cumulativeDialTime += time.Since(startTime) if err != nil { return nil, err } return &MeasuringConnection{Conn: netConn}, nil } func (conn *MeasuringConnection) read(b []byte) (n int, err error) { startTime := time.Now() n, err = conn.Conn.Read(b) conn.cumulativeReadTime += time.Since(startTime) return } func (conn *MeasuringConnection) write(b []byte) (n int, err error) { startTime := time.Now() n, err = conn.Conn.Write(b) conn.cumulativeWriteTime += time.Since(startTime) return }
package net import ( "time" ) func newMeasuringDialer(dialer Dialer) *MeasuringDialer { return &MeasuringDialer{dialer: dialer} } func (d *MeasuringDialer) Dial(network, address string) ( *MeasuringConnection, error) { startTime := time.Now() netConn, err := d.dialer.Dial(network, address) d.cumulativeDialTime += time.Since(startTime) if err != nil { return nil, err } return &MeasuringConnection{Conn: netConn}, nil } func (conn *MeasuringConnection) read(b []byte) (n int, err error) { startTime := time.Now() n, err = conn.Conn.Read(b) conn.cumulativeReadTime += time.Since(startTime) return } func (conn *MeasuringConnection) write(b []byte) (n int, err error) { startTime := time.Now() n, err = conn.Conn.Write(b) conn.cumulativeWriteTime += time.Since(startTime) return }
Change from resourceId to id
package model.job.metadata; import java.util.List; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(Include.NON_NULL) public class ResourceMetadata { public String name; public String id; public String description; public String url; public String filePath; public String format; public String networks; public String qos; public String availability; public String tags; public String classType; @JsonIgnore public DateTime termDate; public Boolean clientCertRequired; public Boolean credentialsRequired; public Boolean preAuthRequired; public String contacts; public String method; public String requestMimeType; public String param; @JsonProperty("params") public List<String> params; public String responseMimeType; public String reason; }
package model.job.metadata; import java.util.List; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(Include.NON_NULL) public class ResourceMetadata { public String name; @JsonProperty("_id") public String resourceId; public String description; public String url; public String filePath; public String format; public String networks; public String qos; public String availability; public String tags; public String classType; @JsonIgnore public DateTime termDate; public Boolean clientCertRequired; public Boolean credentialsRequired; public Boolean preAuthRequired; public String contacts; public String method; public String requestMimeType; public String param; @JsonProperty("params") public List<String> params; public String responseMimeType; public String reason; }
Switch version to semantic versioning.
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='legitfs', version='0.4.0.0dev', description=('A read-only FUSE-based filesystem allowing you to browse ' 'git repositories'), long_description=read('README.rst'), keywords='git,fuse,filesystem,fs,read-only,readonly,legit,legitfs', author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/legitfs', license='MIT', packages=find_packages(exclude=['tests']), install_requires=['dulwich', 'fusepy', 'click', 'logbook'], entry_points={ 'console_scripts': [ 'legitfs = legitfs.cli:main', ] })
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='legitfs', version='0.4.dev1', description=('A read-only FUSE-based filesystem allowing you to browse ' 'git repositories'), long_description=read('README.rst'), keywords='git,fuse,filesystem,fs,read-only,readonly,legit,legitfs', author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/legitfs', license='MIT', packages=find_packages(exclude=['tests']), install_requires=['dulwich', 'fusepy', 'click', 'logbook'], entry_points={ 'console_scripts': [ 'legitfs = legitfs.cli:main', ] })
Remove irrelvant methods in the test model
<?php class MockJsonModel extends Illuminate\Database\Eloquent\Model { use \ModelJsonColumn\JsonColumnTrait; protected $json_columns; public function __construct(array $attributes = []) { static::$booted[get_class($this)] = true; parent::__construct($attributes); } public function setJsonColumns(array $columns) { $this->json_columns = $columns; } public function setCastsColumns(array $columns) { $this->casts = $columns; } public function setJsonColumnDefaults($column_name, $defaults) { $this->json_defaults[$column_name] = $defaults; } }
<?php class MockJsonModel extends Illuminate\Database\Eloquent\Model { use \ModelJsonColumn\JsonColumnTrait; protected $json_columns; public function __construct(array $attributes = []) { static::$booted[get_class($this)] = true; parent::__construct($attributes); } public function setJsonColumns(array $columns) { $this->json_columns = $columns; } public function setCastsColumns(array $columns) { $this->casts = $columns; } public function setJsonColumnDefaults($column_name, $defaults) { $this->json_defaults[$column_name] = $defaults; } public function getCustomGetAttribute() { return 'custom getter result'; } public function setCustomSetAttribute($value) { $this->setJsonAttribute($this->jsonAttributes['custom_set'], 'custom_set', "custom {$value}"); } }
Add sourcemaps for easier debugging
var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './scrappyr/static/js/index', output: { path: path.resolve('./scrappyr/static/webpack_bundles/'), filename: "[name]-[hash].js" }, devtool: 'source-map', plugins: [ new BundleTracker({filename: './webpack-stats.json'}), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.js$/, loader: 'babel', query: { presets:['es2015', 'es2017', 'react'] }, include: path.join(__dirname, 'scrappyr/static/js') } ] } }
var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './scrappyr/static/js/index', output: { path: path.resolve('./scrappyr/static/webpack_bundles/'), filename: "[name]-[hash].js" }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.js$/, loader: 'babel', query: { presets:['es2015', 'es2017', 'react'] }, include: path.join(__dirname, 'scrappyr/static/js') } ] } }
Use variables to cache values
import React from 'react'; export class Checkbox extends React.PureComponent { handleToggle = () => { const { node, handleToggle } = this.props; handleToggle(node); } render() { const { node, handleToggle } = this.props; if (node.childKeys && node.childKeys.length) { let nodeList = node.childKeys.map(childNode => { return <Checkbox key={childNode.key} node={childNode} handleToggle={handleToggle} />; }) return ( <li> <input type='checkbox' checked={node.checked} className='pointer' onChange={this.handleToggle} /> <label className='ml2'>{node.key}</label> <ul className='list'> {nodeList} </ul> </li> ); } else { return ( <li> <input type='checkbox' checked={node.checked} className='pointer' onChange={this.handleToggle} /> <label className='ml2'>{node.key}</label> </li> ); } } }
import React from 'react'; export class Checkbox extends React.PureComponent { handleToggle = () => { this.props.handleToggle(this.props.node); } render() { if (this.props.node.childKeys && this.props.node.childKeys.length) { let nodeList = this.props.node.childKeys.map(childNode => { return <Checkbox key={childNode.key} node={childNode} handleToggle={this.props.handleToggle} />; }) return ( <li> <input type='checkbox' checked={this.props.node.checked} className='pointer' onChange={this.handleToggle} /> <label className='ml2'>{this.props.node.key}</label> <ul className='list'> {nodeList} </ul> </li> ); } else { return ( <li> <input type='checkbox' checked={this.props.node.checked} className='pointer' onChange={this.handleToggle} /> <label className='ml2'>{this.props.node.key}</label> </li> ); } } }
Allow cursor to be executed directly
module.exports = function(schema, options) { options || (options = {}); options.path || (options.path = '_acl'); // Fields var fields = {}; if (!schema.paths[options.path]) { fields[options.path] = {}; } schema.add(fields); // Methods schema.methods.setAccess = function(key, ops) { ops || (ops = {}); this[options.path] || (this[options.path] = {}); this[options.path][key] = ops; this.markModified(options.path); }; schema.methods.getAccess = function(key) { var acl = this[options.path] || {}; return acl[key] || {}; }; // Statics schema.statics.withAccess = function(subject, op, callback) { var keys = subject.getAccessKeys(); var or = keys.map(function(key) { var path = [options.path, key, op].join('.'); var query = {}; query[path] = true; return query; }); var cursor = this.find({ $or: or }); if (callback) { cursor.exec(callback); } return cursor; }; };
module.exports = function(schema, options) { options || (options = {}); options.path || (options.path = '_acl'); // Fields var fields = {}; if (!schema.paths[options.path]) { fields[options.path] = {}; } schema.add(fields); // Methods schema.methods.setAccess = function(key, ops) { ops || (ops = {}); this[options.path] || (this[options.path] = {}); this[options.path][key] = ops; this.markModified(options.path); }; schema.methods.getAccess = function(key) { var acl = this[options.path] || {}; return acl[key] || {}; }; // Statics schema.statics.withAccess = function(subject, op) { var keys = subject.getAccessKeys(); var or = keys.map(function(key) { var path = [options.path, key, op].join('.'); var query = {}; query[path] = true; return query; }); var cursor = this.find({ $or: or }); return cursor; }; };
Use "id" instead of "plot_id" For the fake utf grid
from django.conf.urls import patterns, include, url from django.http import HttpResponse from opentreemap import urls testing_id = 1 def full_utf8_grid(request): """ Creates a big utf8 grid where every entry is 'turned on' to point to whatever plot id is the currently assigned value of testing_id this is useful for mocking a tiler utf8 grid response so that ui tests can click the map and simulate clicking a rendered tree tile. """ global testing_id quoted_space_line = '"' + (' ' * 64) + '"' quoted_space_line_with_comma = quoted_space_line + ',' full_space_utf8_grid = ('{"grid":[' + (quoted_space_line_with_comma * 63) + quoted_space_line + '],"keys":["1"],"data":{"1":{"id":%s}}}' % testing_id) response = HttpResponse(full_space_utf8_grid) response['Content-Type'] = 'application/json' return response urlpatterns = patterns( '', url(r'^tile/.*', full_utf8_grid), url(r'', include(urls)) )
from django.conf.urls import patterns, include, url from django.http import HttpResponse from opentreemap import urls testing_id = 1 def full_utf8_grid(request): """ Creates a big utf8 grid where every entry is 'turned on' to point to whatever plot id is the currently assigned value of testing_id this is useful for mocking a tiler utf8 grid response so that ui tests can click the map and simulate clicking a rendered tree tile. """ global testing_id quoted_space_line = '"' + (' ' * 64) + '"' quoted_space_line_with_comma = quoted_space_line + ',' full_space_utf8_grid = ('{"grid":[' + (quoted_space_line_with_comma * 63) + quoted_space_line + '],"keys":["1"],"data":{"1":{"the_plot_id":%s}}}' % testing_id) response = HttpResponse(full_space_utf8_grid) response['Content-Type'] = 'application/json' return response urlpatterns = patterns( '', url(r'^tile/.*', full_utf8_grid), url(r'', include(urls)) )
Add Ember 1.12 and 1.13 to tests
/*jshint node:true*/ module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-1.12', dependencies: { 'ember': '1.12' } }, { name: 'ember-1.13', dependencies: { 'ember': '1.13' } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } } ] };
/*jshint node:true*/ module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } } ] };