text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add 'sites' task for rigorous doc error discovery
from os import mkdir from os.path import join from shutil import rmtree, copytree from invoke import Collection, ctask as task from invocations.docs import docs, www, sites from invocations.packaging import publish # Until we move to spec-based testing @task def test(ctx, coverage=False, flags=""): if "--verbose" not in flags.split(): flags += " --verbose" runner = "python" if coverage: runner = "coverage run --source=paramiko" ctx.run("{0} test.py {1}".format(runner, flags), pty=True) @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") # Until we stop bundling docs w/ releases. Need to discover use cases first. @task def release(ctx): # Build docs first. Use terribad workaround pending invoke #146 ctx.run("inv docs") # Move the built docs into where Epydocs used to live target = 'docs' rmtree(target, ignore_errors=True) # TODO: make it easier to yank out this config val from the docs coll copytree('sites/docs/_build', target) # Publish publish(ctx) # Remind print("\n\nDon't forget to update RTD's versions page for new minor releases!") ns = Collection(test, coverage, release, docs, www, sites)
from os import mkdir from os.path import join from shutil import rmtree, copytree from invoke import Collection, ctask as task from invocations.docs import docs, www from invocations.packaging import publish # Until we move to spec-based testing @task def test(ctx, coverage=False, flags=""): if "--verbose" not in flags.split(): flags += " --verbose" runner = "python" if coverage: runner = "coverage run --source=paramiko" ctx.run("{0} test.py {1}".format(runner, flags), pty=True) @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") # Until we stop bundling docs w/ releases. Need to discover use cases first. @task def release(ctx): # Build docs first. Use terribad workaround pending invoke #146 ctx.run("inv docs") # Move the built docs into where Epydocs used to live target = 'docs' rmtree(target, ignore_errors=True) # TODO: make it easier to yank out this config val from the docs coll copytree('sites/docs/_build', target) # Publish publish(ctx) # Remind print("\n\nDon't forget to update RTD's versions page for new minor releases!") ns = Collection(test, coverage, release, docs, www)
Use only the base file name for key Former-commit-id: 3acbf9e93d3d501013e2a1b6aa9631bdcc663c66 [formerly eea949727d3693aa032033d84dcca3790d9072dd] [formerly ca065bc9f78b1416903179418d64b3273d437987] Former-commit-id: 58c1d18e8960ad3236a34b8080b18ccff5684eaa Former-commit-id: 6501068cea164df37ec055c3fb8baf8c89fc7823
import os """ Loader settings: we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the same id_sample based on the hash of the file name """ inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat' keyFormatClass = 'org.apache.hadoop.io.LongWritable' valueFormatClass = 'org.apache.hadoop.io.Text' defaultCombineSize = 64 # configuration of the Hadoop loader used by spark conf = {"textinputformat.record.delimiter": "\n", "mapreduce.input.fileinputformat.input.dir.recursive": "true", "mapred.max.split.size": str(defaultCombineSize*1024*1024) } """ Generation of the index of the pandas dataframe. This can be done in different ways: - hashing the complete file name - using directly the file as index (this is visually appealing :) ) """ def generateHashKey(filename): return hash(filename) def generateNameKey(filename): filename = os.path.basename(filename) if filename.endswith(".meta"): return filename[:-5] else: return filename
""" Loader settings: we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the same id_sample based on the hash of the file name """ inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat' keyFormatClass = 'org.apache.hadoop.io.LongWritable' valueFormatClass = 'org.apache.hadoop.io.Text' defaultCombineSize = 64 # configuration of the Hadoop loader used by spark conf = {"textinputformat.record.delimiter": "\n", "mapreduce.input.fileinputformat.input.dir.recursive": "true", "mapred.max.split.size": str(defaultCombineSize*1024*1024) } def generateHashKey(filename): return hash(filename) def generateNameKey(filename): if filename.endswith(".meta"): return filename[:-5] else: return filename
Make contract that client needs to copy or not change value
import MCStoreBus from './mcstorebus'; class StateStoreService { /*@ngInject*/ constructor() { this.states = {}; this.bus = new MCStoreBus(); } updateState(key, value) { this.states[key] = angular.copy(value); let val = this.states[key]; this.bus.fireEvent(key, val); } getState(key) { if (_.has(this.states, key)) { return angular.copy(this.states[key]); } return null; } subscribe(state, fn) { return this.bus.subscribe(state, fn); } } angular.module('materialscommons').service('mcStateStore', StateStoreService);
import MCStoreBus from './mcstorebus'; class StateStoreService { /*@ngInject*/ constructor() { this.states = {}; this.bus = new MCStoreBus(); } updateState(key, value) { this.states[key] = angular.copy(value); let val = angular.copy(this.states[key]); this.bus.fireEvent(key, val); } getState(key) { if (_.has(this.states, key)) { return angular.copy(this.states[key]); } return null; } subscribe(state, fn) { return this.bus.subscribe(state, fn); } } angular.module('materialscommons').service('mcStateStore', StateStoreService);
Use random int, not int64 to select random words [#66747516]
package words import ( "math/rand" "strings" "time" ) type WordGenerator interface { Babble() string } type wordGenerator struct { numberGenerator *rand.Rand adjectives []string nouns []string } func (wg wordGenerator) Babble() (word string) { idx := int(wg.numberGenerator.Int()) % len(wg.adjectives) word = wg.adjectives[idx] + "-" idx = int(wg.numberGenerator.Int()) % len(wg.nouns) word += wg.nouns[idx] return } func NewWordGenerator() WordGenerator { adjectiveBytes, _ := Asset("src/words/dict/adjectives.txt") nounBytes, _ := Asset("src/words/dict/nouns.txt") source := rand.NewSource(time.Now().UnixNano()) return wordGenerator{ adjectives: strings.Split(string(adjectiveBytes), "\n"), nouns: strings.Split(string(nounBytes), "\n"), numberGenerator: rand.New(source), } }
package words import ( "math/rand" "strings" "time" ) type WordGenerator interface { Babble() string } type wordGenerator struct { source rand.Source adjectives []string nouns []string } func (wg wordGenerator) Babble() (word string) { idx := int(wg.source.Int63()) % len(wg.adjectives) word = wg.adjectives[idx] + "-" idx = int(wg.source.Int63()) % len(wg.nouns) word += wg.nouns[idx] return } func NewWordGenerator() WordGenerator { adjectiveBytes, _ := Asset("src/words/dict/adjectives.txt") nounBytes, _ := Asset("src/words/dict/nouns.txt") return wordGenerator{ adjectives: strings.Split(string(adjectiveBytes), "\n"), nouns: strings.Split(string(nounBytes), "\n"), source: rand.NewSource(time.Now().UnixNano()), } }
Change wording for voucher form test I was confused by what the test does, and had to ask @codeinthehole to explain. Hopefully made it's intention a bit clearer now.
from django import test from oscar.apps.dashboard.vouchers import forms class TestVoucherForm(test.TestCase): def test_doesnt_crash_on_empty_date_fields(self): """ There was a bug fixed in 02b3644 where the voucher form would raise an exception (instead of just failing validation) when being called with empty fields. This tests exists to prevent a regression. """ data = { 'code': '', 'name': '', 'start_date': '', 'end_date': '', 'benefit_range': '', 'benefit_type': 'Percentage', 'usage': 'Single use', } form = forms.VoucherForm(data=data) try: form.is_valid() except Exception as e: import traceback self.fail( "Exception raised while validating voucher form: %s\n\n%s" % ( e.message, traceback.format_exc()))
from django import test from oscar.apps.dashboard.vouchers import forms class TestVoucherForm(test.TestCase): def test_handles_empty_date_fields(self): data = {'code': '', 'name': '', 'start_date': '', 'end_date': '', 'benefit_range': '', 'benefit_type': 'Percentage', 'usage': 'Single use'} form = forms.VoucherForm(data=data) try: form.is_valid() except Exception as e: import traceback self.fail("Validating form failed: %s\n\n%s" % ( e.message, traceback.format_exc()))
Fix initial search results not working.
import React, { Component } from 'react'; import getWeatherData from '../../utils/apiUtils'; import Header from '../Header/Header'; import Welcome from '../Welcome/Welcome'; import WeatherFull from '../WeatherFull/WeatherFull'; import './Main.css'; export default class Main extends Component { constructor() { super(); this.state = { isDevelopment: true, }; } getLocation() { return localStorage.getItem('location'); } setLocation(location) { localStorage.setItem('location', location); } componentDidMount() { if (this.getLocation()) { getWeatherData(this.getLocation()).then((data) => { this.setState(data); }); } } changeLocation() { this.setLocation(document.querySelectorAll('.search-bar')[1].value); getWeatherData(this.getLocation()).then((data) => { this.setState(data); }); } toggleView(key) { this.setState({ [key]: !this.state[key] }); } render() { let content; if (this.getLocation()) { content = <WeatherFull state={this.state} toggleView={this.toggleView.bind(this)}/>; } else { content = <Welcome changeLocation={this.changeLocation.bind(this)}/>; } return ( <main> <Header changeLocation={this.changeLocation.bind(this)}/> {content} </main> ); } }
import React, { Component } from 'react'; import getWeatherData from '../../utils/apiUtils'; import Header from '../Header/Header'; import Welcome from '../Welcome/Welcome'; import WeatherFull from '../WeatherFull/WeatherFull'; import './Main.css'; export default class Main extends Component { constructor() { super(); this.state = { isDevelopment: true, }; } getLocation() { return localStorage.getItem('location'); } setLocation(location) { localStorage.setItem('location', location); } componentDidMount() { if (this.getLocation()) { getWeatherData(this.getLocation()).then((data) => { this.setState(data); }); } } changeLocation() { this.setLocation(document.querySelectorAll('.search-bar')[1].value); const data = getWeatherData(this.getLocation()); this.setState(data); } toggleView(key) { this.setState({ [key]: !this.state[key] }); } render() { let content; if (this.getLocation()) { content = <WeatherFull state={this.state} toggleView={this.toggleView.bind(this)}/>; } else { content = <Welcome changeLocation={this.changeLocation.bind(this)}/>; } return ( <main> <Header changeLocation={this.changeLocation.bind(this)}/> {content} </main> ); } }
Allow port to be changed
# -*- coding: utf-8 -*- import os import sys import argparse from logging.config import fileConfig from wsgiref.simple_server import make_server from paste.deploy import loadapp def main(): parser = argparse.ArgumentParser(description = __doc__) parser.add_argument('-p', '--port', action = 'store', default = 2000, help = "port to serve on") args = parser.parse_args() port = int(args.port) hostname = 'localhost' conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini') # If openfisca_web_api has been installed with --editable if not os.path.isfile(conf_file_path): import pkg_resources api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location conf_file_path = os.path.join(api_sources_path, 'development-france.ini') fileConfig(conf_file_path) application = loadapp('config:{}'.format(conf_file_path)) httpd = make_server(hostname, port, application) print u'Serving on http://{}:{}/'.format(hostname, port) try: httpd.serve_forever() except KeyboardInterrupt: return if __name__ == '__main__': sys.exit(main())
# -*- coding: utf-8 -*- import os import sys from logging.config import fileConfig from wsgiref.simple_server import make_server from paste.deploy import loadapp hostname = 'localhost' port = 2000 def main(): conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini') # If openfisca_web_api has been installed with --editable if not os.path.isfile(conf_file_path): import pkg_resources api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location conf_file_path = os.path.join(api_sources_path, 'development-france.ini') fileConfig(conf_file_path) application = loadapp('config:{}'.format(conf_file_path)) httpd = make_server(hostname, port, application) print u'Serving on http://{}:{}/'.format(hostname, port) try: httpd.serve_forever() except KeyboardInterrupt: return if __name__ == '__main__': sys.exit(main())
Change declaration of flot_graph function from using Twig_Function_Method to Twig_SimpleFunction
<?php namespace ACSEO\Bundle\GraphicBundle\Graphic\Flot\Twig\Extension; use Symfony\Component\HttpKernel\KernelInterface; class FlotTwigExtension extends \Twig_Extension { /** * {@inheritdoc} */ public function getFunctions() { return array( new \Twig_SimpleFunction( 'flot_graph', [$this, 'flotGraph'], [ 'is_safe' => array('html', 'js'), 'needs_environment' => true ] ), ); } /** * @param string $string * @return int */ public function flotGraph (\Twig_Environment $twig, \ACSEO\Bundle\GraphicBundle\Graphic\Flot\Type\AbstractType $graph) { return $twig->render('ACSEOGraphicBundle:Graphic\Flot:'.strtolower((new \ReflectionClass($graph))->getShortName()).'.html.twig', $graph->getView()); } /** * {@inheritdoc} */ public function getName() { return 'graphic_flot'; } }
<?php namespace ACSEO\Bundle\GraphicBundle\Graphic\Flot\Twig\Extension; use Symfony\Component\HttpKernel\KernelInterface; class FlotTwigExtension extends \Twig_Extension { /** * {@inheritdoc} */ public function getFunctions() { return array( 'flot_graph' => new \Twig_Function_Method($this, 'flotGraph', array( 'is_safe' => array('html', 'js'), 'needs_environment' => true ) ) ); } /** * @param string $string * @return int */ public function flotGraph (\Twig_Environment $twig, \ACSEO\Bundle\GraphicBundle\Graphic\Flot\Type\AbstractType $graph) { return $twig->render('ACSEOGraphicBundle:Graphic\Flot:'.strtolower((new \ReflectionClass($graph))->getShortName()).'.html.twig', $graph->getView()); } /** * {@inheritdoc} */ public function getName() { return 'graphic_flot'; } }
Add `ts_declaration` to the target kinds for the Intellij TypeScript kind provider. PiperOrigin-RevId: 443097363
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.typescript; import com.google.common.collect.ImmutableSet; import com.google.idea.blaze.base.model.primitives.Kind; import com.google.idea.blaze.base.model.primitives.LanguageClass; import com.google.idea.blaze.base.model.primitives.RuleType; class TypeScriptBlazeRules implements Kind.Provider { @Override public ImmutableSet<Kind> getTargetKinds() { return ImmutableSet.of( Kind.Provider.create("ng_module", LanguageClass.TYPESCRIPT, RuleType.LIBRARY), Kind.Provider.create("ts_library", LanguageClass.TYPESCRIPT, RuleType.LIBRARY), Kind.Provider.create("ts_declaration", LanguageClass.TYPESCRIPT, RuleType.LIBRARY), Kind.Provider.create("ts_config", LanguageClass.TYPESCRIPT, RuleType.BINARY)); } }
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.typescript; import com.google.common.collect.ImmutableSet; import com.google.idea.blaze.base.model.primitives.Kind; import com.google.idea.blaze.base.model.primitives.LanguageClass; import com.google.idea.blaze.base.model.primitives.RuleType; class TypeScriptBlazeRules implements Kind.Provider { @Override public ImmutableSet<Kind> getTargetKinds() { return ImmutableSet.of( Kind.Provider.create("ng_module", LanguageClass.TYPESCRIPT, RuleType.LIBRARY), Kind.Provider.create("ts_library", LanguageClass.TYPESCRIPT, RuleType.LIBRARY), Kind.Provider.create("ts_config", LanguageClass.TYPESCRIPT, RuleType.BINARY)); } }
Smallfix: Send print message to sys.stderr
# -*- coding: utf-8 -*- from __future__ import print_function import sys from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print("Patching APIView", file=sys.stderr) views.APIView = APIView
# -*- coding: utf-8 -*- from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print "Patching APIView" views.APIView = APIView
Clear search text after action
app.controller('SearchController', function($scope, $state, $q, KpmApi) { var self = this; /** * Callback when 'Return' key is pressed * Redirect to the package list page */ this.submit = function() { $state.go('packages', {search: this.searchText}); this.searchText = null; }; /** * Callback when a suggested item is selected * Redirect to the package view page */ this.itemSelected = function(item) { $state.go('package', {name: item.name}); this.searchText = null; }; /** * Autocomplete suggestion callback * @return promise */ this.querySearch = function(search) { var deferred = $q.defer(); KpmApi.get('packages', { named_like: search }) .success(function(data) { deferred.resolve(data); }); return deferred.promise; }; });
app.controller('SearchController', function($scope, $state, $q, KpmApi) { var self = this; /** * Callback when 'Return' key is pressed * Redirect to the package list page */ this.submit = function() { $state.go('packages', {search: this.searchText}); }; /** * Callback when a suggested item is selected * Redirect to the package view page */ this.itemSelected = function(item) { $state.go('package', {name: item.name}); }; /** * Autocomplete suggestion callback * @return promise */ this.querySearch = function(search) { var deferred = $q.defer(); KpmApi.get('packages', { named_like: search }) .success(function(data) { deferred.resolve(data); }); return deferred.promise; }; });
Use the progress reporter for karma
module.exports = function(config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/es5-shim.js', 'vendor/es5-sham.js', 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js' ], browsers: ['ChromeHeadlessNoSandbox'], client: { mocha: { reporter: 'html' } }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] } }, reporters: ['progress'] }); };
module.exports = function(config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/es5-shim.js', 'vendor/es5-sham.js', 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js' ], browsers: ['ChromeHeadlessNoSandbox'], client: { mocha: { reporter: 'html' } }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] } } }); };
Use PORT env var if exists, or fallback to port 3000.
#!/usr/bin/env node 'use strict'; var express = require('express') , app = express(); var kiss = require('kiss.io'), io = kiss(); var main = io.namespace('/'); var router = require('./router'); //! // ----------- CHAT ------------- // main.configure(function setLocals() { this.numUsers = 0; }); main.configure(function registerEvents() { this.use(router); }); main.on('connection', function(socket) { console.log('hello %s', socket.id); }); main.on('disconnection', function(socket) { console.log('bye bye %s', socket.id); }); //! // --------- EXPRESS APP --------- // app.use(express.static(__dirname + '/public')); //! // --------- KISS.IO SERVER ------- // io .attach(app) .listen(process.env.PORT || 3000, function() { console.log('Server listening at port 3000'); });
#!/usr/bin/env node 'use strict'; var express = require('express') , app = express(); var kiss = require('kiss.io'), io = kiss(); var main = io.namespace('/'); var router = require('./router'); //! // ----------- CHAT ------------- // main.configure(function setLocals() { this.numUsers = 0; }); main.configure(function registerEvents() { this.use(router); }); main.on('connection', function(socket) { console.log('hello %s', socket.id); }); main.on('disconnection', function(socket) { console.log('bye bye %s', socket.id); }); //! // --------- EXPRESS APP --------- // app.use(express.static(__dirname + '/public')); //! // --------- KISS.IO SERVER ------- // io .attach(app) .listen(3000, function() { console.log('Server listening at port 3000'); });
Check for nil timer pointer
package pooly import ( "net" "time" ) // Conn abstracts user connections that are part of a Pool. type Conn struct { iface interface{} timer *time.Timer closed bool } // Create a new connection container, wrapping up a user defined connection object. func NewConn(i interface{}) *Conn { return &Conn{iface: i} } // Interface returns an interface referring to the underlying user object. func (c *Conn) Interface() interface{} { return c.iface } // NetConn is a helper for underlying user objects that satisfy // the standard library net.Conn interface func (c *Conn) NetConn() net.Conn { return c.iface.(net.Conn) } func (c *Conn) isClosed() bool { return c.closed } func (c *Conn) setClosed() { c.closed = true } func (c *Conn) setIdle(p *Pool) { if p.IdleTimeout > 0 { c.timer = time.AfterFunc(p.IdleTimeout, func() { // The connection has been idle for too long, // send it to the garbage collector p.gc <- c }) } } func (c *Conn) setActive() bool { if c.timer != nil { return c.timer.Stop() } return true }
package pooly import ( "net" "time" ) // Conn abstracts user connections that are part of a Pool. type Conn struct { iface interface{} timer *time.Timer closed bool } // Create a new connection container, wrapping up a user defined connection object. func NewConn(i interface{}) *Conn { return &Conn{iface: i} } // Interface returns an interface referring to the underlying user object. func (c *Conn) Interface() interface{} { return c.iface } // NetConn is a helper for underlying user objects that satisfy // the standard library net.Conn interface func (c *Conn) NetConn() net.Conn { return c.iface.(net.Conn) } func (c *Conn) isClosed() bool { return c.closed } func (c *Conn) setClosed() { c.closed = true } func (c *Conn) setIdle(p *Pool) { if p.IdleTimeout > 0 { c.timer = time.AfterFunc(p.IdleTimeout, func() { // The connection has been idle for too long, // send it to the garbage collector p.gc <- c }) } } func (c *Conn) setActive() bool { return c.timer.Stop() }
Remove use of deprecated abstractproperty Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from gaphor.core.modeling import Element from gaphor.diagram.diagramtoolbox import ToolboxDefinition class Service(metaclass=ABCMeta): """Base interface for all services in Gaphor.""" @abstractmethod def shutdown(self) -> None: """Shutdown the services, free resources.""" class ActionProvider(metaclass=ABCMeta): """An action provider is a special service that provides actions (see gaphor/action.py).""" class ModelingLanguage(metaclass=ABCMeta): """A model provider is a special service that provides an entrypoint to a model implementation, such as UML, SysML, RAAML.""" @property @abstractmethod def name(self) -> str: """Human readable name of the model.""" @property @abstractmethod def toolbox_definition(self) -> ToolboxDefinition: """Get structure for the toolbox.""" @abstractmethod def lookup_element(self, name: str) -> type[Element] | None: """Look up a model element type (class) by name."""
from __future__ import annotations import abc from typing import TYPE_CHECKING if TYPE_CHECKING: from gaphor.core.modeling import Element from gaphor.diagram.diagramtoolbox import ToolboxDefinition class Service(metaclass=abc.ABCMeta): """Base interface for all services in Gaphor.""" @abc.abstractmethod def shutdown(self) -> None: """Shutdown the services, free resources.""" class ActionProvider(metaclass=abc.ABCMeta): """An action provider is a special service that provides actions (see gaphor/action.py).""" class ModelingLanguage(metaclass=abc.ABCMeta): """A model provider is a special service that provides an entrypoint to a model implementation, such as UML, SysML, RAAML.""" @abc.abstractproperty def name(self) -> str: """Human readable name of the model.""" @abc.abstractproperty def toolbox_definition(self) -> ToolboxDefinition: """Get structure for the toolbox.""" @abc.abstractmethod def lookup_element(self, name: str) -> type[Element] | None: """Look up a model element type (class) by name."""
Remove username and password from repository
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) USER = os.getenv('DATABASE_USER') PASWORD = os.getenv('DATABASE_PASSWORD') MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD) mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority' mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}
Update ApiIntegrationTest to have real AuthorisationService
<?php namespace CtiDigital\Configurator\Test\Unit\Component; use CtiDigital\Configurator\Model\Component\ApiIntegrations; use Magento\Integration\Model\IntegrationFactory; use Magento\Integration\Model\Oauth\TokenFactory; use Magento\Integration\Model\AuthorizationService; use Magento\Integration\Api\IntegrationServiceInterface; class ApiIntegrationsTest extends ComponentAbstractTestCase { protected $authorizationService; public function __construct(AuthorizationService $authorizationService) { parent::__construct(); $this->authorizationService = $authorizationService; } protected function componentSetUp() { $integrationFactory = $this->getMock(IntegrationFactory::class); $integrationService = $this->getMock(IntegrationServiceInterface::class); $authorizationService = $this->authorizationService; $tokenFactory = $this->getMock(TokenFactory::class); $this->component = new ApiIntegrations( $this->logInterface, $this->objectManager, $integrationFactory, $integrationService, $authorizationService, $tokenFactory ); $this->className = ApiIntegrations::class; } }
<?php namespace CtiDigital\Configurator\Test\Unit\Component; use CtiDigital\Configurator\Model\Component\ApiIntegrations; use Magento\Integration\Model\IntegrationFactory; use Magento\Integration\Model\Oauth\TokenFactory; use Magento\Integration\Model\AuthorizationService; use Magento\Integration\Api\IntegrationServiceInterface; class ApiIntegrationsTest extends ComponentAbstractTestCase { protected function componentSetUp() { $integrationFactory = $this->getMock(IntegrationFactory::class); $integrationService = $this->getMock(IntegrationServiceInterface::class); $authorizationService = $this->getMock(AuthorizationService::class); $tokenFactory = $this->getMock(TokenFactory::class); $this->component = new ApiIntegrations( $this->logInterface, $this->objectManager, $integrationFactory, $integrationService, $authorizationService, $tokenFactory ); $this->className = ApiIntegrations::class; } }
Add axis titles to visits chart, move legend to right side.
google.charts.load('current', {'packages':['corechart']}); function drawChart() { // Instead of the following, get the visits and days array from localStorage var visits = [5, 10, 7,20,10]; var data=[]; var Header= ['Day', 'Visits', { role: 'style' }]; data.push(Header); for (var i = 0; i < visits.length; i++) { var temp=[]; temp.push(i.toString()); temp.push(visits[i]); temp.push("blue"); // Line graph will change based on number of visits data.push(temp); } var chartdata = new google.visualization.arrayToDataTable(data); var options = { title: 'Site Visitors', legend: { position: 'right' }, hAxis: {title: 'Day' }, vAxis: {title: 'Number of Visits' }, }; var chart = new google.visualization.LineChart(document.getElementById('line-chart')); chart.draw(chartdata, options); } google.charts.setOnLoadCallback(drawChart);
google.charts.load('current', {'packages':['corechart']}); function drawChart() { // Instead of the following, get the visits and days array from localStorage var visits = [5, 10, 7,20,10]; var data=[]; var Header= ['Day', 'Visits', { role: 'style' }]; data.push(Header); for (var i = 0; i < visits.length; i++) { var temp=[]; temp.push(i.toString()); temp.push(visits[i]); temp.push("blue"); // Line graph will change based on number of visits data.push(temp); } var chartdata = new google.visualization.arrayToDataTable(data); var options = { title: 'Site Visitors', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('line-chart')); chart.draw(chartdata, options); } google.charts.setOnLoadCallback(drawChart);
Add authN/authZ. Start auth process in main()
from pyramid.config import Configurator from sqlalchemy import engine_from_config from pyramid.authorization import ACLAuthorizationPolicy from pyramid.authentication import AuthTktAuthenticationPolicy import os from .models import ( DBSession, Base, ) def make_session(settings): from sqlalchemy.orm import sessionmaker engine = engine_from_config(settings, 'sqlalchemy') Session = sessionmaker(bind=engine) return Session() def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine #authentication dummy_auth = os.environ.get(JOURNAL_AUTH_SECRET, 'testvalue') authentication_policy = AuthTktAuthenticationPolicy( secret= dummy_auth, hashalg='sha512', ) config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('detail_view', '/detail/{this_id}') config.add_route('add_view', '/add') config.add_route('edit_view', '/detail/{this_id}/edit') config.scan() return config.make_wsgi_app()
from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( DBSession, Base, ) def make_session(settings): from sqlalchemy.orm import sessionmaker engine = engine_from_config(settings, 'sqlalchemy') Session = sessionmaker(bind=engine) return Session() def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('detail_view', '/detail/{this_id}') config.add_route('add_view', '/add') config.add_route('edit_view', '/detail/{this_id}/edit') config.scan() return config.make_wsgi_app()
Set schedule status as OPEN when it is created
package com.jmb.springfactory.service.productionschedule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jmb.springfactory.dao.GenericMySQLService; import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService; import com.jmb.springfactory.exceptions.ServiceLayerException; import com.jmb.springfactory.model.bo.BusinessObjectBase; import com.jmb.springfactory.model.dto.ProductionScheduleDto; import com.jmb.springfactory.model.entity.ProductionSchedule; import com.jmb.springfactory.model.enumeration.ProductionScheduleStateEnum; import com.jmb.springfactory.service.GenericServiceImpl; @Service public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto, BusinessObjectBase, Integer> implements ProductionScheduleService { @Autowired private ProductionScheduleMySQLService productionScheduleMySQLService; @Override public GenericMySQLService<ProductionSchedule, Integer> genericDao() { return productionScheduleMySQLService; } @Override public Class<? extends ProductionSchedule> getClazz() { return ProductionSchedule.class; } @Override public Class<? extends ProductionScheduleDto> getDtoClazz() { return ProductionScheduleDto.class; } @Override public Class<? extends BusinessObjectBase> getBoClazz() { return BusinessObjectBase.class; } @Override public ProductionScheduleDto save(ProductionScheduleDto schedule) throws ServiceLayerException { schedule.setState(ProductionScheduleStateEnum.OPEN.name()); return super.save(schedule); } }
package com.jmb.springfactory.service.productionschedule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jmb.springfactory.dao.GenericMySQLService; import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService; import com.jmb.springfactory.model.bo.BusinessObjectBase; import com.jmb.springfactory.model.dto.ProductionScheduleDto; import com.jmb.springfactory.model.entity.ProductionSchedule; import com.jmb.springfactory.service.GenericServiceImpl; @Service public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto, BusinessObjectBase, Integer> implements ProductionScheduleService { @Autowired private ProductionScheduleMySQLService productionScheduleMySQLService; @Override public GenericMySQLService<ProductionSchedule, Integer> genericDao() { return productionScheduleMySQLService; } @Override public Class<? extends ProductionSchedule> getClazz() { return ProductionSchedule.class; } @Override public Class<? extends ProductionScheduleDto> getDtoClazz() { return ProductionScheduleDto.class; } @Override public Class<? extends BusinessObjectBase> getBoClazz() { return BusinessObjectBase.class; } }
Remove --cookies-file option for now. I can't figure out if there are any public APIs for working with the binary cookie formats that PhantomJS now uses. Not sure if there are any functions exposed that would let us interpret them correctly, and attempting to parse cookie binaries might not be super useful.
#!/usr/bin/env phantomjs /** * PhantomJS-based web performance metrics collector * * Usage: * ./phantomas.js * --url=<page to check> * [--format=json|csv|plain] * [--timeout=5] * ]--viewport=<width>x<height>] * [--verbose] * [--silent] * [--log=<log file>] * [--modules=moduleOne,moduleTwo] * [--user-agent='Custom user agent'] * [--config='JSON config file'] * [--cookie='bar=foo;domain=url'] * [--no-externals] * [--allow-domain='domain,domain'] * [--block-domain='domain,domain'] */ var args = require('system').args, // get absolute path (useful when phantomas is installed globally) dir = require('fs').readLink(args[0]).replace(/phantomas.js$/, '') || '.', // parse script arguments params = require(dir + '/lib/args').parse(args), phantomas = require(dir + '/core/phantomas'), instance; // run phantomas instance = new phantomas(params); try { instance.run(); } catch(ex) { console.log('phantomas v' + phantomas.version + ' failed with an error:'); console.log(ex); phantom.exit(1); }
#!/usr/bin/env phantomjs /** * PhantomJS-based web performance metrics collector * * Usage: * ./phantomas.js * --url=<page to check> * [--format=json|csv|plain] * [--timeout=5] * ]--viewport=<width>x<height>] * [--verbose] * [--silent] * [--log=<log file>] * [--modules=moduleOne,moduleTwo] * [--user-agent='Custom user agent'] * [--config='JSON config file'] * [--cookie='bar=foo;domain=url'] * [--cookies-file=/path/to/cookies.txt] * [--no-externals] * [--allow-domain='domain,domain'] * [--block-domain='domain,domain'] */ var args = require('system').args, // get absolute path (useful when phantomas is installed globally) dir = require('fs').readLink(args[0]).replace(/phantomas.js$/, '') || '.', // parse script arguments params = require(dir + '/lib/args').parse(args), phantomas = require(dir + '/core/phantomas'), instance; // run phantomas instance = new phantomas(params); try { instance.run(); } catch(ex) { console.log('phantomas v' + phantomas.version + ' failed with an error:'); console.log(ex); phantom.exit(1); }
Add envirvonment variable for gh-pages
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'production') { ENV.baseURL = 'ember-drag-drop' } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Increase the version number due this bugfix
#!/usr/bin/env python import setuptools version = '3.3.1' setuptools.setup( name="alerta-mailer", version=version, description='Send emails from Alerta', url='https://github.com/alerta/alerta-contrib', license='MIT', author='Nick Satterly', author_email='nick.satterly@theguardian.com', py_modules=['mailer'], data_files=[('.', ['email.tmpl', 'email.html.tmpl'])], install_requires=[ 'alerta', 'kombu', 'redis', 'jinja2' ], include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'alerta-mailer = mailer:main' ] }, keywords="alerta monitoring mailer sendmail smtp", classifiers=[ 'Topic :: System :: Monitoring', ] )
#!/usr/bin/env python import setuptools version = '3.3.0' setuptools.setup( name="alerta-mailer", version=version, description='Send emails from Alerta', url='https://github.com/alerta/alerta-contrib', license='MIT', author='Nick Satterly', author_email='nick.satterly@theguardian.com', py_modules=['mailer'], data_files=[('.', ['email.tmpl', 'email.html.tmpl'])], install_requires=[ 'alerta', 'kombu', 'redis', 'jinja2' ], include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'alerta-mailer = mailer:main' ] }, keywords="alerta monitoring mailer sendmail smtp", classifiers=[ 'Topic :: System :: Monitoring', ] )
Remove default email sender from CozyLAN config Brand-specific emails should always use the sender from the brand-specific email configuration.
# Examplary development configuration for the "CozyLAN" demo site DEBUG = True SECRET_KEY = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' SESSION_COOKIE_SECURE = False SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://byceps:boioioing@127.0.0.1/byceps' REDIS_URL = 'redis://127.0.0.1:6379/0' APP_MODE = 'site' SITE_ID = 'cozylan' MAIL_DEBUG = True MAIL_SUPPRESS_SEND = False MAIL_TRANSPORT = 'logging' DEBUG_TOOLBAR_ENABLED = True STYLE_GUIDE_ENABLED = True
# Examplary development configuration for the "CozyLAN" demo site DEBUG = True SECRET_KEY = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' SESSION_COOKIE_SECURE = False SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://byceps:boioioing@127.0.0.1/byceps' REDIS_URL = 'redis://127.0.0.1:6379/0' APP_MODE = 'site' SITE_ID = 'cozylan' MAIL_DEBUG = True MAIL_DEFAULT_SENDER = 'CozyLAN <noreply@cozylan.example>' MAIL_SUPPRESS_SEND = False MAIL_TRANSPORT = 'logging' DEBUG_TOOLBAR_ENABLED = True STYLE_GUIDE_ENABLED = True
Increment version number to 0.4.0 This should have been done a while ago... many changes including comprehensive documentation, support for lat-lon grids, bug fixes, etc.
__version__ = '0.4.0' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.domain.initial import column_state, surface_state from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
__version__ = '0.3.2' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.domain.initial import column_state, surface_state from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
Use NewRandom instead of NewUUID NewUUID is based on a timestamp, while NewRandom is based on a PRNG, like it should be.
package osin import ( "encoding/base64" "strings" "code.google.com/p/go-uuid/uuid" ) // AuthorizeTokenGenDefault is the default authorization token generator type AuthorizeTokenGenDefault struct { } func removePadding(token string) string { return strings.TrimRight(token, "=") } // GenerateAuthorizeToken generates a base64-encoded UUID code func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) { token := uuid.NewRandom() return removePadding(base64.URLEncoding.EncodeToString([]byte(token))), nil } // AccessTokenGenDefault is the default authorization token generator type AccessTokenGenDefault struct { } // GenerateAccessToken generates base64-encoded UUID access and refresh tokens func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error) { token := uuid.NewRandom() accesstoken = removePadding(base64.URLEncoding.EncodeToString([]byte(token))) if generaterefresh { rtoken := uuid.NewRandom() refreshtoken = removePadding(base64.URLEncoding.EncodeToString([]byte(rtoken))) } return }
package osin import ( "encoding/base64" "strings" "code.google.com/p/go-uuid/uuid" ) // AuthorizeTokenGenDefault is the default authorization token generator type AuthorizeTokenGenDefault struct { } func removePadding(token string) string { return strings.TrimRight(token, "=") } // GenerateAuthorizeToken generates a base64-encoded UUID code func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) { token := uuid.NewUUID() return removePadding(base64.URLEncoding.EncodeToString([]byte(token))), nil } // AccessTokenGenDefault is the default authorization token generator type AccessTokenGenDefault struct { } // GenerateAccessToken generates base64-encoded UUID access and refresh tokens func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error) { token := uuid.NewUUID() accesstoken = removePadding(base64.URLEncoding.EncodeToString([]byte(token))) if generaterefresh { rtoken := uuid.NewUUID() refreshtoken = removePadding(base64.URLEncoding.EncodeToString([]byte(rtoken))) } return }
Use the Mojang API directly; reduces overhead.
""" Username to UUID Converts a Minecraft username to it's UUID equivalent. Uses the official Mojang API to fetch player data. """ import http.client import json class UsernameToUUID: def __init__(self, username): self.username = username def get_uuid(self, timestamp=None): """ Get the UUID of the player. Parameters ---------- timestamp : long integer The time at which the player used this name, expressed as a Unix timestamp. """ get_args = "" if timestamp is None else "?at=" + str(timestamp) http_conn = http.client.HTTPSConnection("api.mojang.com"); http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args, headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'}); response = http_conn.getresponse().read().decode("utf-8") if (not response and timestamp is None): # No response & no timestamp return self.get_uuid(0) # Let's retry with the Unix timestamp 0. if (not response): # No response (player probably doesn't exist) return "" json_data = json.loads(response) uuid = json_data['id'] return uuid
""" Username to UUID Converts a Minecraft username to it's UUID equivalent. Parses http://www.lb-stuff.com/Minecraft-Name-History output to retrieve the UUID of an old name that's no longer in use. """ import http.client from bs4 import BeautifulSoup class UsernameToUUID: def __init__(self, username): self.username = username def get_uuid(self): """ Get the UUID of the player. """ httpConn = http.client.HTTPConnection("www.lb-stuff.com"); httpConn.request("GET", "/Minecraft-Name-History?user=" + self.username); response = httpConn.getresponse().read() soup = BeautifulSoup(response) return soup.body.findAll('p')[1].findAll('code')[1].text
Add console statement for testing.
var Backbone = require('backbone'); var $ = require("jquery"); var Router = require('./router'); var PlayerView = require('./views/playerView'); var NavView = require('./views/navView'); window.app = { airtimeURL: "http://airtime.frequency.asia", init: function () { this.views = { playerView: new PlayerView({ el: $("#player-container"), }), navView: new NavView({ el: $("#nav-container"), }), } this.views.playerView.render(); this.views.navView.render(); // Create and fire up the router this.router = new Router(); this.router.on("route", function(route, params) { window.app.views.navView.setActivePage(); }); Backbone.history.start(); } }; window.app.init(); console.log("Frequency Asia v1.1")
var Backbone = require('backbone'); var $ = require("jquery"); var Router = require('./router'); var PlayerView = require('./views/playerView'); var NavView = require('./views/navView'); window.app = { airtimeURL: "http://airtime.frequency.asia", init: function () { this.views = { playerView: new PlayerView({ el: $("#player-container"), }), navView: new NavView({ el: $("#nav-container"), }), } this.views.playerView.render(); this.views.navView.render(); // Create and fire up the router this.router = new Router(); this.router.on("route", function(route, params) { window.app.views.navView.setActivePage(); }); Backbone.history.start(); } }; window.app.init();
Add identity gard before firing layout change
import Vue from "vue" export default { name: 'AppPage', props: { layout: { type: String, required: true, validator: [].includes.bind(["standard", "empty"]) } }, created() { let component = components[this.layout] if (!Vue.options.components[component.name]) { Vue.component( component.name, component, ); } if (this.$parent.layout !== component) { this.$parent.$emit('update:layout', component); } }, render(h) { return this.$slots.default ? this.$slots.default[0] : h(); }, } const components = { "standard": () => import("./layout-standard"), "empty": () => import("./layout-empty") }
import Vue from "vue" export default { name: 'AppPage', props: { layout: { type: String, required: true, validator: [].includes.bind(["standard", "empty"]) } }, created() { let component = components[this.layout] if (!Vue.options.components[component.name]) { Vue.component( component.name, component, ); } this.$parent.$emit('update:layout', component); }, render(h) { return this.$slots.default ? this.$slots.default[0] : h(); }, } const components = { "standard": () => import("./layout-standard"), "empty": () => import("./layout-empty") }
Remove varNameRegExp since it's never used;
/* * Copyright 2011 eBay Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // var varNameRegExp = /^[A-Za-z_][A-Za-z0-9_\.]*$/; function AssignNode(props) { AssignNode.$super.call(this); if (props) { this.setProperties(props); } } AssignNode.prototype = { doGenerateCode: function (template) { var varName = this.getProperty('var'); var value = this.getProperty('value'); if (!varName) { this.addError('"var" attribute is required'); } if (!value) { this.addError('"value" attribute is required'); } if (varName) { template.statement(varName + '=' + value + ';'); } } }; module.exports = AssignNode;
/* * Copyright 2011 eBay Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var varNameRegExp = /^[A-Za-z_][A-Za-z0-9_\.]*$/; function AssignNode(props) { AssignNode.$super.call(this); if (props) { this.setProperties(props); } } AssignNode.prototype = { doGenerateCode: function (template) { var varName = this.getProperty('var'); var value = this.getProperty('value'); if (!varName) { this.addError('"var" attribute is required'); } if (!value) { this.addError('"value" attribute is required'); } if (varName) { template.statement(varName + '=' + value + ';'); } } }; module.exports = AssignNode;
Remove duplicate line from suggested PowerDNS config
<?php ## ## Copyright 2013-2017 Opera Software AS ## ## 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. ## $active_user = $this->get('active_user'); ?> <h1>DNS server communication failure</h1> <p>The DNS server is not responding.</p> <?php if(!is_null($active_user) && $active_user->admin) { ?> <p>Make sure that the following PowerDNS parameters are set correctly in <code>pdns.conf</code>:</p> <pre>webserver=yes webserver-address=... webserver-allow-from=... webserver-port=... api=yes api-key=...</pre> <p>Reload PowerDNS after making changes to this file.</p> <p>Also check the values set in the <code>[powerdns]</code> section of the DNS UI configuration file (<code>config/config.ini</code>).</p> <?php } ?>
<?php ## ## Copyright 2013-2017 Opera Software AS ## ## 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. ## $active_user = $this->get('active_user'); ?> <h1>DNS server communication failure</h1> <p>The DNS server is not responding.</p> <?php if(!is_null($active_user) && $active_user->admin) { ?> <p>Make sure that the following PowerDNS parameters are set correctly in <code>pdns.conf</code>:</p> <pre>webserver=yes webserver=yes webserver-address=... webserver-allow-from=... webserver-port=... api=yes api-key=...</pre> <p>Reload PowerDNS after making changes to this file.</p> <p>Also check the values set in the <code>[powerdns]</code> section of the DNS UI configuration file (<code>config/config.ini</code>).</p> <?php } ?>
Enhance debug output for retry strategies Retry strategies outputs the retryable type [#129348495](https://www.pivotaltracker.com/story/show/129348495) Signed-off-by: Beyhan Veli <0702de361e3c91d973ce2c0ee3e34845ebaf95e6@sap.com>
package retrystrategy import ( "reflect" "time" boshlog "github.com/cloudfoundry/bosh-utils/logger" ) type attemptRetryStrategy struct { maxAttempts int delay time.Duration retryable Retryable logger boshlog.Logger logTag string } func NewAttemptRetryStrategy( maxAttempts int, delay time.Duration, retryable Retryable, logger boshlog.Logger, ) RetryStrategy { return &attemptRetryStrategy{ maxAttempts: maxAttempts, delay: delay, retryable: retryable, logger: logger, logTag: "attemptRetryStrategy", } } func (s *attemptRetryStrategy) Try() error { var err error var isRetryable bool for i := 0; i < s.maxAttempts; i++ { s.logger.Debug(s.logTag, "Making attempt #%d for %s", i, reflect.TypeOf(s.retryable)) isRetryable, err = s.retryable.Attempt() if err == nil { return nil } if !isRetryable { return err } time.Sleep(s.delay) } return err }
package retrystrategy import ( "time" boshlog "github.com/cloudfoundry/bosh-utils/logger" ) type attemptRetryStrategy struct { maxAttempts int delay time.Duration retryable Retryable logger boshlog.Logger logTag string } func NewAttemptRetryStrategy( maxAttempts int, delay time.Duration, retryable Retryable, logger boshlog.Logger, ) RetryStrategy { return &attemptRetryStrategy{ maxAttempts: maxAttempts, delay: delay, retryable: retryable, logger: logger, logTag: "attemptRetryStrategy", } } func (s *attemptRetryStrategy) Try() error { var err error var isRetryable bool for i := 0; i < s.maxAttempts; i++ { s.logger.Debug(s.logTag, "Making attempt #%d", i) isRetryable, err = s.retryable.Attempt() if err == nil { return nil } if !isRetryable { return err } time.Sleep(s.delay) } return err }
fix: Remove the dependence on path.
<?php /** * CodeIgniter PHP-Development Server Rewrite Rules * * This script works with the CLI serve command to help run a seamless * development server based around PHP's built-in development * server. This file simply tries to mimic Apache's mod_rewrite * functionality so the site will operate as normal. * */ // @codeCoverageIgnoreStart // Avoid this file run when listing commands if (php_sapi_name() === 'cli') { return; } // If we're serving the site locally, then we need // to let the application know that we're in development mode $_SERVER['CI_ENVIRONMENT'] = 'development'; $uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); // Front Controller path - expected to be in the default folder $fcpath = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR; // Full path $path = $fcpath . ltrim($uri, '/'); // If $path is an existing file or folder within the public folder // then let the request handle it like normal. if ($uri !== '/' && (is_file($path) || is_dir($path))) { return false; } // Otherwise, we'll load the index file and let // the framework handle the request from here. require_once $fcpath . 'index.php'; // @codeCoverageIgnoreEnd
<?php /** * CodeIgniter PHP-Development Server Rewrite Rules * * This script works with the CLI serve command to help run a seamless * development server based around PHP's built-in development * server. This file simply tries to mimic Apache's mod_rewrite * functionality so the site will operate as normal. * */ // @codeCoverageIgnoreStart // Avoid this file run when listing commands if (php_sapi_name() === 'cli') { return; } // If we're serving the site locally, then we need // to let the application know that we're in development mode $_SERVER['CI_ENVIRONMENT'] = 'development'; $uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); // Front Controller path - expected to be in the default folder $fcpath = realpath(__DIR__ . '/../../../public') . DIRECTORY_SEPARATOR; // Full path $path = $fcpath . ltrim($uri, '/'); // If $path is an existing file or folder within the public folder // then let the request handle it like normal. if ($uri !== '/' && (is_file($path) || is_dir($path))) { return false; } // Otherwise, we'll load the index file and let // the framework handle the request from here. require_once $fcpath . 'index.php'; // @codeCoverageIgnoreEnd
Sort letters by series, volume, number Resolves: ADWD-2212
import Ember from 'ember'; import Solr from '../mixins/solr'; export default Ember.Route.extend(Solr, { intl: Ember.inject.service(), model() { return this.loadAllLettersInVolume(); }, beforeModel() { // define the app's runtime locale // For example, here you would maybe do an API lookup to resolver // which locale the user should be targeted and perhaps lazily // load translations using XHR and calling intl's `addTranslation`/`addTranslations` // method with the results of the XHR request this.get('intl').setLocale('de-de'); }, renderTemplate() { this.render(); this.render('nav', { into: 'application', outlet: 'nav' }); }, loadAllLettersInVolume() { return this.query('type:brief', {fl: 'id, band, reihe, brief_nummer', sort: 'reihe asc, band asc, brief_nummer asc'}).then( (json) => { if ( json.response.docs.length > 0 ) { return json.response.docs; } }); }, });
import Ember from 'ember'; import Solr from '../mixins/solr'; export default Ember.Route.extend(Solr, { intl: Ember.inject.service(), model() { return this.loadAllLettersInVolume(); }, beforeModel() { // define the app's runtime locale // For example, here you would maybe do an API lookup to resolver // which locale the user should be targeted and perhaps lazily // load translations using XHR and calling intl's `addTranslation`/`addTranslations` // method with the results of the XHR request this.get('intl').setLocale('de-de'); }, renderTemplate() { this.render(); this.render('nav', { into: 'application', outlet: 'nav' }); }, loadAllLettersInVolume() { return this.query('type:brief', {fl: 'id, band, reihe, brief_nummer', sort: 'brief_nummer asc'}).then( (json) => { if ( json.response.docs.length > 0 ) { return json.response.docs; } }); }, });
Add status code to error message
# -*- coding: utf-8 -*- import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s, %s" % (r.status_code, r.text)) try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url)
# -*- coding: utf-8 -*- import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % r.text) try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url)
Fix CoFH-locked drawers crashing clients
package com.jaquadro.minecraft.storagedrawers.integration.thermalfoundation; import com.jaquadro.minecraft.storagedrawers.api.security.ISecurityProvider; import com.jaquadro.minecraft.storagedrawers.api.storage.attribute.IProtectable; import com.jaquadro.minecraft.storagedrawers.integration.ThermalFoundation; import com.jaquadro.minecraft.storagedrawers.security.DefaultSecurityProvider; import com.mojang.authlib.GameProfile; public class CoFHSecurityProvider implements ISecurityProvider { ThermalFoundation foundation; private DefaultSecurityProvider defaultProvider = new DefaultSecurityProvider(); public CoFHSecurityProvider (ThermalFoundation foundation) { this.foundation = foundation; } @Override public String getProviderID () { return "cofh"; } @Override public boolean hasOwnership (GameProfile profile, IProtectable target) { return defaultProvider.hasOwnership(profile, target); } @Override public boolean hasAccess (GameProfile profile, IProtectable target) { if (target.getOwner() == null) return true; GameProfile ownerProfile = (profile.getId().equals(target.getOwner())) ? new GameProfile(profile.getId(), profile.getName()) : new GameProfile(target.getOwner(), null); return foundation.playerHasAccess(profile.getName(), ownerProfile); } }
package com.jaquadro.minecraft.storagedrawers.integration.thermalfoundation; import com.jaquadro.minecraft.storagedrawers.api.security.ISecurityProvider; import com.jaquadro.minecraft.storagedrawers.api.storage.attribute.IProtectable; import com.jaquadro.minecraft.storagedrawers.integration.ThermalFoundation; import com.jaquadro.minecraft.storagedrawers.security.DefaultSecurityProvider; import com.mojang.authlib.GameProfile; import net.minecraft.server.MinecraftServer; public class CoFHSecurityProvider implements ISecurityProvider { ThermalFoundation foundation; private DefaultSecurityProvider defaultProvider = new DefaultSecurityProvider(); public CoFHSecurityProvider (ThermalFoundation foundation) { this.foundation = foundation; } @Override public String getProviderID () { return "cofh"; } @Override public boolean hasOwnership (GameProfile profile, IProtectable target) { return defaultProvider.hasOwnership(profile, target); } @Override public boolean hasAccess (GameProfile profile, IProtectable target) { if (target.getOwner() == null) return true; GameProfile ownerProfile = MinecraftServer.getServer().func_152358_ax().func_152652_a(target.getOwner()); if (ownerProfile == null) return false; return foundation.playerHasAccess(profile.getName(), ownerProfile); } }
Add actual call to the jumping function.
var arrayContainsObject = require('./array-contains-object'); var collisionObstacles = []; var Jump = require('./../jump'); var hypotenuse = require('./hypotenuse'); var isColliding = function(skier, obstacle) { if (hypotenuse(skier, obstacle) < skier.width && obstacle instanceof Jump) { jump(skier); } else if (hypotenuse(skier, obstacle) < skier.width && skier.jumping === false) { crashed(skier, obstacle, collisionObstacles); } }; function crashed(skier, obstacle, collisionObstacles) { skier.crashed = true; if (arrayContainsObject(obstacle, collisionObstacles) === false) { collisionObstacles.push(obstacle); skier.lives -= 1; } document.onkeydown=function(){ skier.crashed = false; }; } function jump(skier) { skier.jumping = true; if (cancelableStateTimeout) { clearTimeout(cancelableStateTimeout); } var cancelableStateTimeout = setTimeout(function() { skier.jumping = false; }, 2000); } module.exports = isColliding;
var arrayContainsObject = require('./array-contains-object'); var collisionObstacles = []; var Jump = require('./../jump'); var hypotenuse = require('./hypotenuse'); var isColliding = function(skier, obstacle) { if (hypotenuse(skier, obstacle) < skier.width && obstacle instanceof Jump) { } else if (hypotenuse(skier, obstacle) < skier.width && skier.jumping === false) { crashed(skier, obstacle, collisionObstacles); } }; function crashed(skier, obstacle, collisionObstacles) { skier.crashed = true; if (arrayContainsObject(obstacle, collisionObstacles) === false) { collisionObstacles.push(obstacle); skier.lives -= 1; } document.onkeydown=function(){ skier.crashed = false; }; } function jump(skier) { skier.jumping = true; if (cancelableStateTimeout) { clearTimeout(cancelableStateTimeout); } var cancelableStateTimeout = setTimeout(function() { skier.jumping = false; }, 2000); } module.exports = isColliding;
Add timeout to downloading custom background images
import asyncio import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, asyncio.TimeoutError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: async with session.get(url, timeout=10) as response: if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: message = str(e).strip("() ") or e.__class__.__name__ logger.error(f"Invalid response from {url}: {message}") return False
import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, UnicodeError, ) async def download(url: str, path: AsyncPath) -> bool: async with aiohttp.ClientSession() as session: try: async with session.get(url) as response: if response.status == 200: f = await aiofiles.open(path, mode="wb") # type: ignore await f.write(await response.read()) await f.close() return True logger.error(f"{response.status} response from {url}") except EXCEPTIONS as e: message = str(e).strip("() ") logger.error(f"Invalid response from {url}: {message}") return False
Enable embedding/saving to basket "box" components in BackendUtils
package gr.demokritos.iit.ydsapi.model; import java.util.HashSet; import java.util.Set; /** * accepted component types. * * @author George K. <gkiom@iit.demokritos.gr> */ public enum ComponentType { LINE("line"), SCATTER("scatter"), BUBBLE("bubble"), PIE("pie"), BAR("bar"), TREE("tree"), MAP("map"), GRID("grid"), INFO("info"), BOX("box"), RESULT("result"), RESULTSET("resultset"); private final String type; private ComponentType(String type) { this.type = type; } public String getDecl() { return type; } public static final Set<String> ACCEPTED = new HashSet(); static { ACCEPTED.add(LINE.getDecl()); ACCEPTED.add(SCATTER.getDecl()); ACCEPTED.add(BUBBLE.getDecl()); ACCEPTED.add(PIE.getDecl()); ACCEPTED.add(BAR.getDecl()); ACCEPTED.add(TREE.getDecl()); ACCEPTED.add(MAP.getDecl()); ACCEPTED.add(GRID.getDecl()); ACCEPTED.add(INFO.getDecl()); ACCEPTED.add(BOX.getDecl()); ACCEPTED.add(RESULT.getDecl()); ACCEPTED.add(RESULTSET.getDecl()); } }
package gr.demokritos.iit.ydsapi.model; import java.util.HashSet; import java.util.Set; /** * accepted component types. * * @author George K. <gkiom@iit.demokritos.gr> */ public enum ComponentType { LINE("line"), SCATTER("scatter"), BUBBLE("bubble"), PIE("pie"), BAR("bar"), TREE("tree"), MAP("map"), GRID("grid"), INFO("info"), RESULT("result"), RESULTSET("resultset"); private final String type; private ComponentType(String type) { this.type = type; } public String getDecl() { return type; } public static final Set<String> ACCEPTED = new HashSet(); static { ACCEPTED.add(LINE.getDecl()); ACCEPTED.add(SCATTER.getDecl()); ACCEPTED.add(BUBBLE.getDecl()); ACCEPTED.add(PIE.getDecl()); ACCEPTED.add(BAR.getDecl()); ACCEPTED.add(TREE.getDecl()); ACCEPTED.add(MAP.getDecl()); ACCEPTED.add(GRID.getDecl()); ACCEPTED.add(INFO.getDecl()); ACCEPTED.add(RESULT.getDecl()); ACCEPTED.add(RESULTSET.getDecl()); } }
chore: Fix year and link in code comment
package floydwarshall // Grafos - Algoritmo de Floyd-Warshall em GO // Douglas Oliveira - 2022 // https://github.com/xDouglas90 // link Go PlayGround: https://go.dev/play/p/tIRTHkNf7Fz // Algoritmo de Floyd-Warshall func FloydWarshall(graph [][]int) [][]int { // Inicializa a matriz de distancias dist := make([][]int, len(graph)) for i := range dist { dist[i] = make([]int, len(graph)) copy(dist[i], graph[i]) } // Percorre os vértices for k := 0; k < len(graph); k++ { // Percorre as linhas for i := 0; i < len(graph); i++ { // Percorre as colunas for j := 0; j < len(graph); j++ { // Verifica se o caminho passando pelo vértice k é menor if dist[i][k]+dist[k][j] < dist[i][j] { dist[i][j] = dist[i][k] + dist[k][j] } } } } return dist }
package floydwarshall // Grafos - Algoritmo de Floyd-Warshall em GO // Douglas Oliveira - 2021 // https://github.com/xDouglas90 // link Go PlayGround: https://go.dev/play/p/4fOHMMxWxiy // Algoritmo de Floyd-Warshall func FloydWarshall(graph [][]int) [][]int { // Inicializa a matriz de distancias dist := make([][]int, len(graph)) for i := range dist { dist[i] = make([]int, len(graph)) copy(dist[i], graph[i]) } // Percorre os vértices for k := 0; k < len(graph); k++ { // Percorre as linhas for i := 0; i < len(graph); i++ { // Percorre as colunas for j := 0; j < len(graph); j++ { // Verifica se o caminho passando pelo vértice k é menor if dist[i][k]+dist[k][j] < dist[i][j] { dist[i][j] = dist[i][k] + dist[k][j] } } } } return dist }
Use plumber to prenvent babel from crashing gulp
/* eslint-disable import/no-commonjs */ const fs = require('fs'); const gulp = require('gulp'); const watch = require('gulp-watch'); const plumber = require('gulp-plumber'); const babel = require('gulp-babel'); const del = require('del'); const babelRc = JSON.parse(fs.readFileSync('./.babelrc.node')); gulp.task('clean', () => { return del(['./lib']); }); gulp.task('copy', ['clean'], () => { return gulp .src('./src/**/*') .pipe(gulp.dest('./lib')); }); gulp.task('build', ['copy'], () => { return gulp.src('./src/**/*.js') .pipe(plumber()) .pipe(babel(babelRc)) .pipe(plumber.stop()) .pipe(gulp.dest('./lib')); }); gulp.task('build:watch', ['build'], () => { return watch('./src/**/*', () => gulp.start('build')); });
/* eslint-disable import/no-commonjs */ const fs = require('fs'); const gulp = require('gulp'); const babel = require('gulp-babel'); const del = require('del'); const babelRc = JSON.parse(fs.readFileSync('./.babelrc.node')); gulp.task('clean', () => { return del(['./lib']); }); gulp.task('copy', ['clean'], () => { return gulp .src('./src/**/*') .pipe(gulp.dest('./lib')); }); gulp.task('build', ['copy'], () => { return gulp.src('./src/**/*.js') .pipe(babel(babelRc)) .pipe(gulp.dest('./lib')); }); gulp.task('build:watch', ['build'], () => { return gulp.watch('./src/**/*', ['build']); });
Add the length into a simplified video
var exports = {}; exports.simplePrint = function(video) { return `**${video.title}**`; }; exports.prettyPrint = function(video) { try { viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ','); } catch (e) { viewCount = 'unknown'; } return `**${video.title}** by **${video.author}** *(${viewCount} views)* [${exports.prettyTime(video.length_seconds*1000)}]`; }; exports.prettyPrintWithUser = function(video) { return exports.prettyPrint(video) + `, added by <@${video.userId}>`; }; exports.simplify = function(video, vid) { return { vid: vid, title: video.title, author: video.author, view_count: video.view_count, length_seconds: video.length_seconds }; }; exports.prettyTime = function(ms) { var seconds = ms / 1000; var actualSeconds = Math.ceil(seconds % 60); var paddedSeconds = String('00' + actualSeconds).slice(-2); var minutes = Math.round((seconds - actualSeconds) / 60); return `${minutes}:${paddedSeconds}`; }; module.exports = exports;
var exports = {}; exports.simplePrint = function(video) { return `**${video.title}**`; }; exports.prettyPrint = function(video) { try { viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ','); } catch (e) { viewCount = 'unknown'; } return `**${video.title}** by **${video.author}** *(${viewCount} views)* [${exports.prettyTime(video.length_seconds*1000)}]`; }; exports.prettyPrintWithUser = function(video) { return exports.prettyPrint(video) + `, added by <@${video.userId}>`; }; exports.simplify = function(video, vid) { return { vid: vid, title: video.title, author: video.author, view_count: video.view_count, }; }; exports.prettyTime = function(ms) { var seconds = ms / 1000; var actualSeconds = Math.ceil(seconds % 60); var paddedSeconds = String('00' + actualSeconds).slice(-2); var minutes = Math.round((seconds - actualSeconds) / 60); return `${minutes}:${paddedSeconds}`; }; module.exports = exports;
Remove comment bloat from Route\Filter class.
<?php namespace System\Route; class Filter { /** * The loaded route filters. * * @var array */ public static $filters; /** * Call a set of route filters. * * @param string $filter * @param array $parameters * @param bool $override * @return mixed */ public static function call($filters, $parameters = array(), $override = false) { if (is_null(static::$filters)) { static::$filters = require APP_PATH.'filters'.EXT; } foreach (explode(', ', $filters) as $filter) { if ( ! isset(static::$filters[$filter])) { throw new \Exception("Route filter [$filter] is not defined."); } $response = call_user_func_array(static::$filters[$filter], $parameters); // If overriding is set to true and the filter returned a response, return that response. // Overriding allows for convenient halting of the request flow for things like // authentication, CSRF protection, etc. if ( ! is_null($response) and $override) { return $response; } } } }
<?php namespace System\Route; class Filter { /** * The loaded route filters. * * @var array */ public static $filters; /** * Call a set of route filters. * * @param string $filter * @param array $parameters * @param bool $override * @return mixed */ public static function call($filters, $parameters = array(), $override = false) { if (is_null(static::$filters)) { static::$filters = require APP_PATH.'filters'.EXT; } // -------------------------------------------------------------- // Filters can be comma-delimited, so spin through each one. // -------------------------------------------------------------- foreach (explode(', ', $filters) as $filter) { if ( ! isset(static::$filters[$filter])) { throw new \Exception("Route filter [$filter] is not defined."); } $response = call_user_func_array(static::$filters[$filter], $parameters); // -------------------------------------------------------------- // If overriding is set to true and the filter returned a // response, return that response. // // Overriding allows for convenient halting of the request // flow for things like authentication, CSRF protection, etc. // -------------------------------------------------------------- if ( ! is_null($response) and $override) { return $response; } } } }
Declare classes in global namespace In strict mode, type hints were throwing errors (Sminnee\SilverStripeIntercom\SS_HTTPRequest doesn't exist)
<?php namespace Sminnee\SilverStripeIntercom; use SS_HTTPRequest; use SS_HTTPResponse; use Session; use DataModel; class RequestFilter implements \RequestFilter { /** * Does nothing */ public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) { } /** * Adds Intercom script tags just before the body */ public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) { $mime = $response->getHeader('Content-Type'); if(!$mime || strpos($mime, 'text/html') !== false) { $intercomScriptTags = (new IntercomScriptTags())->forTemplate(); if($intercomScriptTags) { $content = $response->getBody(); $content = preg_replace("/(<\/body[^>]*>)/i", $intercomScriptTags . "\\1", $content); $response->setBody($content); } } } }
<?php namespace Sminnee\SilverStripeIntercom; class RequestFilter implements \RequestFilter { /** * Does nothing */ public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) { } /** * Adds Intercom script tags just before the body */ public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) { $mime = $response->getHeader('Content-Type'); if(!$mime || strpos($mime, 'text/html') !== false) { $intercomScriptTags = (new intercomScriptTags())->forTemplate(); if($intercomScriptTags) { $content = $response->getBody(); $content = preg_replace("/(<\/body[^>]*>)/i", $intercomScriptTags . "\\1", $content); $response->setBody($content); } } } }
Add Facebook login test 3
'use strict'; angular.module('ngSocial.facebook', ['ngRoute','ngFacebook']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/facebook', { templateUrl: 'facebook/facebook.html', controller: 'FacebookCtrl' }); }]) .config( function( $facebookProvider ) { $facebookProvider.setAppId('450853485276464'); $facebookProvider.setPermissions("email","public_profile","user_posts","publish_actions","user_photos"); }) .run( function( $rootScope ) { (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }) .controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) { aler.log('hello!'); $scope.isLoggedIn = false; $scope.login = function(){ $facebook.login().then(function(){ console.log('Logged in...'); }); } }]);
'use strict'; angular.module('ngSocial.facebook', ['ngRoute','ngFacebook']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/facebook', { templateUrl: 'facebook/facebook.html', controller: 'FacebookCtrl' }); }]) .config( function( $facebookProvider ) { $facebookProvider.setAppId('450853485276464'); $facebookProvider.setPermissions("email","public_profile","user_posts","publish_actions","user_photos"); }) .run( function( $rootScope ) { (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }) .controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) { console.log('hello!'); $scope.isLoggedIn = false; $scope.login = function(){ $facebook.login().then(function(){ console.log('Logged in...'); }); } }]);
Move check of connection to a specific function
let connecting = false; let connection = null; export async function connect(serverInfo, databaseName) { if (connecting) throw new Error('connecting to server'); try { connecting = true; if (connection) connection.disconnect(); const driver = require(`./clients/${serverInfo.client}`).default; connection = await driver(serverInfo, databaseName); } catch (err) { throw err; } finally { connecting = false; } } export async function listTables() { _checkIsConnected(); return await connection.listTables(); } export async function executeQuery(query) { _checkIsConnected(); return await connection.executeQuery(query); } export async function listDatabases() { _checkIsConnected(); return await connection.listDatabases(); } function _checkIsConnected() { if (connecting || !connection) { throw new Error('connecting to server'); } }
let connecting = false; let connection = null; export async function connect(serverInfo, databaseName) { if (connecting) throw new Error('connecting to server'); try { connecting = true; if (connection) connection.disconnect(); const driver = require(`./clients/${serverInfo.client}`).default; connection = await driver(serverInfo, databaseName); } catch (err) { throw err; } finally { connecting = false; } } export async function listTables() { if (connecting || !connection) throw new Error('connecting to server'); return await connection.listTables(); } export async function executeQuery(query) { if (connecting || !connection) throw new Error('connecting to server'); return await connection.executeQuery(query); } export async function listDatabases() { if (connecting || !connection) throw new Error('connecting to server'); return await connection.listDatabases(); }
Reset loaded flag on new video. (Must be a better way to do this)
module.exports = ['$sce', $sce => { return { restrict: 'E', template: require('./template.html'), controller: ['$scope', $scope => { $scope.video = {src: undefined}; $scope.receivedPaste = $event => { console.log($event, $event.clipboardData.getData('text/plain')); }; $scope.droppedFiles = function($files, $items) { const file = $files[0]; if (file) { const type = file.type; if (type.indexOf('video') === 0) { $scope.video.src = $sce.trustAsResourceUrl(URL.createObjectURL(file)); $scope.video.loaded = false; } } }; }] }; }];
module.exports = ['$sce', $sce => { return { restrict: 'E', template: require('./template.html'), controller: ['$scope', $scope => { $scope.video = {src: undefined}; $scope.receivedPaste = $event => { console.log($event, $event.clipboardData.getData('text/plain')); }; $scope.droppedFiles = function($files, $items) { const file = $files[0]; if (file) { const type = file.type; if (type.indexOf('video') === 0) { $scope.video.src = $sce.trustAsResourceUrl(URL.createObjectURL(file)); } } }; }] }; }];
Fix var names on interfaces
package fabric import ( "context" ) // HandlerFunc defines the handler function for the server type HandlerFunc func(ctx context.Context, conn Conn) (context.Context, Conn, error) // NegotiatorFunc defines the negotiator functions for the clients type NegotiatorFunc func(ctx context.Context, conn Conn) (context.Context, Conn, error) // Handler is responsible for handling a negotiation on the server's side type Handler interface { Handle(ctx context.Context, conn Conn) (context.Context, Conn, error) Name() string } // Negotiator is responsible for initiating a negotiation on the client's side type Negotiator interface { Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error) Name() string } // Middleware are composites of a handler, a negotiator, and a name methods type Middleware interface { Handle(ctx context.Context, conn Conn) (context.Context, Conn, error) Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error) Name() string }
package fabric import ( "context" ) // HandlerFunc defines the handler function for the server type HandlerFunc func(context.Context, Conn) (context.Context, Conn, error) // NegotiatorFunc defines the negotiator functions for the clients type NegotiatorFunc func(ctx context.Context, conn Conn) (context.Context, Conn, error) // Handler is responsible for handling a negotiation on the server's side type Handler interface { Handle(context.Context, Conn) (context.Context, Conn, error) Name() string } // Negotiator is responsible for initiating a negotiation on the client's side type Negotiator interface { Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error) Name() string } // Middleware are composites of a handler, a negotiator, and a name methods type Middleware interface { Handle(context.Context, Conn) (context.Context, Conn, error) Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error) Name() string }
Fix to show task button
PluginsAPI.Dashboard.addNewTaskButton( ["cloudimport/build/ImportView.js"], function(args, ImportView) { return React.createElement(ImportView, { onNewTaskAdded: args.onNewTaskAdded, projectId: args.projectId, apiURL: "{{ api_url }}", }); } ); PluginsAPI.Dashboard.addTaskActionButton( ["cloudimport/build/TaskView.js"], function(args, TaskView) { var reactElement; $.ajax({ url: "{{ api_url }}/projects/" + args.task.project + "/tasks/" + args.task.id + "/checkforurl", dataType: 'json', async: false, success: function(data) { if (data.folder_url) { reactElement = React.createElement(TaskView, { folderUrl: data.folder_url, }); } } }); return reactElement; } );
PluginsAPI.Dashboard.addNewTaskButton( ["cloudimport/build/ImportView.js"], function(args, ImportView) { return React.createElement(ImportView, { onNewTaskAdded: args.onNewTaskAdded, projectId: args.projectId, apiURL: "{{ api_url }}", }); } ); PluginsAPI.Dashboard.addTaskActionButton( ["cloudimport/build/TaskView.js"], function(args, ImportView) { $.ajax({ url: "{{ api_url }}/projects/" + args.task.project + "/tasks/" + args.task.id + "/checkforurl", dataType: 'json', async: false, success: function(data) { if (data.folder_url) { return React.createElement(ImportView, { folderUrl: data.folder_url, }); } } }); } );
Add a test case to ensure that the memory leak is fixed.
var iTunes = require('../') , conn = null iTunes.createConnection(onConn); function onConn (err, c) { if (err) throw err; conn = c; conn.selection( onSelection ); } function onSelection (err, selection) { if (err) throw err; if (selection.length > 0) { var track = selection[0]; track.artworks(onArtworks); } else { console.log('There are no tracks currently selected...'); } } function onArtworks (err, artworks) { if (err) throw err; if (artworks.length > 0) { console.log(artworks); artworks[0].data(function (err, data) { if (err) throw err; console.log(data.constructor.name); console.log(data.length); // A test to make sure that gargabe collecting one of the Buffers doesn't // cause a seg fault. Invoke node with '--expose_gc' to force garbage coll data = null; setTimeout(function() { if (typeof gc != 'undefined') { console.log('invoking gc()'); gc(); } }, 1000); setTimeout(function() { console.log("Done!"); }, 10000); }); } else { console.log('The selected track does not have any album artwork...'); } }
var iTunes = require('../') , conn = null iTunes.createConnection(onConn); function onConn (err, c) { if (err) throw err; conn = c; conn.selection( onSelection ); } function onSelection (err, selection) { if (err) throw err; if (selection.length > 0) { var track = selection[0]; track.artworks(onArtworks); } else { console.log('There are no tracks currently selected...'); } } function onArtworks (err, artworks) { if (err) throw err; if (artworks.length > 0) { console.log(artworks); artworks[0].data(function (err, data) { if (err) throw err; console.log(data.constructor.name); console.log(data.length); }); } else { console.log('The selected track does not have any album artwork...'); } }
Add ignore warnings for setting a timer
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import { AppRegistry, YellowBox } from 'react-native'; import { Provider } from 'react-redux'; import { ErrorHandler } from 'redux-persist-error-handler'; import { Client as BugsnagClient } from 'bugsnag-react-native'; import { name as appName } from '../app.json'; import { store, persistedStore } from './Store'; import MSupplyMobileApp from './mSupplyMobileApp'; // eslint-disable-next-line no-unused-vars const bugsnagClient = new BugsnagClient(); function App() { return ( <ErrorHandler persistedStore={persistedStore}> <Provider store={store}> <MSupplyMobileApp /> </Provider> </ErrorHandler> ); } YellowBox.ignoreWarnings(['Setting a timer']); AppRegistry.registerComponent(appName, () => App);
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import { AppRegistry } from 'react-native'; import { Provider } from 'react-redux'; import { ErrorHandler } from 'redux-persist-error-handler'; import { Client as BugsnagClient } from 'bugsnag-react-native'; import { name as appName } from '../app.json'; import { store, persistedStore } from './Store'; import MSupplyMobileApp from './mSupplyMobileApp'; // eslint-disable-next-line no-unused-vars const bugsnagClient = new BugsnagClient(); function App() { return ( <ErrorHandler persistedStore={persistedStore}> <Provider store={store}> <MSupplyMobileApp /> </Provider> </ErrorHandler> ); } AppRegistry.registerComponent(appName, () => App);
Add little bit comments for Planet model
from django.db import models from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): # Making `ek` unique just because it will be used as `FK` # in other models. ek = Base64Field(unique=True) name = models.CharField( default='Fucker', max_length=103 ) class Continent(models.Model): ek = Base64Field() name = models.CharField( default='Suckers!', max_length=13 ) planet = models.ForeignKey(Planet, to_field='ek') class Helper(models.Model): """ base64 encoded value won't be available at first time creation. It can ve accessible by getting the object from database after creation mean when it get saved completely, But what if we don't want to get our base64 encoded key from our sweet model by retrieving it again from database? It's easy, efficient, holly and molly! """ ek = Base64Field() def _ek(self): if self.ek: return self.ek if not self.ek and self.pk: return base64.encode(self.pk) return self.ek class CustomReceiver(models.Model): """ Passing custom receiver to generate `youyouid` with a custom receiver. """ youyouid = Base64Field( encode_receiver='django_base64field.tests.receivers:custom_receiver' )
from django.db import models from django.utils.baseconv import base64 from django_base64field.fields import Base64Field class Planet(models.Model): ek = Base64Field() name = models.CharField( default='Fucker', max_length=103 ) class Continent(models.Model): ek = Base64Field() name = models.CharField( default='Suckers!', max_length=13 ) planet = models.ForeignKey(Planet, to_field='ek') class Helper(models.Model): """ base64 encoded value won't be available at first time creation. It can ve accessible by getting the object from database after creation mean when it get saved completely, But what if we don't want to get our base64 encoded key from our sweet model by retrieving it again from database? It's easy, efficient, holly and molly! """ ek = Base64Field() def _ek(self): if self.ek: return self.ek if not self.ek and self.pk: return base64.encode(self.pk) return self.ek class CustomReceiver(models.Model): """ Passing custom receiver to generate `youyouid` with a custom receiver. """ youyouid = Base64Field( encode_receiver='django_base64field.tests.receivers:custom_receiver' )
Revert "added accessor for getting marker ID" This reverts commit b01cfd334df3d4e76e817dc29825f3ec100c9ba3.
L.SmoothMarkerTransition = L.Marker.extend({ options: { traverseTime: 1000, clickable: false }, initialize: function (latlngs, options) { L.Marker.prototype.initialize.call(this, latlngs, options); }, transition: function(latlngs) { if (L.DomUtil.TRANSITION) { if (this._icon) { this._icon.style[L.DomUtil.TRANSITION] = ('all ' + this.options.traverseTime + 'ms linear'); } if (this._shadow) { this._shadow.style[L.DomUtil.TRANSITION] = 'all ' + this.options.traverseTime + 'ms linear'; } } // Move to the next position this.setLatLng(latlngs); } }); L.smoothMarkerTransition = function (latlngs, options) { return new L.smoothMarkerTransition(latlngs, options); };
L.SmoothMarkerTransition = L.Marker.extend({ options: { traverseTime: 1000, clickable: false, markerID: '' }, initialize: function (latlngs, options) { L.Marker.prototype.initialize.call(this, latlngs, options); }, transition: function(latlngs) { if (L.DomUtil.TRANSITION) { if (this._icon) { this._icon.style[L.DomUtil.TRANSITION] = ('all ' + this.options.traverseTime + 'ms linear'); } if (this._shadow) { this._shadow.style[L.DomUtil.TRANSITION] = 'all ' + this.options.traverseTime + 'ms linear'; } } // Move to the next position this.setLatLng(latlngs); }, getMarkerID: function(){ return this.options.markerID; } }); L.smoothMarkerTransition = function (latlngs, options) { return new L.smoothMarkerTransition(latlngs, options); };
Fix conversion of parsed JSON numbers to double so they do not go through a float value in between; also use correct Java base class returned by Json-simple for boxed numbers.
import org.json.simple.JSONObject; /** Representation of the geoip information for a given IP address, created from a JSON representation of the information returned by the Pings server. Includes the longitude and latitude, and the city and country. */ public class GeoipInfo { final public String city; final public String country; final public double longitude; final public double latitude; /** Constructs a GeoipInfo object from JSON information returned by the Pings server. */ public GeoipInfo(JSONObject json) { city = (String)json.get("city"); country = (String)json.get("country_name"); longitude = ((Number)json.get("longitude")).doubleValue(); latitude = ((Number)json.get("latitude")).doubleValue(); } /** * An alternative constructor for testing purposes. */ public GeoipInfo(String city, String country, double longitude, double latitude) { this.city = city; this.country = country; this.longitude = longitude; this.latitude = latitude; } }
import org.json.simple.JSONObject; /** Representation of the geoip information for a given IP address, created from a JSON representation of the information returned by the Pings server. Includes the longitude and latitude, and the city and country. */ public class GeoipInfo { final public String city; final public String country; final public double longitude; final public double latitude; /** Constructs a GeoipInfo object from JSON information returned by the Pings server. */ public GeoipInfo(JSONObject json) { city = (String)json.get("city"); country = (String)json.get("country_name"); /*FIXME : jsonobject get cast into doubles which are cast into floats and then cast back into double*/ longitude = ((Double)json.get("longitude")).floatValue(); latitude = ((Double)json.get("latitude")).floatValue(); } /** * An alternative constructor for testing purpose */ //TODO : remove it when useless public GeoipInfo(String city,String country,double longitude,double latitude) { this.city = city; this.country = country; this.longitude = longitude; this.latitude = latitude; } }
Edit server route url to match client request
var bodyParser = require('body-parser'); var express = require('express'); var app = express(); var router = express.Router(); var Sequelize = require('sequelize'); var sequelize = new Sequelize(process.env.DATABASE_URL); var matchmaker = require('./controllers/Matchmaker'); var playController = require('./controllers/Play'); var turnController = require('./controllers/Turn'); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); router.route('/play') .post(matchmaker.startGame); router.route('/fire') .post(playController.fire); router.route('/cancel') .post(matchmaker.cancel); router.route('/turn/:username') .get(turnController.nextPlayer); app.use('/api', router); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); });
var bodyParser = require('body-parser'); var express = require('express'); var app = express(); var router = express.Router(); var Sequelize = require('sequelize'); var sequelize = new Sequelize(process.env.DATABASE_URL); var matchmaker = require('./controllers/Matchmaker'); var playController = require('./controllers/Play'); var turnController = require('./controllers/Turn'); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); router.route('/play') .post(matchmaker.startGame); router.route('/fire') .post(playController.fire); router.route('/cancel/:username') .post(matchmaker.cancel); router.route('/turn/:username') .get(turnController.nextPlayer); app.use('/api', router); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); });
Allow mime-types like 'text/html; charset=utf-8'
<?php namespace Hmaus\Spas\Formatter; class FormatterService { /** * @var Formatter[] */ private $formatters = []; /** * Add formatters to the service. * Done by a compiler pass * * @param Formatter $formatter */ public function addFormatter(Formatter $formatter) { foreach ($formatter->getContentTypes() as $supportedType) { $this->formatters[$supportedType] = $formatter; } } /** * Retrieve the correct formatter by content-type string, e.g. "application/json" * * @param string $type * @return Formatter * @throws \Exception */ public function getFormatterByContentType(string $type) : Formatter { foreach ($this->formatters as $formatter) { foreach ($formatter->getContentTypes() as $contentType) { if (strpos($type, $contentType) !== false) { return $formatter; } } } throw new \Exception( sprintf('Content-type "%s" is not supported', $type) ); } }
<?php namespace Hmaus\Spas\Formatter; class FormatterService { /** * @var Formatter[] */ private $formatters = []; /** * Add formatters to the service. * Done by a compiler pass * * @param Formatter $formatter */ public function addFormatter(Formatter $formatter) { foreach ($formatter->getContentTypes() as $supportedType) { $this->formatters[$supportedType] = $formatter; } } /** * Retrieve the correct formatter by content-type string, e.g. "application/json" * * @param string $type * @return Formatter * @throws \Exception */ public function getFormatterByContentType(string $type) : Formatter { if (!isset($this->formatters[$type])) { throw new \Exception( sprintf('Content-type "%s" is not supported', $type) ); } return $this->formatters[$type]; } }
Change class name Publisher to Published on models
#!/usr/bin/env python from django.db import models from django.utils.translation import ugettext_lazy as _ from datetime import datetime class PublisherMnager(models.Manager): def all_published(self): return super(PublisherMnager, self).get_query_set().filter( date_available__lte=datetime.now(), published=True) class Published(models.Model): date_available = models.DateTimeField(_(u"Date available"), default=datetime.now, null=True) published = models.BooleanField(_(u"Published"), default=False) objects = PublisherMnager() class Meta: abstract = True def is_published(self): return self.published and \ self.date_available.replace(tzinfo=None) <= datetime.now()
#!/usr/bin/env python from django.db import models from django.utils.translation import ugettext_lazy as _ from datetime import datetime class PublisherMnager(models.Manager): def all_published(self): return super(PublisherMnager, self).get_query_set().filter( date_available__lte=datetime.now(), published=True) class Publisher(models.Model): date_available = models.DateTimeField(_(u"Date available"), default=datetime.now, null=True) published = models.BooleanField(_(u"Published"), default=False) objects = PublisherMnager() class Meta: abstract = True def is_published(self): return self.published and \ self.date_available.replace(tzinfo=None) <= datetime.now()
Add test to DataLoader base class
import unittest from brew.parsers import DataLoader from brew.parsers import JSONDataLoader class TestDataLoader(unittest.TestCase): def setUp(self): self.parser = DataLoader('./') def test_read_data_raises(self): with self.assertRaises(NotImplementedError): self.parser.read_data('filename') class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
import unittest from brew.parsers import JSONDataLoader class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
Simplify the view as the validation logic has already moved to the model
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='text/plain') def login(request, key, redirect_invalid_to=None): user = auth.authenticate(key=key) if user is None: if redirect_invalid_to is not None: return HttpResponseRedirect(redirect_invalid_to) else: return HttpResponseGone() auth.login(request, user) data = Key.objects.get(key=key) data.update_usage() next = request.GET.get('next', None) if data.next is not None: next = data.next if next is None: next = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(next)
from datetime import datetime from django.http import HttpResponseRedirect, HttpResponseGone from django.contrib.auth import login from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() def login(request, key, redirect_invalid_to=None, redirect_expired_to=None): data = Key.objects.get(key=key) if data is None: if redirect_invalid_to is not None: return HttpResponseRedirect(redirect_invalid_to) else: return HttpResponseGone() expired = False if data.usage_left is not None and data.usage_left <= 0: expired = True if data.expires is not None and data.expires < datetime.now(): expired = True if expired: if redirect_expired_to is not None: return HttpResponseRedirect(redirect_expired_to) else: return HttpResponseGone() if data.usage_left is not None: data.usage_left -= 1 data.save() login(request, data.user) next = request.GET.get('next', None) if data.next is not None: next = data.next if next is None: next = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(next)
Fix undefined variable error. (woops)
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use \App\Manga; use \App\MangaInformation; class MangaEditController extends Controller { public function __construct() { $this->middleware('auth'); } public function index($id) { if (\Auth::user()->isAdmin() == false && \Auth::user()->isMaintainer() == false) { return view('error.403'); } $manga = Manga::find($id); if ($manga == null) { return view('error.404'); } $name = $manga->getName(); $info = MangaInformation::find($id); $mu_id = null; if ($info != null) { $mu_id = $info->getMangaUpdatesId(); } $archives = $manga->getArchives('ascending'); return view('manga.edit')->with('id', $id) ->with('mu_id', $mu_id) ->with('name', $name) ->with('archives', $archives); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use \App\Manga; use \App\MangaInformation; class MangaEditController extends Controller { public function __construct() { $this->middleware('auth'); } public function index($id) { if (\Auth::user()->isAdmin() == false && \Auth::user()->isMaintainer() == false) { return view('error.403'); } $manga = Manga::find($id); if ($manga == null) { return view('error.404'); } $name = $manga->getName(); $info = MangaInformation::find($id); if ($info != null) { $mu_id = $info->getMangaUpdatesId(); } $archives = $manga->getArchives('ascending'); return view('manga.edit')->with('id', $id) ->with('mu_id', $mu_id) ->with('name', $name) ->with('archives', $archives); } }
Allow blank zotero url reference, but require zotero json data
from django.db import models from editorsnotes.main.models import Document import utils import json class ZoteroLink(models.Model): doc = models.OneToOneField(Document, related_name='_zotero_link') zotero_url = models.URLField(blank=True) zotero_data = models.TextField() date_information = models.TextField(blank=True) def __str__(self): return 'Zotero data: %s' % self.doc.__str__() def get_zotero_fields(self): z = json.loads(self.zotero_data) z['itemType'] = utils.type_map['readable'][z['itemType']] if self.date_information: date_parts = json.loads(self.date_information) for part in date_parts: z[part] = date_parts[part] if z['creators']: names = utils.resolve_names(z, 'facets') z.pop('creators') output = z.items() for name in names: for creator_type, creator_value in name.items(): output.append((creator_type, creator_value)) else: output = z.items() return output
from django.db import models from editorsnotes.main.models import Document import utils import json class ZoteroLink(models.Model): doc = models.OneToOneField(Document, related_name='_zotero_link') zotero_url = models.URLField() zotero_data = models.TextField(blank=True) date_information = models.TextField(blank=True) def __str__(self): return 'Zotero data: %s' % self.doc.__str__() def get_zotero_fields(self): z = json.loads(self.zotero_data) z['itemType'] = utils.type_map['readable'][z['itemType']] if self.date_information: date_parts = json.loads(self.date_information) for part in date_parts: z[part] = date_parts[part] if z['creators']: names = utils.resolve_names(z, 'facets') z.pop('creators') output = z.items() for name in names: for creator_type, creator_value in name.items(): output.append((creator_type, creator_value)) else: output = z.items() return output
Update enum to pass name to constructor
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.commonwl.view.cwl; /** * Enum for possible CWL processes */ public enum CWLProcess { WORKFLOW("Workflow"), COMMANDLINETOOL("CommandLineTool"), EXPRESSIONTOOL("ExpressionTool"); private final String name; CWLProcess(String name) { this.name = name; } @Override public String toString() { return name; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.commonwl.view.cwl; /** * Enum for possible CWL processes */ public enum CWLProcess { WORKFLOW, COMMANDLINETOOL, EXPRESSIONTOOL; @Override public String toString() { switch (this) { case WORKFLOW: return "Workflow"; case COMMANDLINETOOL: return "CommandLineTool"; case EXPRESSIONTOOL: default: return "ExpressionTool"; } } }
Integrate content server with new settings module
import os import pytest import tempfile import shutil from falafel.content.manager import ContentManager @pytest.fixture def cm(): tmp_dir = tempfile.mkdtemp() yield ContentManager(tmp_dir, ["falafel.tests.plugins"]) shutil.rmtree(tmp_dir) def test_create_manager(cm): assert len(list(cm.get_all())) == 0 def test_save(cm): doc = { "resolution": "butts", "rule_id": "tina_loves_butts|OH_YEAH" } cm.save(doc, default=True) doc["path"] = os.path.join(cm.content_prefix, "tina_loves_butts/OH_YEAH") assert next(cm.get("tina_loves_butts|OH_YEAH")) == doc assert next(cm.get("tina_loves_butts")) == doc def test_error_keys(cm): cm.save({"rule_id": "tina_loves_butts|OH_YEAH"}, default=True) cm.save({"rule_id": "tina_loves_butts|OH_NO"}, default=True) assert set(cm.error_keys()) == {"tina_loves_butts|OH_YEAH", "tina_loves_butts|OH_NO"}
import os import pytest import tempfile import shutil from falafel.content.manager import ContentManager @pytest.fixture def cm(): tmp_dir = tempfile.mkdtemp() yield ContentManager(tmp_dir, "falafel.tests.plugins") shutil.rmtree(tmp_dir) def test_create_manager(cm): assert len(list(cm.get_all())) == 0 def test_save(cm): doc = { "resolution": "butts", "rule_id": "tina_loves_butts|OH_YEAH" } cm.save(doc, default=True) doc["path"] = os.path.join(cm.content_prefix, "tina_loves_butts/OH_YEAH") assert next(cm.get("tina_loves_butts|OH_YEAH")) == doc assert next(cm.get("tina_loves_butts")) == doc def test_error_keys(cm): cm.save({"rule_id": "tina_loves_butts|OH_YEAH"}, default=True) cm.save({"rule_id": "tina_loves_butts|OH_NO"}, default=True) assert set(cm.error_keys()) == {"tina_loves_butts|OH_YEAH", "tina_loves_butts|OH_NO"}
Fix New menu to work with state.
Application.Directives.directive("navbar", navbarDirective); function navbarDirective() { return { scope: true, restrict: "AE", replace: true, templateUrl: "index/navbar.html", controller: "navbarDirectiveController" }; } Application.Controllers.controller("navbarDirectiveController", ["$scope", "current", "$state", "projectState", navbarDirectiveController]); function navbarDirectiveController($scope, current, $state, projectState) { // This is needed to toggle the menu closed when an item is selected. // This is a part of how ui-bootstrap interacts with the menus and // the menu item does an ng-click. $scope.status = { isopen: false }; $scope.create = function(action) { var projectID = current.projectID(); var route = "projects.project." + action + ".create"; var state = null; var stateID = projectState.add(projectID, state); $scope.status = false; $state.go(route, {id: projectID, sid: stateID}); }; }
Application.Directives.directive("navbar", navbarDirective); function navbarDirective() { return { scope: true, restrict: "AE", replace: true, templateUrl: "index/navbar.html", controller: "navbarDirectiveController" }; } Application.Controllers.controller("navbarDirectiveController", ["$scope", "ui", "current", "$state", navbarDirectiveController]); function navbarDirectiveController($scope, ui, current, $state) { // This is needed to toggle the menu closed when an item is selected. // This is a part of how ui-bootstrap interacts with the menus and // the menu item does an ng-click. $scope.status = { isopen: false }; $scope.create = function(action) { var projectID = current.projectID(); var route = "projects.project." + action + ".create"; $scope.status = false; $state.go(route, {id: projectID}); }; }
Switch to buttons to avoid the hash href.
import React from 'react'; const Navigation = ({ week, day, triggerNavigation }) => { const handleNext = () => { triggerNavigation(1); return false; } const handlePrevious = () => { triggerNavigation(-1); return false; } return ( <div> { !(week === 1 && day === 1) && <button onClick={ handlePrevious }>&lsaquo;&lsaquo; Week { day === 1 ? week - 1 : week }, Day { day === 1 ? 3 : day - 1 }</button> } ... { !(week === 9 && day === 3) && <button onClick={ handleNext }>Week { day === 3 ? week + 1 : week }, Day { day === 3 ? 1 : day + 1 } &rsaquo;&rsaquo;</button> } </div> ) } export default Navigation;
import React from 'react'; const Navigation = ({ week, day, triggerNavigation }) => { const handleNext = () => { triggerNavigation(1); return false; } const handlePrevious = () => { triggerNavigation(-1); return false; } return ( <div> { !(week === 1 && day === 1) && <a href="#" onClick={ handlePrevious }>&lsaquo;&lsaquo; Week { day === 1 ? week - 1 : week }, Day { day === 1 ? 3 : day - 1 }</a> } ... { !(week === 9 && day === 3) && <a href="#" onClick={ handleNext }>Week { day === 3 ? week + 1 : week }, Day { day === 3 ? 1 : day + 1 } &rsaquo;&rsaquo;</a> } </div> ) } export default Navigation;
Add link for distance computation
import numpy as np def fast_distance(lat1, lon1, lat2, lon2): '''Compute the arc distance assuming the earth is a sphere. This is not the only possible implementation. It was taken from: https://www.mkompf.com/gps/distcalc.html ''' g = np.sin(lat1)*np.sin(lat2)+np.cos(lat1)*np.cos(lat2)*np.cos(lon1-lon2) return np.arccos(np.minimum(1, g)) def spherical_distance(depth1_m, lat1_deg, lon1_deg, depth2_m, lat2_deg, lon2_deg): "Compute the arc distance, uses degrees as input." R_earth = 6371000 lat1 = np.pi*lat1_deg/180 lon1 = np.pi*lon1_deg/180 lat2 = np.pi*lat2_deg/180 lon2 = np.pi*lon2_deg/180 horiz_dist = R_earth*fast_distance(lat1, lon1, lat2, lon2) vert_dist = np.abs(depth1_m-depth2_m) return (vert_dist, horiz_dist)
import numpy as np def fast_distance(lat1, lon1, lat2, lon2): '''Compute the arc distance assuming the earth is a sphere.''' g = np.sin(lat1)*np.sin(lat2)+np.cos(lat1)*np.cos(lat2)*np.cos(lon1-lon2) return np.arccos(np.minimum(1, g)) def spherical_distance(depth1_m, lat1_deg, lon1_deg, depth2_m, lat2_deg, lon2_deg): "Compute the arc distance, uses degrees as input." R_earth = 6371000 lat1 = np.pi*lat1_deg/180 lon1 = np.pi*lon1_deg/180 lat2 = np.pi*lat2_deg/180 lon2 = np.pi*lon2_deg/180 horiz_dist = R_earth*fast_distance(lat1, lon1, lat2, lon2) vert_dist = np.abs(depth1_m-depth2_m) return (vert_dist, horiz_dist)
Move ModuleConcatenationPlugin to the end of plugins list
import webpack from 'webpack'; import UglifyJSPlugin from 'uglifyjs-webpack-plugin'; module.exports = ( { target }, { vendor = target.name === 'browsers', manifest = vendor, uglify = true } = {} ) => ({ plugins: [] .concat( vendor ? new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: ({ resource }) => /node_modules/.test(resource), }) : [] ) .concat( manifest ? new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity, }) : [] ) .concat( uglify ? new UglifyJSPlugin({ uglifyOptions: { beautify: false, ecma: 6, compress: true, comments: false, }, }) : [] ) .concat(new webpack.optimize.ModuleConcatenationPlugin()), });
import webpack from 'webpack'; import UglifyJSPlugin from 'uglifyjs-webpack-plugin'; module.exports = ( { target }, { vendor = target.name === 'browsers', manifest = vendor, uglify = true } = {} ) => ({ plugins: [new webpack.optimize.ModuleConcatenationPlugin()] .concat( vendor ? new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: ({ resource }) => /node_modules/.test(resource), }) : [] ) .concat( manifest ? new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity, }) : [] ) .concat( uglify ? new UglifyJSPlugin({ uglifyOptions: { beautify: false, ecma: 6, compress: true, comments: false, }, }) : [] ), });
[SD-770] Fix homepage carousels on iOS
//= require spree/frontend/viewport Spree.fetchProductCarousel = function (taxonId, htmlContainer) { return $.ajax({ url: Spree.routes.product_carousel(taxonId) }).done(function (data) { htmlContainer.html(data); htmlContainer.find('.carousel').carouselBootstrap4() }) } Spree.loadCarousel = function (element, div) { var container = $(element) var productCarousel = $(div) var carouselLoaded = productCarousel.attr('data-product-carousel-loaded') if (container.length && !carouselLoaded && container.isInViewport()) { var taxonId = productCarousel.attr('data-product-carousel-taxon-id') productCarousel.attr('data-product-carousel-loaded', 'true') Spree.fetchProductCarousel(taxonId, container) } } Spree.loadsCarouselElements = function () { $('div[data-product-carousel]').each(function (_index, element) { Spree.loadCarousel(element, this) }) } document.addEventListener('turbolinks:load', function () { var homePage = $('body#home') if (homePage.length) { // load Carousels straight away if they are in the viewport Spree.loadsCarouselElements() // load additional Carousels when scrolling down $(window).on('resize scroll', function () { Spree.loadsCarouselElements() }) } })
//= require spree/frontend/viewport Spree.fetchProductCarousel = function (taxonId, htmlContainer) { return $.ajax({ url: Spree.routes.product_carousel(taxonId) }).done(function (data) { htmlContainer.html(data); htmlContainer.find('.carousel').carouselBootstrap4() }) } Spree.loadCarousel = function (element, div) { var container = $(element) var productCarousel = $(div) var carouselLoaded = productCarousel.attr('data-product-carousel-loaded') if (container.length && !carouselLoaded && container.isInViewport()) { var taxonId = productCarousel.attr('data-product-carousel-taxon-id') productCarousel.attr('data-product-carousel-loaded', 'true') Spree.fetchProductCarousel(taxonId, container) } } Spree.loadsCarouselElements = function () { $('div[data-product-carousel').each(function (_index, element) { Spree.loadCarousel(element, this) }) } document.addEventListener('turbolinks:load', function () { var homePage = $('body#home') if (homePage.length) { // load Carousels straight away if they are in the viewport Spree.loadsCarouselElements() // load additional Carousels when scrolling down $(window).on('resize scroll', function () { Spree.loadsCarouselElements() }) } })
Fix Chrome vote scroll issue
import React, { Component, PropTypes } from 'react'; import FlipMove from 'react-flip-move'; import { Element as ScrollElement } from 'react-scroll'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './RestaurantList.scss'; import RestaurantContainer from '../../containers/RestaurantContainer'; class RestaurantList extends Component { componentWillUpdate() { this.scrollY = window.scrollY; } componentDidUpdate() { // prevent Chrome from scrolling to new position of voted restaurant window.scrollTo(0, this.scrollY); } render() { const { ids } = this.props; return ( <FlipMove typeName="ul" className={s.root} staggerDelayBy={40} staggerDurationBy={40}> {ids.map(id => ( <li key={`restaurantListItem_${id}`}> <ScrollElement name={`restaurantListItem_${id}`}> <RestaurantContainer id={id} shouldShowAddTagArea shouldShowDropdown /> </ScrollElement> </li> ))} </FlipMove> ); } } RestaurantList.propTypes = { ids: PropTypes.array.isRequired }; export default withStyles(s)(RestaurantList);
import React, { PropTypes } from 'react'; import FlipMove from 'react-flip-move'; import { Element as ScrollElement } from 'react-scroll'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './RestaurantList.scss'; import RestaurantContainer from '../../containers/RestaurantContainer'; const RestaurantList = ({ ids }) => ( <ul className={s.root}> <FlipMove staggerDelayBy={40} staggerDurationBy={40}> {ids.map(id => ( <li key={`restaurantListItem_${id}`}> <ScrollElement name={`restaurantListItem_${id}`}> <RestaurantContainer id={id} shouldShowAddTagArea shouldShowDropdown /> </ScrollElement> </li> ))} </FlipMove> </ul> ); RestaurantList.propTypes = { ids: PropTypes.array.isRequired }; export default withStyles(s)(RestaurantList);
Fix "amount from" for "Big orders"
package org.camunda.bpm.demo.orderconfirmation.config; import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO; import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; import java.util.List; import java.util.logging.Logger; /* * Helper class to create an initial set of discount rules */ @Singleton @Startup public class DiscountRuleEntryConfig { private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName()); @Inject private RuleEntryDAO rulesDAO; /* * If no discount rules are present in the database, we create some initial ones */ @PostConstruct public void initializeDiscountRules() { List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries(); if ((rules == null) || (rules.size() == 0)) { log.info("Creating initial sample discount rules: ..."); rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5)); rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1000, 7)); rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10)); } } }
package org.camunda.bpm.demo.orderconfirmation.config; import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO; import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; import java.util.List; import java.util.logging.Logger; /* * Helper class to create an initial set of discount rules */ @Singleton @Startup public class DiscountRuleEntryConfig { private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName()); @Inject private RuleEntryDAO rulesDAO; /* * If no discount rules are present in the database, we create some initial ones */ @PostConstruct public void initializeDiscountRules() { List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries(); if ((rules == null) || (rules.size() == 0)) { log.info("Creating initial sample discount rules: ..."); rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5)); rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1001, 7)); rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10)); } } }
Fix import path for metrics provider cmd
package main import ( log "github.com/Sirupsen/logrus" "github.com/cerana/cerana/provider" "github.com/cerana/cerana/providers/metrics" logx "github.com/mistifyio/mistify-logrus-ext" flag "github.com/spf13/pflag" ) func main() { log.SetFormatter(&logx.MistifyFormatter{}) config := provider.NewConfig(nil, nil) flag.Parse() dieOnError(config.LoadConfig()) dieOnError(config.SetupLogging()) server, err := provider.NewServer(config) dieOnError(err) m := &metrics.Metrics{} m.RegisterTasks(server) if len(server.RegisteredTasks()) != 0 { dieOnError(server.Start()) server.StopOnSignal() } else { log.Warn("no registered tasks, exiting") } } func dieOnError(err error) { if err != nil { log.Fatal("encountered an error during startup") } }
package main import ( log "github.com/Sirupsen/logrus" logx "github.com/mistifyio/mistify-logrus-ext" "github.com/mistifyio/mistify/provider" "github.com/mistifyio/mistify/providers/metrics" flag "github.com/spf13/pflag" ) func main() { log.SetFormatter(&logx.MistifyFormatter{}) config := provider.NewConfig(nil, nil) flag.Parse() dieOnError(config.LoadConfig()) dieOnError(config.SetupLogging()) server, err := provider.NewServer(config) dieOnError(err) m := &metrics.Metrics{} m.RegisterTasks(server) if len(server.RegisteredTasks()) != 0 { dieOnError(server.Start()) server.StopOnSignal() } else { log.Warn("no registered tasks, exiting") } } func dieOnError(err error) { if err != nil { log.Fatal("encountered an error during startup") } }
Add api prefix for image API
"""rcard URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from waterfall_wall import views router = routers.DefaultRouter() router.register(r'images', views.ImageViewSet) urlpatterns = [ url(r'^api/', include(router.urls)), url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]
"""rcard URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from waterfall_wall import views router = routers.DefaultRouter() router.register(r'images', views.ImageViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]
Change contextlib import to handle the new location in Python 3.
from django.test import TestCase from ..externals import External try: from contextlib import GeneratorContextManager except ImportError: from contextlib import _GeneratorContextManager as GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): external = External('foo') with self.assertRaises(ImportError): external._load('') def test_load_class(self): external = External('foo') self.assertIsInstance(external.load_class(''), object) self.assertTrue(external.load_class('', fallback=True)) def test_load_method(self): external = External('foo') self.assertIsNone(external.load_method('')()) self.assertTrue(external.load_method('', fallback=True)) def test_context_manager(self): external = External('foo') self.assertIs(type(external.context_manager('')), FunctionType) self.assertIsInstance(external.context_manager('')(), GeneratorContextManager) self.assertTrue(external.context_manager('', fallback=True))
from django.test import TestCase from ..externals import External from contextlib import GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): external = External('foo') with self.assertRaises(ImportError): external._load('') def test_load_class(self): external = External('foo') self.assertIsInstance(external.load_class(''), object) self.assertTrue(external.load_class('', fallback=True)) def test_load_method(self): external = External('foo') self.assertIsNone(external.load_method('')()) self.assertTrue(external.load_method('', fallback=True)) def test_context_manager(self): external = External('foo') self.assertIs(type(external.context_manager('')), FunctionType) self.assertIsInstance(external.context_manager('')(), GeneratorContextManager) self.assertTrue(external.context_manager('', fallback=True))
Fix für Samsung Geräte ohne Navbar
package com.haw.projecthorse.android; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.haw.projecthorse.gamemanager.CoreGameMain; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Hiermit wird die Android Navigation Bar ausgeblendet, zur�ckholen // geht ab Android 4.4 mit einem Swipe vom oberen Bildschirmrand nach unten if (Build.VERSION.SDK_INT >= 19) { Window window = getWindow(); if(window!=null){ try { View decorView = window.getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } catch (Exception e) { // No navbar on device } } } AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); initialize(new CoreGameMain(), config); } }
package com.haw.projecthorse.android; import android.os.Build; import android.os.Bundle; import android.view.View; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.haw.projecthorse.gamemanager.CoreGameMain; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Hiermit wird die Android Navigation Bar ausgeblendet, zurckholen // geht ab Android 4.4 mit einem Swipe vom oberen Bildschirmrand nach unten if (Build.VERSION.SDK_INT >= 19) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); initialize(new CoreGameMain(), config); } }
Check if pit has data
import React, { PropTypes } from 'react'; import './index.css'; const Pit = React.createClass({ propTypes: { pit: PropTypes.object.isRequired, }, render() { const { pit } = this.props; return ( <div className="Pit"> <div className="Pit-name">{pit.name}</div> <div className="Pit-type">{pit.type}</div> <div className="Pit-dataset">{pit.dataset}</div> <div className="Pit-id">{pit.id}</div> {pit.data ? <table> <tbody> {Object.keys(pit.data).map((key) => <tr key={key}> <td>{key}</td> <td>{pit.data[key]}</td> </tr> )} </tbody> </table> : null } </div> ); }, }); export default Pit;
import React, { PropTypes } from 'react'; import './index.css'; const Pit = React.createClass({ propTypes: { pit: PropTypes.object.isRequired, }, render() { const { pit } = this.props; return ( <div className="Pit"> <div className="Pit-name">{pit.name}</div> <div className="Pit-type">{pit.type}</div> <div className="Pit-dataset">{pit.dataset}</div> <div className="Pit-id">{pit.id}</div> <table> <tbody> {Object.keys(pit.data).map((key) => <tr key={key}> <td>{key}</td> <td>{pit.data[key]}</td> </tr> )} </tbody> </table> </div> ); }, }); export default Pit;
Use CommonJS module style for improved compatibility
const Promise = require('dexie').Promise module.exports = class DexieBatch { constructor(opts = { batchSize: 20 }) { this.opts = opts } each(collection, callback) { return this.eachBatch(collection, a => { return Promise.all(a.map(callback)) }) } eachBatch(collection, callback) { const delegate = this.opts.limit ? 'eachBatchParallel' : 'eachBatchSerial' return this[delegate](collection, callback) } eachBatchParallel(collection, callback) { const batchSize = this.opts.batchSize const batchPromises = [] for (let i = 0; i * batchSize < this.opts.limit; i++) { const batchPromise = collection .clone() .offset(i * batchSize) .limit(batchSize) .toArray() .then(a => callback(a, i)) batchPromises.push(batchPromise) } return Promise.all(batchPromises).then(batches => batches.length) } eachBatchSerial(collection, callback) { const batchSize = this.opts.batchSize const batchPromise = collection.clone().limit(batchSize).toArray() batchPromise.then(callback) return batchPromise.then(batch => { return batch.length ? this.eachBatch(collection.clone().offset(batchSize), callback) : undefined }) } }
import Dexie from 'dexie' const Promise = Dexie.Promise export default class DexieBatch { constructor(opts = { batchSize: 20 }) { this.opts = opts } each(collection, callback) { return this.eachBatch(collection, a => { return Promise.all(a.map(callback)) }) } eachBatch(collection, callback) { const delegate = this.opts.limit ? 'eachBatchParallel' : 'eachBatchSerial' return this[delegate](collection, callback) } eachBatchParallel(collection, callback) { const batchSize = this.opts.batchSize const batchPromises = [] for (let i = 0; i * batchSize < this.opts.limit; i++) { const batchPromise = collection .clone() .offset(i * batchSize) .limit(batchSize) .toArray() .then(a => callback(a, i)) batchPromises.push(batchPromise) } return Dexie.Promise.all(batchPromises).then(batches => batches.length) } eachBatchSerial(collection, callback) { const batchSize = this.opts.batchSize const batchPromise = collection.clone().limit(batchSize).toArray() batchPromise.then(callback) return batchPromise.then(batch => { return batch.length ? this.eachBatch(collection.clone().offset(batchSize), callback) : undefined }) } }
Make data URI in a separate method and remove some litter
<?php class Layout { private $cache; private function mime($path) { switch(pathinfo($path, PATHINFO_EXTENSION)) { case 'css': return 'text/css'; case 'png': return 'image/png'; case 'ttf': return 'application/x-font-ttf'; default: return (new finfo(FILEINFO_MIME_TYPE))->file($path); } } private function uri($path) { $mime = $this->mime($path); $data = base64_encode((strpos($mime, 'text/') === 0) ? $this->embed($path) : file_get_contents($path)); return "data:$mime;base64,$data"; } private function embed($path) { return preg_replace_callback ( '/«([^«»]++)»/', function($match) { return $this->uri($match[1]); }, file_get_contents($path) ); } /** * Creates a new instance based on the given folder. * @param string $dir */ function __construct($dir) { $cache = "$dir/.cache/"; if(!is_dir($cache) && !mkdir($cache, 0700)) trigger_error('Cannot create cache directory. Performance will be affected.'); else $this->cache = $cache; } }
<?php class Layout { private $cache; private function mime($path) { switch(pathinfo($path, PATHINFO_EXTENSION)) { case 'css': return 'text/css'; case 'png': return 'image/png'; case 'ttf': return 'application/x-font-ttf'; default: return (new finfo(FILEINFO_MIME_TYPE))->file($path); } } private function embed($path) { return preg_replace_callback ( '/«([^«»]++)»/', function($match) { $mime = $this->mime($match[1]); $data = base64_encode((strpos($mime, 'text/') === 0) ? $this->embed($match[1]) : file_get_contents($match[1])); return "data:$mime;base64,$data"; }, file_get_contents($path) ); } function test_embed($path) { echo $this->embed($path); } /** * Creates a new instance based on the given folder. * @param string $dir */ function __construct($dir) { $cache = "$dir/.cache/"; if(!is_dir($cache) && !mkdir($cache, 0700)) trigger_error('Cannot create cache directory. Performance will be affected.'); else $this->cache = $cache; } }
Allow time to be positive offset if position is not set
var utils = require('radiodan-client').utils; module.exports = function(options) { var validOptions = {}; validOptions.time = parseInt(options.time); if (isNaN(validOptions.time)) { return utils.promise.reject( new Error('Seek time must be an integer') ); } if(options.hasOwnProperty('position')) { validOptions.position = parseInt(options.position); if (isNaN(validOptions.position)) { return utils.promise.reject( new Error('Playlist position must be an integer') ); } if(validOptions.time < 0) { return utils.promise.reject( new Error('Seek time must be an absolute value') ); } } else { // time is an offset to the current track, so should be passed as a string if('+'+validOptions.time === options.time) { validOptions.time = options.time; } } return utils.promise.resolve(validOptions); };
var utils = require('radiodan-client').utils; module.exports = function(options) { var validOptions = {}; validOptions.time = parseInt(options.time); if (isNaN(validOptions.time)) { return utils.promise.reject( new Error('Seek time must be an integer') ); } if(options.hasOwnProperty('position')) { validOptions.position = parseInt(options.position); if (isNaN(validOptions.position)) { return utils.promise.reject( new Error('Playlist position must be an integer') ); } if(validOptions.time < 0) { return utils.promise.reject( new Error('Seek time must be an absolute value') ); } } // time set is an offset, so should be passed as a string if('+'+validOptions.time === options.time) { validOptions.time = options.time; } return utils.promise.resolve(validOptions); };
Add helper function to get theme assets
<?php /* * Global helper functions for Clearboard */ /** * Combines filesystem paths. * Accepts unlimited number of arguments in the form of strings. * @return string */ function joinPath() { // Credit - http://stackoverflow.com/a/1091219/3764348 $args = func_get_args(); $paths = array(); foreach ($args as $arg) { $paths = array_merge($paths, (array)$arg); } $paths = array_map(create_function('$p', 'return trim($p, "/");'), $paths); $paths = array_filter($paths); return join('/', $paths); } /** * Returns the base path of the theme's personal asset directory. * Similar to Laravel's *_path() functions, a path argument can be supplied to produce a full path. * WARNING! Does not return URL! * @param string $path Optional. Path to resource. * @param string|null $theme Name of theme. If left null, will use current theme. * @return string */ function theme_path($path = '', $theme = null) { if ($theme == null) { $theme = config('clearboard.theme'); } return app_path() . "/assets/$theme/" . ($path ? DIRECTORY_SEPARATOR.$path : $path); } /** * Identical behaviour to Laravel's inbuilt asset() helper function, expect returns assets from a theme's personal * asset directory. * @param $path * @param null $secure * @param null $theme * @return string */ function theme_asset($path, $secure = null, $theme = null) { if ($theme == null) { $theme = config('clearboard.theme'); } return asset("assets/$theme/" . $path, $secure); }
<?php /* * Global helper functions for Clearboard */ /** * Combines filesystem paths. * Accepts unlimited number of arguments in the form of strings. * @return string */ function joinPath() { // Credit - http://stackoverflow.com/a/1091219/3764348 $args = func_get_args(); $paths = array(); foreach ($args as $arg) { $paths = array_merge($paths, (array)$arg); } $paths = array_map(create_function('$p', 'return trim($p, "/");'), $paths); $paths = array_filter($paths); return join('/', $paths); } /** * Returns the base path of the theme's personal asset directory. * Similar to Laravel's *_path() functions, a path argument can be supplied to produce a full path. * @param string $path Optional. Path to resource. * @param string|null $theme Name of theme. If left null, will use current theme. * @return string */ function theme_path($path = '', $theme = null) { if ($theme == null) { $theme = config('clearboard.theme'); } return app_path() . "/assets/$theme/" . ($path ? DIRECTORY_SEPARATOR.$path : $path); }
Load SCSS and SVG files
/* eslint-disable */ var path = require('path'); var webpack = require('webpack'); var autoprefixer = require('autoprefixer') var config = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './src/main.js' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/dist/' }, module: { loaders: [{ test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ }, { test: /\.scss$/, loaders: ['style', 'css', 'sass', 'postcss'] }, { test: /\.svg$/, loaders: ['svg-inline'], }] }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], postcss: function () { return [autoprefixer] } }; module.exports = config;
var path = require('path'); var webpack = require('webpack'); var config = { devtool: 'cheap-module-eval-source-map', entry: [ './src/main.js', 'webpack-hot-middleware/client' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/dist/' }, module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ } ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ] }; module.exports = config;
Remove probably outdated error suppression https://bugs.php.net/bug.php?id=50688 was closed as fixed in 2017 when PHP 7.0 was only supported upstream. We already require PHP 7.2. Change-Id: Ie9801e38915da634e31c91ebdcb61226e0ae5712
<?php class Bundler { private function sort( &$array ) { usort( $array, static function ( Bundleable $a, Bundleable $b ) { return strcmp( $b->getSortingKey(), $a->getSortingKey() ); } ); } /** * Bundle bundleable elements that can be bundled by their bundling keys * * @param Bundleable[] $bundleables * @return Bundleable[] Grouped notifications sorted by timestamp DESC */ public function bundle( array $bundleables ) { $groups = []; $bundled = []; /** @var Bundleable $element */ foreach ( $bundleables as $element ) { if ( $element->canBeBundled() && $element->getBundlingKey() ) { $groups[ $element->getBundlingKey() ][] = $element; } else { $bundled[] = $element; } } foreach ( $groups as $bundlingKey => $group ) { $this->sort( $group ); /** @var Bundleable $base */ $base = array_shift( $group ); $base->setBundledElements( $group ); $bundled[] = $base; } $this->sort( $bundled ); return $bundled; } }
<?php class Bundler { private function sort( &$array ) { // We have to ignore the error here (use @usort) // otherwise this code fails when executed by unit tests // See: https://bugs.php.net/bug.php?id=50688 // phpcs:ignore Generic.PHP.NoSilencedErrors @usort( $array, static function ( Bundleable $a, Bundleable $b ) { return strcmp( $b->getSortingKey(), $a->getSortingKey() ); } ); } /** * Bundle bundleable elements that can be bundled by their bundling keys * * @param Bundleable[] $bundleables * @return Bundleable[] Grouped notifications sorted by timestamp DESC */ public function bundle( array $bundleables ) { $groups = []; $bundled = []; /** @var Bundleable $element */ foreach ( $bundleables as $element ) { if ( $element->canBeBundled() && $element->getBundlingKey() ) { $groups[ $element->getBundlingKey() ][] = $element; } else { $bundled[] = $element; } } foreach ( $groups as $bundlingKey => $group ) { $this->sort( $group ); /** @var Bundleable $base */ $base = array_shift( $group ); $base->setBundledElements( $group ); $bundled[] = $base; } $this->sort( $bundled ); return $bundled; } }
Make console output noisy again Otherwise tool reports like phploc wouldn't be part of the report
<?php declare(strict_types=1); namespace Phpcq\PostProcessor; use Phpcq\PluginApi\Version10\OutputInterface; use Phpcq\PluginApi\Version10\PostProcessorInterface; use Phpcq\PluginApi\Version10\ToolReportInterface; final class ConsoleOutputToolReportProcessor implements PostProcessorInterface { /** * @var string */ private $toolName; /** * ConsoleOutputToolReportProcessor constructor. * * @param string $toolName */ public function __construct(string $toolName) { $this->toolName = $toolName; } /** * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function process( ToolReportInterface $report, string $consoleOutput, int $exitCode, OutputInterface $output ): void { if (0 !== $exitCode) { $report->addError('error', $consoleOutput); } else { $report->addError('info', $consoleOutput); } $report->finish(0 === $exitCode ? ToolReportInterface::STATUS_PASSED : ToolReportInterface::STATUS_FAILED); } }
<?php declare(strict_types=1); namespace Phpcq\PostProcessor; use Phpcq\PluginApi\Version10\OutputInterface; use Phpcq\PluginApi\Version10\PostProcessorInterface; use Phpcq\PluginApi\Version10\ToolReportInterface; final class ConsoleOutputToolReportProcessor implements PostProcessorInterface { /** * @var string */ private $toolName; /** * ConsoleOutputToolReportProcessor constructor. * * @param string $toolName */ public function __construct(string $toolName) { $this->toolName = $toolName; } /** * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function process( ToolReportInterface $report, string $consoleOutput, int $exitCode, OutputInterface $output ): void { if (0 !== $exitCode) { $report->addError('error', $consoleOutput); } $report->finish(0 === $exitCode ? ToolReportInterface::STATUS_PASSED : ToolReportInterface::STATUS_FAILED); } }
Change keras to use dtensor public API. PiperOrigin-RevId: 438605222
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keras' DTensor library.""" _DTENSOR_API_ENABLED = False # Conditional import the dtensor API, since it is currently broken in OSS. if _DTENSOR_API_ENABLED: from tensorflow.compat.v2.experimental import dtensor as dtensor_api # pylint: disable=g-import-not-at-top else: # Leave it with a placeholder, so that the import line from other python file # will not break. dtensor_api = None
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keras' DTensor library.""" _DTENSOR_API_ENABLED = False # Conditional import the dtensor API, since it is currently broken in OSS. if _DTENSOR_API_ENABLED: # pylint: disable=g-direct-tensorflow-import, g-import-not-at-top from tensorflow.dtensor import python as dtensor_api else: # Leave it with a placeholder, so that the import line from other python file # will not break. dtensor_api = None
Revise return hint of method signature
<?php /** * @author Guidance Magento Team <magento@guidance.com> * @category Guidance * @package Simplepage * @copyright Copyright (c) 2015 Guidance Solutions (http://www.guidance.com) */ /** * Class Guidance_Simplepage_Block_ContentType * * @method string getContentType() * @method Guidance_Simplepage_Block_ContentType setContentType(string $value) */ class Guidance_Simplepage_Block_ContentType extends Mage_Core_Block_Abstract { protected function _beforeToHtml() { $contentType = $this->getContentType(); if (!is_null($this->getContentType())) { $this->getAction()->getResponse()->setHeader('Content-type', $contentType, true); } return $this; } }
<?php /** * @author Guidance Magento Team <magento@guidance.com> * @category Guidance * @package Simplepage * @copyright Copyright (c) 2015 Guidance Solutions (http://www.guidance.com) */ /** * Class Guidance_Simplepage_Block_ContentType * * @method float getContentType() * @method Guidance_Simplepage_Block_ContentType setContentType(string $value) */ class Guidance_Simplepage_Block_ContentType extends Mage_Core_Block_Abstract { protected function _beforeToHtml() { $contentType = $this->getContentType(); if (!is_null($this->getContentType())) { $this->getAction()->getResponse()->setHeader('Content-type', $contentType, true); } return $this; } }
Use make infallible for win load handlers
/* See license.txt for terms of usage */ "use strict"; const { Cu } = require("chrome"); const { Trace, TraceError } = require("../core/trace.js").get(module.id); const { once } = require("sdk/dom/events.js"); const { getMostRecentBrowserWindow } = require("sdk/window/utils"); const { openTab } = require("sdk/tabs/utils"); const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); const { makeInfallible } = devtools["require"]("devtools/toolkit/DevToolsUtils.js"); // Module implementation var Win = {}; /** * Returns a promise that is resolved as soon as the window is loaded * or immediately if the window is already loaded. * * @param {Window} The window object we need use when loaded. */ Win.loaded = makeInfallible(win => new Promise(resolve => { if (win.document.readyState === "complete") { resolve(win.document); } else { once(win, "load", event => resolve(event.target)); } })); // xxxHonza: we might want to merge with Win.loaded Win.domContentLoaded = makeInfallible(win => new Promise(resolve => { if (win.document.readyState === "complete") { resolve(win.document); } else { once(win, "DOMContentLoaded", event => resolve(event.target)); } })); Win.openNewTab = function(url, options) { let browser = getMostRecentBrowserWindow(); openTab(browser, url, options); } // Exports from this module exports.Win = Win;
/* See license.txt for terms of usage */ "use strict"; const { Trace, TraceError } = require("../core/trace.js").get(module.id); const { once } = require("sdk/dom/events.js"); const { getMostRecentBrowserWindow } = require("sdk/window/utils"); const { openTab } = require("sdk/tabs/utils"); // Module implementation var Win = {}; /** * Returns a promise that is resolved as soon as the window is loaded * or immediately if the window is already loaded. * * @param {Window} The window object we need use when loaded. */ Win.loaded = win => new Promise(resolve => { if (win.document.readyState === "complete") { resolve(win.document); } else { once(win, "load", event => resolve(event.target)); } }); // xxxHonza: we might want to merge with Win.loaded Win.domContentLoaded = win => new Promise(resolve => { if (win.document.readyState === "complete") { resolve(win.document); } else { once(win, "DOMContentLoaded", event => resolve(event.target)); } }); Win.openNewTab = function(url, options) { let browser = getMostRecentBrowserWindow(); openTab(browser, url, options); } // Exports from this module exports.Win = Win;
Fix JavaDoc tags for Java8
package com.auth0.net; import com.auth0.exception.APIException; import com.auth0.exception.Auth0Exception; import java.util.concurrent.CompletableFuture; /** * Class that represents an HTTP Request that can be executed. * * @param <T> the type of payload expected in the response after the execution. */ public interface Request<T> { /** * Executes this request synchronously. * * @return the response body JSON decoded as T * @throws APIException if the request was executed but the response wasn't successful. * @throws Auth0Exception if the request couldn't be created or executed successfully. */ T execute() throws Auth0Exception; /** * Executes this request asynchronously. * * Note: This method was added after the interface was released in version 1.0. * It is defined as a default method for compatibility reasons. * From version 2.0 on, the method will be abstract and all implementations of this interface * will have to provide their own implementation. * * The default implementation throws an {@linkplain UnsupportedOperationException}. * * @return a {@linkplain CompletableFuture} representing the specified request. */ default CompletableFuture<T> executeAsync() { throw new UnsupportedOperationException("executeAsync"); } }
package com.auth0.net; import com.auth0.exception.APIException; import com.auth0.exception.Auth0Exception; import java.util.concurrent.CompletableFuture; /** * Class that represents an HTTP Request that can be executed. * * @param <T> the type of payload expected in the response after the execution. */ public interface Request<T> { /** * Executes this request synchronously. * * @return the response body JSON decoded as T * @throws APIException if the request was executed but the response wasn't successful. * @throws Auth0Exception if the request couldn't be created or executed successfully. */ T execute() throws Auth0Exception; /** * Executes this request asynchronously. * * @apiNote This method was added after the interface was released in version 1.0. * It is defined as a default method for compatibility reasons. * From version 2.0 on, the method will be abstract and all implementations of this interface * will have to provide their own implementation. * * @implSpec The default implementation throws an {@linkplain UnsupportedOperationException}. * * @return a {@linkplain CompletableFuture} representing the specified request. */ default CompletableFuture<T> executeAsync() { throw new UnsupportedOperationException("executeAsync"); } }
Allow passing extra data to sentry
#!/usr/bin/env python # encoding: utf-8 import logging from raven.contrib.flask import Sentry from framework.sessions import get_session from website import settings logger = logging.getLogger(__name__) sentry = Sentry(dsn=settings.SENTRY_DSN) # Nothing in this module should send to Sentry if debug mode is on # or if Sentry isn't configured. enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN def get_session_data(): try: return get_session().data except (RuntimeError, AttributeError): return {} def log_exception(): if not enabled: logger.warning('Sentry called to log exception, but is not active') return None return sentry.captureException(extra={ 'session': get_session_data(), }) def log_message(message, extra={}): if not enabled: logger.warning( 'Sentry called to log message, but is not active: %s' % message ) return None return sentry.captureMessage(message, extra=extra)
#!/usr/bin/env python # encoding: utf-8 import logging from raven.contrib.flask import Sentry from framework.sessions import get_session from website import settings logger = logging.getLogger(__name__) sentry = Sentry(dsn=settings.SENTRY_DSN) # Nothing in this module should send to Sentry if debug mode is on # or if Sentry isn't configured. enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN def get_session_data(): try: return get_session().data except (RuntimeError, AttributeError): return {} def log_exception(): if not enabled: logger.warning('Sentry called to log exception, but is not active') return None return sentry.captureException(extra={ 'session': get_session_data(), }) def log_message(message): if not enabled: logger.warning( 'Sentry called to log message, but is not active: %s' % message ) return None return sentry.captureMessage(message, extra={ 'session': get_session_data(), })
Disable strict C90 flag that appears to be accidentally being used by distutils
#!/usr/local/bin/python3 from distutils.core import setup, Extension # Workaround -Werror=statement-after-declaration # http://bugs.python.org/issue18211 import os os.environ['CFLAGS'] = '-Wno-unused-result' setup( name = 'lazy', version = '1.0', description = 'Lazy', ext_modules = [ Extension( name = 'b._collections', sources = [ 'src/collections.c', ], ), Extension( name = 'b._types', depends = [ 'include/memoizer.h', ], include_dirs = [ 'include', ], sources = [ 'src/memoizer.c', 'src/types.c', ], ), ], )
#!/usr/local/bin/python3 from distutils.core import setup, Extension setup( name = 'lazy', version = '1.0', description = 'Lazy', ext_modules = [ Extension( name = 'b._collections', sources = [ 'src/collections.c', ], ), Extension( name = 'b._types', depends = [ 'include/memoizer.h', ], include_dirs = [ 'include', ], sources = [ 'src/memoizer.c', 'src/types.c', ], ), ], )
Add tracks to playlist on update
from rest_framework import serializers from .models import Playlist, Track, Favorite class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = '__all__' class PlaylistSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Playlist fields = ('id', 'playlist_name', 'user_id', 'tracks') def create(self, validated_data): tracks_data = validated_data.pop('tracks') playlist = Playlist.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(**track_data) return playlist def update(self, instance, validated_data): tracks_data = validated_data.pop('tracks') instance.playlist_name = validated_data.get('playlist_name', instance.playlist_name) instance.save() Track.objects.filter(playlist=instance.id).delete() for track_data in tracks_data: track_id = Track.objects.create(**track_data) instance.tracks.add(track_id) instance.save() return Playlist.objects.get(pk=instance.id) class FavoriteSerializer(serializers.ModelSerializer): class Meta: model = Favorite fields = '__all__'
from rest_framework import serializers from .models import Playlist, Track, Favorite class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = '__all__' class PlaylistSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Playlist fields = ('id', 'playlist_name', 'user_id', 'tracks') def create(self, validated_data): tracks_data = validated_data.pop('tracks') playlist = Playlist.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(**track_data) return playlist def update(self, instance, validated_data): tracks_data = validated_data.pop('tracks') instance.playlist_name = validated_data.get('playlist_name', instance.playlist_name) instance.save() Track.objects.filter(playlist=instance.id).delete() for track_data in tracks_data: Track.objects.create(**track_data) instance.tracks.add(track_id) instance.save() return Playlist.objects.get(pk=instance.id) class FavoriteSerializer(serializers.ModelSerializer): class Meta: model = Favorite fields = '__all__'
Use us-east-1 to query route53 Route53 is a global service so doesn't belong to a region, but the API endpoint is in us-east-1. This makes various listings now work, but not record sets. Updates #4.
import boto3 _CLIENTS = {} def get_regions_for_service(service, regions=()): """Given a service name, return a list of region names where this service can have resources, restricted by a possible set of regions.""" if service == "s3": return ['us-east-1'] # s3 ListBuckets is a global request, so no region required. if service == "route53": return ['us-east-1'] # route53 is a global service, but the endpoint is in us-east-1. service_regions = boto3.Session().get_available_regions(service) if regions: # If regions were passed, return the intersecion. return [r for r in regions if r in service_regions] else: return service_regions def get_client(service, region=None): """Return (cached) boto3 clients for this service and this region""" if (service, region) not in _CLIENTS: _CLIENTS[(service, region)] = boto3.Session(region_name=region).client(service) return _CLIENTS[(service, region)]
import boto3 _CLIENTS = {} def get_regions_for_service(service, regions=()): """Given a service name, return a list of region names where this service can have resources, restricted by a possible set of regions.""" if service == "s3": return ['us-east-1'] # s3 ListBuckets is a global request, so no region required. service_regions = boto3.Session().get_available_regions(service) if regions: # If regions were passed, return the intersecion. return [r for r in regions if r in service_regions] else: return service_regions def get_client(service, region=None): """Return (cached) boto3 clients for this service and this region""" if (service, region) not in _CLIENTS: _CLIENTS[(service, region)] = boto3.Session(region_name=region).client(service) return _CLIENTS[(service, region)]
FIX update status help to match new CSS
<?php class Default_View_Helper_StatusHelp extends Zend_View_Helper_Abstract { public function statusHelp() { $result = '<ul>'; $result .= '<li><span class="status current status_need"><span>' . Default_Model_Status::$ratings[Default_Model_Status::Need] . '</span></span>: ' . $this->view->translate('I want to see this movie') . '</li>'; $result .= '<li><span class="status current status_bad"><span>' . Default_Model_Status::$ratings[Default_Model_Status::Bad] . '</span></span>: ' . $this->view->translate('Boring movie, I wasted my time') . '</li>'; $result .= '<li><span class="status current status_ok"><span>' . Default_Model_Status::$ratings[Default_Model_Status::Ok] . '</span></span>: ' . $this->view->translate('Enjoyable movie (most movies)') . '</li>'; $result .= '<li><span class="status current status_excellent"><span>' . Default_Model_Status::$ratings[Default_Model_Status::Excellent] . '</span></span>: ' . $this->view->translate('Excellent, I would watch it twice') . '</li>'; $result .= '<li><span class="status current status_favorite"><span>' . Default_Model_Status::$ratings[Default_Model_Status::Favorite] . '</span></span>: ' . $this->view->translate('Incredibly awesome, the kind of movie you must watch many times regurlarly') . '</li>'; $result .= '</ul>'; return $result; } } ?>
<?php class Default_View_Helper_StatusHelp extends Zend_View_Helper_Abstract { public function statusHelp() { $result = '<ul>'; $result .= '<li><span class="status current status_need">' . $this->view->translate('Need') . '</span>: ' . $this->view->translate('I want to see this movie') . '</li>'; $result .= '<li><span class="status current status_bad">' . $this->view->translate('Bad') . '</span>: ' . $this->view->translate('Boring movie, I wasted my time') . '</li>'; $result .= '<li><span class="status current status_ok">' . $this->view->translate('OK') . '</span>: ' . $this->view->translate('Enjoyable movie (most movies)') . '</li>'; $result .= '<li><span class="status current status_excellent">' . $this->view->translate('Excellent') . '</span>: ' . $this->view->translate('Really good, I would watch it twice') . '</li>'; $result .= '<li><span class="status current status_favorite">' . $this->view->translate('Favorite') . '</span>: ' . $this->view->translate('Incredibly awesome, the kind of movie you must watch many times regurlarly') . '</li>'; $result .= '</ul>'; return $result; } } ?>
Make sure that we're testing properly
<?php /** * Copyright (c) 2016 RhubarbPHP. * * 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. */ namespace Rhubarb\Crown\Tests\unit\String; use Rhubarb\Crown\String\Template; use Rhubarb\Crown\Tests\Fixtures\TestCases\RhubarbTestCase; class TemplateTest extends RhubarbTestCase { public function testTemplateParsing() { $plainTextTemplate = "Nothing in here to parse"; $this->assertEquals($plainTextTemplate, Template::parseTemplate($plainTextTemplate, [])); $template = "Ah something to process! {Forename}"; $this->assertEquals( "Ah something to process! Andrew", Template::parseTemplate($template, ["Forename" => "Andrew"]) ); $template = "Something to parse, but that you can't parse, because there is no {data}"; $this->assertEquals( $template, Template::parseTemplate($template, []) ); } }
<?php /** * Copyright (c) 2016 RhubarbPHP. * * 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. */ namespace Rhubarb\Crown\Tests\unit\String; use Rhubarb\Crown\String\Template; use Rhubarb\Crown\Tests\Fixtures\TestCases\RhubarbTestCase; class TemplateTest extends RhubarbTestCase { public function testTemplateParsing() { $plainTextTemplate = "Nothing in here to parse"; $this->assertEquals($plainTextTemplate, Template::parseTemplate($plainTextTemplate, [])); $template = "Ah something to process! {Forename}"; $this->assertEquals( "Ah something to process! Andrew", Template::parseTemplate($template, ["Forename" => "Andrew"]) ); $template = "Something to parse, but that you can't parse, because there is no data"; $this->assertEquals( $template, Template::parseTemplate($template, []) ); } }
Make sure everything is correct version
/** * FIRST Team 1699 * * Abstract Command Class * * @author squirlemaster42, FIRST Team 1699 * * @version v0.2-norobot */ package org.usfirst.frc.team1699.utils.command; public abstract class Command { private String name; private int id; // id is used for commands run in auto. It should be set to an integer // value that corresponds to // the value used when wanting to call the command from the autonomous file. public Command(String name, int id) { this.name = name; this.id = id; // Add code to add name and id to respective lists } public abstract void init(); public abstract void run(); public abstract void outputToDashBoard(); // Output all data to dash board public abstract void zeroAllSensors(); // zeroAllSensors may need to be // looked at and changed // public abstract boolean isFinished(); Not used at this time may change in // the future. public String getName() { return name; } public int getId() { return id; } @Override public String toString() { return "Command [name=" + name + ", id=" + id + "]"; } }
/** * FIRST Team 1699 * * Abstract Command Class * * @author squirlemaster42, FIRST Team 1699 * * @version v0.2-norobot */ package org.usfirst.frc.team1699.utils.command; public abstract class Command { private String name; private int id; // id is used for commands run in auto. It should be set to an integer // value that corresponds to // the value used when wanting to call the command from the autonomous file. public Command(String name, int id) { this.name = name; this.id = id; //Add code to add name and id to respective lists } public abstract void init(); public abstract void run(); public abstract void outputToDashBoard(); //Output all data to dash board public abstract void zeroAllSensors(); // zeroAllSensors may need to be looked at and changed //public abstract boolean isFinished(); Not used at this time may change in the future. public String getName() { return name; } public int getId() { return id; } @Override public String toString() { return "Command [name=" + name + ", id=" + id + "]"; } }
Correct CC img being mislinked on subpages.
/** * Small config file to define website-related constants */ module.exports = { author: 'Severin Fürbringer', name: `Personal Site by Severin Fürbringer`, brand: 'SF', titleSeparator: ' ⇐ ', allowRobots: true, licenseLegal: 'https://creativecommons.org/licenses/by-sa/4.0/legalcode', license: 'https://creativecommons.org/licenses/by-sa/4.0/', licenseImage: '/images/cc_by_sa.png', indexBlogPreview: { maxCount: 3 }, pages: { about: { title: 'About' }, blog: { title: 'Blog' }, contact: { title: 'Contact' }, home: { title: 'Welcome' }, now: { title: 'Now' }, } }
/** * Small config file to define website-related constants */ module.exports = { author: 'Severin Fürbringer', name: `Personal Site by Severin Fürbringer`, brand: 'SF', titleSeparator: ' ⇐ ', allowRobots: true, licenseLegal: 'https://creativecommons.org/licenses/by-sa/4.0/legalcode', license: 'https://creativecommons.org/licenses/by-sa/4.0/', licenseImage: 'images/cc_by_sa.png', indexBlogPreview: { maxCount: 3 }, pages: { about: { title: 'About' }, blog: { title: 'Blog' }, contact: { title: 'Contact' }, home: { title: 'Welcome' }, now: { title: 'Now' }, } }
Put docstring inside Server class
#!/usr/bin/python import threading, socket class Server(threading.Thread): """ Dummy server using for unit testing """ def __init__(self, handler, host='localhost', port=8021): threading.Thread.__init__(self) self.handler = handler self.host = host self.port = port self.ready_event = threading.Event() self.stop_event = threading.Event() def run(self): sock = socket.socket() sock.bind((self.host, self.port)) sock.listen(0) self.ready_event.set() self.handler(sock) self.stop_event.set() sock.close() def __enter__(self): self.start() self.ready_event.wait() return self.host, self.port def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: self.stop_event.wait() return False # allow exceptions to propagate
#!/usr/bin/python import threading, socket """ Dummy server using for unit testing """ class Server(threading.Thread): def __init__(self, handler, host='localhost', port=8021): threading.Thread.__init__(self) self.handler = handler self.host = host self.port = port self.ready_event = threading.Event() self.stop_event = threading.Event() def run(self): sock = socket.socket() sock.bind((self.host, self.port)) sock.listen(0) self.ready_event.set() self.handler(sock) self.stop_event.set() sock.close() def __enter__(self): self.start() self.ready_event.wait() return self.host, self.port def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: self.stop_event.wait() return False # allow exceptions to propagate
Add support for new @mention command syntax
/* Require modules */ var nodeTelegramBot = require('node-telegram-bot') , config = require('./config.json') , request = require("request") , cheerio = require("cheerio"); /* Functions */ /** * Uses the request module to return the body of a web page * @param {string} url * @param {callback} callback * @return {string} */ function getWebContent(url, callback){ request({ uri: url, }, function(error, response, body) { callback(body); }); } /* Logic */ var recipeURL = 'http://www.cookstr.com/searches/surprise'; var bot = new nodeTelegramBot({ token: config.token }) .on('message', function (message) { /* Process "/dinner" command */ if (message.text == "/dinner" || message.text == "/dinner@WhatToEatBot") { console.log(message); getWebContent(recipeURL, function(data){ // Parse DOM and recipe informations var $ = cheerio.load(data) , recipeName = $("meta[property='og:title']").attr('content') , recipeURL = $("meta[property='og:url']").attr('content'); // Send bot reply bot.sendMessage({ chat_id: message.chat.id, text: 'What about "' + recipeName + '"? ' + recipeURL }); }); } }) .start();
/* Require modules */ var nodeTelegramBot = require('node-telegram-bot') , config = require('./config.json') , request = require("request") , cheerio = require("cheerio"); /* Functions */ /** * Uses the request module to return the body of a web page * @param {string} url * @param {callback} callback * @return {string} */ function getWebContent(url, callback){ request({ uri: url, }, function(error, response, body) { callback(body); }); } /* Logic */ var recipeURL = 'http://www.cookstr.com/searches/surprise'; var bot = new nodeTelegramBot({ token: config.token }) .on('message', function (message) { /* Process "/random" command */ if (message.text == "/dinner") { console.log(message); getWebContent(recipeURL, function(data){ // Parse DOM and recipe informations var $ = cheerio.load(data) , recipeName = $("meta[property='og:title']").attr('content') , recipeURL = $("meta[property='og:url']").attr('content'); // Send bot reply bot.sendMessage({ chat_id: message.chat.id, text: 'What about "' + recipeName + '"? ' + recipeURL }); }); } }) .start();
fix(Core): Exclude Laminas modules from module version widget.
<?php /** * YAWIK * * @filesource * @license MIT * @copyright 2013 - 2016 Cross Solution <http://cross-solution.de> */ /** */ namespace Core\Listener; use Core\Controller\AdminControllerEvent; use Core\ModuleManager\Feature\VersionProviderInterface; use Laminas\ModuleManager\ModuleManager; /** * ${CARET} * * @author Mathias Gelhausen <gelhausen@cross-solution.de> * @todo write test */ class ModuleVersionAdminWidgetProvider { /** * * * @var ModuleManager */ private $moduleManager; public function __construct(ModuleManager $moduleManager) { $this->moduleManager = $moduleManager; } public function __invoke(AdminControllerEvent $event) { /* @var \Core\Controller\AdminController $controller */ $modules = $this->moduleManager->getLoadedModules(); $modules = array_filter( $modules, function($i) { return 0 !== strpos($i, 'Laminas\\') && 0 !== strpos($i, 'Doctrine'); }, ARRAY_FILTER_USE_KEY ); ksort($modules); $event->addViewTemplate('modules', 'core/admin/module-version-widget.phtml', ['modules' => $modules], 100); } }
<?php /** * YAWIK * * @filesource * @license MIT * @copyright 2013 - 2016 Cross Solution <http://cross-solution.de> */ /** */ namespace Core\Listener; use Core\Controller\AdminControllerEvent; use Core\ModuleManager\Feature\VersionProviderInterface; use Laminas\ModuleManager\ModuleManager; /** * ${CARET} * * @author Mathias Gelhausen <gelhausen@cross-solution.de> * @todo write test */ class ModuleVersionAdminWidgetProvider { /** * * * @var ModuleManager */ private $moduleManager; public function __construct(ModuleManager $moduleManager) { $this->moduleManager = $moduleManager; } public function __invoke(AdminControllerEvent $event) { /* @var \Core\Controller\AdminController $controller */ $modules = $this->moduleManager->getLoadedModules(); $modules = array_filter( $modules, function($i) { return 0 !== strpos($i, 'Zend\\') && 0 !== strpos($i, 'Doctrine'); }, ARRAY_FILTER_USE_KEY ); ksort($modules); $event->addViewTemplate('modules', 'core/admin/module-version-widget.phtml', ['modules' => $modules], 100); } }
Use historyId as filter instead of threadId
'use strict'; /** * @file Retrieve threads from the account */ var googleapis = require('googleapis'); // Retrieve all threads associated with this user account, // using refresh_token // starting from message #`cursor`. module.exports = function retrieveThreads(options, cursor, threads, cb) { options.q = "-is:chat after:" + cursor.date.getFullYear() + "/" + (cursor.date.getMonth() + 1) + "/" + cursor.date.getDate(); googleapis.gmail('v1').users.threads .list(options, function(err, res) { if(err) { return cb(err); } // We can't use a cursor in the query, so we need to do the sorting ourselves res.threads.reverse(); threads = threads.concat(res.threads.filter(function(thread) { return parseInt(thread.historyId, 16) > cursor.id; })); if(res.nextPageToken) { options.pageToken = res.nextPageToken; retrieveThreads(options, cursor, threads, cb); } else { cb(null, { date: new Date((new Date()).getTime() - 1000 * 3600 * 24), id: threads.length > 0 ? parseInt(threads[threads.length - 1].historyId, 16) : cursor.id }, threads); } }); };
'use strict'; /** * @file Retrieve threads from the account */ var googleapis = require('googleapis'); // Retrieve all threads associated with this user account, // using refresh_token // starting from message #`cursor`. module.exports = function retrieveThreads(options, cursor, threads, cb) { options.q = "-is:chat after:" + cursor.date.getFullYear() + "/" + (cursor.date.getMonth() + 1) + "/" + cursor.date.getDate(); googleapis.gmail('v1').users.threads .list(options, function(err, res) { if(err) { return cb(err); } // We can't use a cursor in the query, so we need to do the sorting ourselves res.threads.reverse(); threads = threads.concat(res.threads.filter(function(thread) { return parseInt(thread.id, 16) > cursor.id; })); if(res.nextPageToken) { options.pageToken = res.nextPageToken; retrieveThreads(options, cursor, threads, cb); } else { cb(null, { date: new Date((new Date()).getTime() - 1000 * 3600 * 24), id: threads.length > 0 ? parseInt(threads[threads.length - 1].id, 16) : cursor.id }, threads); } }); };
Use the first HarvestCraft crop's texture in its iconArray (asparagus) as the crops block's blockIcon
package squeek.harvestcraftwaila.fixers; import net.minecraft.block.Block; import net.minecraft.util.Icon; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.EventPriority; import net.minecraftforge.event.ForgeSubscribe; import assets.pamharvestcraft.BlockPamCrop; import assets.pamharvestcraft.PamHarvestCraft; import cpw.mods.fml.common.ObfuscationReflectionHelper; import cpw.mods.fml.relauncher.ReflectionHelper; public class IconFixer { @ForgeSubscribe(priority = EventPriority.NORMAL) public void onPostTextureStitch(TextureStitchEvent.Post event) { try { Icon icon = ((BlockPamCrop) PamHarvestCraft.pamCrop).iconArray[0][0]; ReflectionHelper.setPrivateValue(Block.class, PamHarvestCraft.pamCrop, icon, ObfuscationReflectionHelper.remapFieldNames(Block.class.getName(), "blockIcon", "field_94336_cN", "cW")); } catch (Exception e) { e.printStackTrace(); } } }
package squeek.harvestcraftwaila.fixers; import net.minecraft.block.Block; import net.minecraft.util.Icon; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.EventPriority; import net.minecraftforge.event.ForgeSubscribe; import assets.pamharvestcraft.PamHarvestCraft; import cpw.mods.fml.common.ObfuscationReflectionHelper; import cpw.mods.fml.relauncher.ReflectionHelper; public class IconFixer { @ForgeSubscribe(priority = EventPriority.NORMAL) public void onPostTextureStitch(TextureStitchEvent.Post event) { try { Icon icon = Block.crops.getIcon(0, 0); ReflectionHelper.setPrivateValue(Block.class, PamHarvestCraft.pamCrop, icon, ObfuscationReflectionHelper.remapFieldNames(Block.class.getName(), "blockIcon", "field_94336_cN", "cW")); } catch (Exception e) { e.printStackTrace(); } } }
Use a timeout to handle position fixed only on scroll
// ==UserScript== // @name Remove Position Fixed // @namespace name.robgant // @description Makes some things on the page with position fixed become static. Adds a menu command to run the script. // @include * // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue // ==/UserScript== function unfix_position() { // console.log("Unfixing Positions!!"); Array.forEach( document.querySelectorAll("div, header, section, nav") ,function(el) { if (window.getComputedStyle(el).position === 'fixed') { el.style.position = 'static'; el.style.cssText += ';position:static !important;'; } } ); } GM_registerMenuCommand("Position Unfixed", unfix_position); function set_default_unfix() { var domain = window.location.host; GM_setValue(domain, true); } GM_registerMenuCommand("Default Unfixed", set_default_unfix); var domain = window.location.host; if (GM_getValue(domain, false)) { // console.log("Default Unfixed Position"); window.addEventListener("scroll", function(evt){ window.setTimeout(unfix_position, 800); window.removeEventListener("scroll", arguments.callee); }, false); } //else { console.log("Not Default Unfixed Position"); }
// ==UserScript== // @name Remove Position Fixed // @namespace name.robgant // @description Makes anything on the page with position fixed become static // @include * // @version 1 // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue // ==/UserScript== function unfix_position() { // console.log("Unfixing Positions!!"); Array.forEach( document.querySelectorAll("div, header, section, nav") ,function(el) { if (window.getComputedStyle(el).position === 'fixed') { el.style.position = 'static'; el.style.cssText += ';position:static !important;'; } } ); } GM_registerMenuCommand("Position Unfixed", unfix_position); function set_default_unfix() { var domain = window.location.host; GM_setValue(domain, true); } GM_registerMenuCommand("Default Unfixed", set_default_unfix); var domain = window.location.host; if (GM_getValue(domain, false)) { // console.log("Default Unfixed Position"); window.addEventListener("scroll", function(evt){ unfix_position(); window.removeEventListener("scroll", arguments.callee); }, false); } //else { console.log("Not Default Unfixed Position"); }