text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Set language choices based on user locale.
'use strict'; /** * @ngdoc directive * @name translapediaApp.directive:translateInput * @description * # translateInput */ angular.module('translapediaApp') .directive('translateInput', function () { return { restrict: 'E', templateUrl: 'views/directives/translate-input.html', controller: function ($scope, $rootScope, $location, languageCodes, $locale) { var previousTranslation = $rootScope.translation || {}; var userLocale = $locale.id.substr(0,2); $scope.term = previousTranslation.originalTerm || ''; $scope.toLangId = previousTranslation.toLangId || (userLocale === 'pt' ? 'en' : 'pt'); $scope.fromLangId = previousTranslation.fromLangId || userLocale || 'en'; $scope.languages = Object.keys(languageCodes).map(function(key) { return { id: key, text: languageCodes[key] }; }); $scope.translate = function () { $location.path('/translate').search({ term: $scope.term, from: $scope.fromLangId, to: $scope.toLangId }); }; } }; });
'use strict'; /** * @ngdoc directive * @name translapediaApp.directive:translateInput * @description * # translateInput */ angular.module('translapediaApp') .directive('translateInput', function () { return { restrict: 'E', templateUrl: 'views/directives/translate-input.html', controller: function ($scope, $rootScope, $location, languageCodes) { var previousTranslation = $rootScope.translation || {}; $scope.term = previousTranslation.originalTerm || ''; $scope.toLangId = previousTranslation.toLangId || 'pt'; $scope.fromLangId = previousTranslation.fromLangId || 'en'; $scope.languages = Object.keys(languageCodes).map(function(key) { return { id: key, text: languageCodes[key] }; }); $scope.translate = function () { $location.path('/translate').search({ term: $scope.term, from: $scope.fromLangId, to: $scope.toLangId }); }; } }; });
Add further constrains to create_dataset To clarify that it capped_size must be zero or a positive integer.
from __future__ import unicode_literals import json import requests from django.conf import settings class BackdropError(Exception): pass def create_dataset(name, capped_size): """ Connect to Backdrop and create a new collection called ``name``. Specify ``capped_size`` in bytes to create a capped collection, or 0 to create an uncapped collection. """ if not isinstance(capped_size, int) or capped_size < 0: raise BackdropError( "capped_size must be 0 or a positive integer number of bytes.") json_request = json.dumps({'capped_size': capped_size}) backdrop_url = '{url}/data-sets/{name}'.format( url=settings.BACKDROP_URL, name=name) auth_header = ( 'Authorization', 'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN)) type_header = ('content-type', 'application/json') try: response = requests.post( backdrop_url, headers=dict([type_header, auth_header]), data=json_request) response.raise_for_status() except Exception as e: raise BackdropError(repr(e))
from __future__ import unicode_literals import json import requests from django.conf import settings class BackdropError(Exception): pass def create_dataset(name, capped_size): """ Connect to Backdrop and create a new collection called ``name``. Specify ``capped_size`` in bytes to create a capped collection, or 0 to create an uncapped collection. """ assert isinstance(capped_size, int) json_request = json.dumps({'capped_size': capped_size}) backdrop_url = '{url}/data-sets/{name}'.format( url=settings.BACKDROP_URL, name=name) auth_header = ( 'Authorization', 'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN)) type_header = ('content-type', 'application/json') try: response = requests.post( backdrop_url, headers=dict([type_header, auth_header]), data=json_request) response.raise_for_status() except Exception as e: raise BackdropError(repr(e))
Build in support for writing mha files.
""" DataWriter.py """ from DataController import DataController from DataReader import DataReader from vtk import vtkMetaImageWriter from vtk import vtkXMLImageDataWriter class DataWriter(DataController): """ DataWriter writes an image data object to disk using the provided format. """ def __init__(self): super(DataWriter, self).__init__() self.supportedExtensions = [DataReader.TypeMHD, DataReader.TypeVTI, DataReader.TypeMHA] def WriteToFile(self, imageData, exportFileName, fileType): if fileType == DataReader.TypeMHD: if not exportFileName.endswith(".mhd"): exportFileName = exportFileName + ".mhd" writer = vtkMetaImageWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() elif fileType == DataReader.TypeVTI: writer = vtkXMLImageDataWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() elif fileType == DataReader.TypeMHA: writer = vtkMetaImageWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() else: raise NotImplementedError("No writing support for type " + str(fileType))
""" DataWriter.py """ from DataController import DataController from DataReader import DataReader from vtk import vtkMetaImageWriter from vtk import vtkXMLImageDataWriter class DataWriter(DataController): """ DataWriter writes an image data object to disk using the provided format. """ def __init__(self): super(DataWriter, self).__init__() self.supportedExtensions = [DataReader.TypeMHD, DataReader.TypeVTI] def WriteToFile(self, imageData, exportFileName, fileType): if fileType == DataReader.TypeMHD: if not exportFileName.endswith(".mhd"): exportFileName = exportFileName + ".mhd" writer = vtkMetaImageWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() elif fileType == DataReader.TypeVTI: writer = vtkXMLImageDataWriter() writer.SetFileName(exportFileName) writer.SetInputData(imageData) writer.Write() else: raise NotImplementedError("No writing support for type " + str(fileType))
Add a property that allows the web server to start automatically during initialization
package com.aspectran.with.jetty; import com.aspectran.core.component.bean.ablility.DisposableBean; import com.aspectran.core.component.bean.ablility.InitializableBean; import com.aspectran.core.util.logging.Log; import com.aspectran.core.util.logging.LogFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.ThreadPool; /** * <p>Created: 2016. 12. 22.</p> */ public class JettyServer extends Server implements InitializableBean, DisposableBean { private static final Log log = LogFactory.getLog(JettyServer.class); private boolean autoStart; public JettyServer() { super(); } public JettyServer(int port) { super(port); } public JettyServer(ThreadPool pool) { super(pool); } public void setAutoStart(boolean autoStart) { this.autoStart = autoStart; } @Override public void initialize() throws Exception { System.setProperty("org.apache.jasper.compiler.disablejsr199", "false"); if (autoStart) { start(); } } @Override public void destroy() { try { stop(); } catch (Exception e) { log.error("JettyServer shutdown failed", e); } } }
package com.aspectran.with.jetty; import com.aspectran.core.component.bean.ablility.DisposableBean; import com.aspectran.core.component.bean.ablility.InitializableBean; import com.aspectran.core.util.logging.Log; import com.aspectran.core.util.logging.LogFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.ThreadPool; /** * <p>Created: 2016. 12. 22.</p> */ public class JettyServer extends Server implements InitializableBean, DisposableBean { private static final Log log = LogFactory.getLog(JettyServer.class); public JettyServer() { super(); } public JettyServer(int port) { super(port); } public JettyServer(ThreadPool pool) { super(pool); } @Override public void initialize() throws Exception { System.setProperty("org.apache.jasper.compiler.disablejsr199", "false"); } @Override public void destroy() { try { stop(); } catch (Exception e) { log.error("JettyServer shutdown failed", e); } } }
Use README.md instead of README.rst
#-*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='zerows', version='1.0.0', description='Websockets built on top of tornado & zeromq', long_description=long_description, url='https://github.com/sebastianlach/zerows', author='Sebastian Łach', author_email='root@slach.eu', license='MIT', keywords='zerows zero ws zeromq tornado websocket', packages=['zerows'], install_requires=['tornado'], entry_points={ 'console_scripts': [ 'zerows=zerows:main', ], }, classifiers=[ 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Topic :: System :: Networking', 'Operating System :: Unix', ], )
#-*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='zerows', version='1.0.0', description='Websockets built on top of tornado & zeromq', long_description=long_description, url='https://github.com/sebastianlach/zerows', author='Sebastian Łach', author_email='root@slach.eu', license='MIT', keywords='zerows zero ws zeromq tornado websocket', packages=['zerows'], install_requires=['tornado'], entry_points={ 'console_scripts': [ 'zerows=zerows:main', ], }, classifiers=[ 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Topic :: System :: Networking', 'Operating System :: Unix', ], )
Refactor carousel image references for better readability
app.controller('HomeController', ['$http', 'AuthFactory', function($http, AuthFactory) { console.log('HomeController running'); var self = this; self.userStatus = AuthFactory.userStatus; self.dataArray = [ { src: '../assets/images/carousel/genome-sm.jpg' }, { src: '../assets/images/carousel/falkirk-wheel-sm.jpg' }, { src: '../assets/images/carousel/iss-sm.jpg' }, { src: '../assets/images/carousel/shark-sm.jpg' }, { src: '../assets/images/carousel/snowflake-sm.jpg' }, { src: '../assets/images/carousel/virus-sm.jpg' }, { src: '../assets/images/carousel/rock-formation-sm.jpg' }, { src: '../assets/images/carousel/circuit-board-sm.jpg' } ]; }]);
app.controller('HomeController', ['$http', 'AuthFactory', function($http, AuthFactory) { console.log('HomeController running'); var self = this; self.userStatus = AuthFactory.userStatus; self.dataArray = [{ src: '../assets/images/carousel/genome-sm.jpg' }, { src: '../assets/images/carousel/falkirk-wheel-sm.jpg' }, { src: '../assets/images/carousel/iss-sm.jpg' }, { src: '../assets/images/carousel/shark-sm.jpg' }, { src: '../assets/images/carousel/snowflake-sm.jpg' }, { src: '../assets/images/carousel/virus-sm.jpg' }, { src: '../assets/images/carousel/rock-formation-sm.jpg' }, { src: '../assets/images/carousel/circuit-board-sm.jpg' } ]; }]);
Tweak layer list overflow settings to auto
// gerber file output component 'use strict' const {h} = require('deku') const GerberSettings = require('./gerber-settings') const {LayerDefs} = require('../../layer/component') module.exports = function renderGerberOutput({props}) { const {layers, layerDisplayStates, renders, units} = props const { toggleVisibility, toggleSettings, remove, setType, setConversionOpts, setColor } = props const children = layers.map((layer) => { const id = layer.id return h(GerberSettings, { layer, showSettings: layerDisplayStates[id].showSettings, toggleVisibility: toggleVisibility(id), toggleSettings: toggleSettings(id), remove: remove(id), setType: setType(id), setConversionOpts: setConversionOpts, setColor: setColor(id) }) }) return h('output', {class: 'fx fx-d-c bg-white-90 clickable max-app-ht'}, [ h('ol', { class: 'list ma0 ph0 pv2 fx-1-1 overflow-y-auto' }, children), h('p', {class: 'ma0 pa1 tc fx-0-0'}, [`${children.length} files`]), h('svg', {class: 'clip'}, [ h(LayerDefs, {renders, units}) ]) ]) }
// gerber file output component 'use strict' const {h} = require('deku') const GerberSettings = require('./gerber-settings') const {LayerDefs} = require('../../layer/component') module.exports = function renderGerberOutput({props}) { const {layers, layerDisplayStates, renders, units} = props const { toggleVisibility, toggleSettings, remove, setType, setConversionOpts, setColor } = props const children = layers.map((layer) => { const id = layer.id return h(GerberSettings, { layer, showSettings: layerDisplayStates[id].showSettings, toggleVisibility: toggleVisibility(id), toggleSettings: toggleSettings(id), remove: remove(id), setType: setType(id), setConversionOpts: setConversionOpts, setColor: setColor(id) }) }) return h('output', {class: 'fx fx-d-c bg-white-90 clickable max-app-ht'}, [ h('ol', { class: 'list ma0 ph0 pv2 fx-1-1 overflow-scroll' }, children), h('p', {class: 'ma0 pa1 tc fx-0-0'}, [`${children.length} files`]), h('svg', {class: 'clip'}, [ h(LayerDefs, {renders, units}) ]) ]) }
Use for...of loops where appropriate
'use strict'; // // --- Aggregator // function Aggregator(defaultTags) { this.buffer = {}; this.defaultTags = defaultTags || []; } Aggregator.prototype.makeBufferKey = function(key, tags) { tags = tags || ['']; return key + '#' + tags.concat().sort().join('.'); }; Aggregator.prototype.addPoint = function(Type, key, value, tags, host, timestampInMillis, options) { const bufferKey = this.makeBufferKey(key, tags); if (!this.buffer.hasOwnProperty(bufferKey)) { this.buffer[bufferKey] = new Type(key, tags, host, options); } this.buffer[bufferKey].addPoint(value, timestampInMillis); }; Aggregator.prototype.flush = function() { let series = []; for (const item of Object.values(this.buffer)) { series = series.concat(item.flush()); } // Concat default tags if (this.defaultTags) { for (const metric of series) { metric.tags = this.defaultTags.concat(metric.tags); } } this.buffer = {}; return series; }; module.exports = { Aggregator: Aggregator };
'use strict'; // // --- Aggregator // function Aggregator(defaultTags) { this.buffer = {}; this.defaultTags = defaultTags || []; } Aggregator.prototype.makeBufferKey = function(key, tags) { tags = tags || ['']; return key + '#' + tags.concat().sort().join('.'); }; Aggregator.prototype.addPoint = function(Type, key, value, tags, host, timestampInMillis, options) { const bufferKey = this.makeBufferKey(key, tags); if (!this.buffer.hasOwnProperty(bufferKey)) { this.buffer[bufferKey] = new Type(key, tags, host, options); } this.buffer[bufferKey].addPoint(value, timestampInMillis); }; Aggregator.prototype.flush = function() { let series = []; for (let key in this.buffer) { if (this.buffer.hasOwnProperty(key)) { series = series.concat(this.buffer[key].flush()); } } // Concat default tags if (this.defaultTags) { for (let i = 0; i < series.length; i++) { series[i].tags = this.defaultTags.concat(series[i].tags); } } this.buffer = {}; return series; }; module.exports = { Aggregator: Aggregator };
Add missing redirect after POST in product details
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return redirect('product:details', slug=slug, product_id=product_id) return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form}) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category})
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form }) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category })
Add Python 3 to supported platforms
# -*- coding: utf-8 -*- """ nose-notify ~~~~~~~~~~~ A nose plugin to display testsuite progress in the notify osd. :copyright: 2010, Pascal Hartig <phartig@rdrei.net> :license: BSD, see LICENSE for more details """ from setuptools import setup from nosenotify import __version__ setup( name="nose-notify", version=__version__, author="Pascal Hartig", author_email="phartig@rdrei.de", description="A nose plugin to display testsuite progress " "in the notify osd", url="https://github.com/passy/nose-notify", packages=['nosenotify'], package_data={'nosenotify': ['images/*']}, long_description=__doc__, requires=['nose (>=0.10)'], classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Testing", "Topic :: Software Development :: Libraries :: Python Modules" ], entry_points={ 'nose.plugins.0.10': [ 'notify = nosenotify.plugin:NotifyPlugin' ] } )
# -*- coding: utf-8 -*- """ nose-notify ~~~~~~~~~~~ A nose plugin to display testsuite progress in the notify osd. :copyright: 2010, Pascal Hartig <phartig@rdrei.net> :license: BSD, see LICENSE for more details """ from setuptools import setup from nosenotify import __version__ setup( name="nose-notify", version=__version__, author="Pascal Hartig", author_email="phartig@rdrei.de", description="A nose plugin to display testsuite progress " "in the notify osd", url="https://github.com/passy/nose-notify", packages=['nosenotify'], package_data={'nosenotify': ['images/*']}, long_description=__doc__, requires=['nose (>=0.10)'], classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Testing", "Topic :: Software Development :: Libraries :: Python Modules" ], entry_points={ 'nose.plugins.0.10': [ 'notify = nosenotify.plugin:NotifyPlugin' ] } )
Remove ranking from denormalization command
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Performance, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v in vs: v.save() ts = Contest.objects.all() for t in ts: t.save() cs = Contestant.objects.all() for c in cs: c.save() ps = Performance.objects.all() for p in ps: p.save() return "Done"
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Performance, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v in vs: v.save() ts = Contest.objects.all() for t in ts: t.save() cs = Contestant.objects.all() for c in cs: c.save() ps = Performance.objects.all() for p in ps: p.save() for t in ts: t.rank() return "Done"
Determine GPU presence on workers based on instance metadata
""" Grab worker configuration from GCloud instance attributes. """ import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu" MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text == "true" with open("config.json", "w") as configfile: json.dump({ "MANAGER_URL": MANAGER_URL, "SECRET_FOLDER": SECRET_FOLDER, "CAPABILITIES": ["gpu"] if HAS_GPU else [], }, configfile)
""" Grab worker configuration from GCloud instance attributes. """ import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text with open("config.json", "w") as configfile: json.dump({ "MANAGER_URL": MANAGER_URL, "SECRET_FOLDER": SECRET_FOLDER, }, configfile)
stdlib: Make api directly available in stdlib
""" :py:mod:`leapp.libraries.stdlib` represents a location for functions that otherwise would be defined multiple times across leapp actors and at the same time, they are really useful for other actors. """ import six import subprocess import os from leapp.libraries.stdlib import api def call(args, split=True): """ Call an external program, capture and automatically utf-8 decode its ouput. Then, supress output to stderr and redirect to /dev/null. :param args: Command to execute :type args: list :param split: Split the output on newlines :type split: bool :return: stdout output, 'utf-8' decoded, split by lines if split=True :rtype: unicode/str or [unicode/str] if split=True """ r = None with open(os.devnull, mode='w') as err: if six.PY3: r = subprocess.check_output(args, stderr=err, encoding='utf-8') else: r = subprocess.check_output(args, stderr=err).decode('utf-8') if split: return r.splitlines() return r
""" :py:mod:`leapp.libraries.stdlib` represents a location for functions that otherwise would be defined multiple times across leapp actors and at the same time, they are really useful for other actors. """ import six import subprocess import os def call(args, split=True): """ Call an external program, capture and automatically utf-8 decode its ouput. Then, supress output to stderr and redirect to /dev/null. :param args: Command to execute :type args: list :param split: Split the output on newlines :type split: bool :return: stdout output, 'utf-8' decoded, split by lines if split=True :rtype: unicode/str or [unicode/str] if split=True """ r = None with open(os.devnull, mode='w') as err: if six.PY3: r = subprocess.check_output(args, stderr=err, encoding='utf-8') else: r = subprocess.check_output(args, stderr=err).decode('utf-8') if split: return r.splitlines() return r
Test fail not to deploy
from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb, i will fail')
from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb')
Fix the memory leak issue on idle timeout
/** * Emulates stream.setTimeout() behaviour, but respects outgoing data * too. * * @param {Number} timeout Milliseconds */ exports.attach = function(stream, timeout) { var timer; var emitTimeout = function() { timer = undefined; stream.emit('timeout'); }; var updateTimer = function() { if (timer) clearTimeout(timer); timer = setTimeout(emitTimeout, timeout); }; var oldWrite = stream.write; stream.write = function() { updateTimer(); oldWrite.apply(this, arguments); }; stream.addListener('data', updateTimer); stream.addListener('close', function() { if (timer) clearTimeout(timer); stream.write = oldWrite; }); stream.addListener('end', function() { if (timer) clearTimeout(timer); stream.write = oldWrite; }); };
/** * Emulates stream.setTimeout() behaviour, but respects outgoing data * too. * * @param {Number} timeout Milliseconds */ exports.attach = function(stream, timeout) { var timer; var emitTimeout = function() { timer = undefined; stream.emit('timeout'); }; var updateTimer = function() { if (timer) clearTimeout(timer); timer = setTimeout(emitTimeout, timeout); }; var oldWrite = stream.write; stream.write = function() { updateTimer(); oldWrite.apply(this, arguments); }; stream.addListener('data', updateTimer); stream.addListener('close', function() { if (timer) clearTimeout(timer); }); };
Revert "fix transfer form unlock wallet issue" This reverts commit 9510fcaea98c9f569c0176500efebcbc0d648a8a.
import alt from "alt-instance" import WalletUnlockActions from "actions/WalletUnlockActions" import WalletDb from "stores/WalletDb" class WalletUnlockStore { constructor() { this.bindActions(WalletUnlockActions) this.state = {locked: true} } onUnlock({resolve, reject}) { //DEBUG console.log('... onUnlock setState', WalletDb.isLocked()) if( ! WalletDb.isLocked()) { resolve(false) return } this.setState({resolve, reject, locked: WalletDb.isLocked()}) } onLock({resolve}) { //DEBUG console.log('... WalletUnlockStore\tprogramatic lock', WalletDb.isLocked()) if(WalletDb.isLocked()) { resolve(false) return } WalletDb.onLock() resolve(true) this.setState({resolve:null, reject:null, locked: WalletDb.isLocked()}) } onCancel() { this.setState({resolve:null, reject:null}) } onChange() { this.setState({locked: WalletDb.isLocked()}) } } export default alt.createStore(WalletUnlockStore, 'WalletUnlockStore')
import alt from "alt-instance" import WalletUnlockActions from "actions/WalletUnlockActions" import WalletDb from "stores/WalletDb" class WalletUnlockStore { constructor() { this.bindActions(WalletUnlockActions) this.state = {locked: true} } onUnlock({resolve, reject}) { let locked = WalletDb.isLocked() if(!locked) resolve(true) else this.setState({resolve, reject, locked}) } onLock({resolve}) { //DEBUG console.log('... WalletUnlockStore\tprogramatic lock', WalletDb.isLocked()) if(WalletDb.isLocked()) { resolve(false) return } WalletDb.onLock() resolve(true) this.setState({resolve:null, reject:null, locked: WalletDb.isLocked()}) } onCancel() { this.setState({resolve:null, reject:null}) } onChange() { this.setState({locked: WalletDb.isLocked()}) } } export default alt.createStore(WalletUnlockStore, 'WalletUnlockStore')
Add directory for state files
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License from distutils.core import setup setup(name='htcondor-es-probes', version='0.6.3', description='HTCondor probes for Elasticsearch analytics', author='Suchandra Thapa', author_email='sthapa@ci.uchicago.edu', url='https://github.com/DHTC-Tools/logstash-confs/tree/master/condor', packages=['probe_libs'], scripts=['collect_history_info.py', 'get_job_status.py'], data_files=[('/etc/init.d/', ['scripts/collect_history']), ('/etc/cron.d/', ['config/schedd_probe']), ('/var/lib/collect_history', []), ('/etc/sysconfig', ['config/collect_history'])], license='Apache 2.0' )
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License from distutils.core import setup setup(name='htcondor-es-probes', version='0.6.3', description='HTCondor probes for Elasticsearch analytics', author='Suchandra Thapa', author_email='sthapa@ci.uchicago.edu', url='https://github.com/DHTC-Tools/logstash-confs/tree/master/condor', packages=['probe_libs'], scripts=['collect_history_info.py', 'get_job_status.py'], data_files=[('/etc/init.d/', ['scripts/collect_history']), ('/etc/cron.d/', ['config/schedd_probe']), ('/etc/sysconfig', ['config/collect_history'])], license = 'Apache 2.0' )
Rename method and remove debugging code
var App = angular.module('Ohtu-Hatut', []); App.controller('ReferenceController', function ($scope, $http) { getReferences(); $scope.confirmDeletion = function (referenceId) { console.log("got into deleteion"); if (confirm("Confirm deletion of reference") === true) { $scope.references.splice(getReferenceIndex(referenceId), 1); $http.post('/references/' + referenceId + '/delete'); } }; function getReferenceIndex(id) { for (var i = 0; i < $scope.references.length; i++) { if ($scope.references[i].id === id) { return i; } } } function getReferences() { $http.get('/references/json') .then(function (response) { $scope.references = response.data; }); } });
var App = angular.module('Ohtu-Hatut', []); App.controller('ReferenceController', function ($scope, $http) { getReferences(); $scope.confirmDeletion = function (referenceId) { console.log("got into deleteion"); if (confirm("Confirm deletion of reference") === true) { $scope.references.splice(getReference(referenceId), 1); $http.post('/references/' + referenceId + '/delete'); } }; function getReference(id) { for (var i = 0; i < $scope.references.length; i++) { if ($scope.references[i].id === id) { console.log("löydettiin") return i; } } } function getReferences() { $http.get('/references/json') .then(function (response) { $scope.references = response.data; }); } });
Fix Error: The method addTestSuite(Class<? extends TestCase>) in the type TestSuite is not applicable for the arguments (Class<TaskTemplateVariableResolver>) TaskTemplateVariableResolver is now TaskTemplateResolverTest
/******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.ide.tests; import junit.framework.Test; import junit.framework.TestSuite; /** * @author Mik Kersten */ public class AllIdeTests { public static Test suite() { TestSuite suite = new TestSuite("Test for org.eclipse.mylyn.ide.tests"); suite.addTestSuite(OpenCorrespondingTaskActionTest.class); suite.addTestSuite(IdeStartupTest.class); suite.addTestSuite(IdePreferencesTest.class); suite.addTestSuite(TaskTemplateResolverTest.class); return suite; } }
/******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.ide.tests; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.mylyn.internal.ide.ui.TaskTemplateVariableResolver; /** * @author Mik Kersten */ public class AllIdeTests { public static Test suite() { TestSuite suite = new TestSuite("Test for org.eclipse.mylyn.ide.tests"); suite.addTestSuite(OpenCorrespondingTaskActionTest.class); suite.addTestSuite(IdeStartupTest.class); suite.addTestSuite(IdePreferencesTest.class); suite.addTestSuite(TaskTemplateVariableResolver.class); return suite; } }
Introduce option to set text formField's value without triggering `change`
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input': function() { this.trigger('blur'); }, 'focus input': function() { this.trigger('focus'); } }, /** * @param {String} value * @param {Boolean} [skipTriggerChange] */ setValue: function(value, skipTriggerChange) { this._skipTriggerChange = skipTriggerChange; this.$('input').val(value); this._skipTriggerChange = false; }, setFocus: function() { this.$('input').focus(); }, enableTriggerChange: function() { var self = this; var $input = this.$('input'); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; if (!self._skipTriggerChange) { self.trigger('change'); } } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', events: { 'blur input': function() { this.trigger('blur'); }, 'focus input': function() { this.trigger('focus'); } }, /** * @param {String} value */ setValue: function(value) { this.$('input').val(value); }, setFocus: function() { this.$('input').focus(); }, enableTriggerChange: function() { var self = this; var $input = this.$('input'); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; self.trigger('change'); } }; // IE9: `propertychange` and `keyup` needed additionally $input.on('input propertychange keyup', callback); } });
Allow cron jobs to be long lasting
<?php /** * This class provides some common cron controller functionality * * @package Nails * @subpackage module-cron * @category Controller * @author Nails Dev Team * @link */ namespace Nails\Cron\Controller; class Base extends \MX_Controller { protected $oCronRouter; // -------------------------------------------------------------------------- /** * Construct the controller */ public function __construct($oCronRouter) { parent::__construct(); $this->oCronRouter = $oCronRouter; // -------------------------------------------------------------------------- // By default cron jobs should be long lasting if (function_exists('set_time_limit')) { set_time_limit(0); } } // -------------------------------------------------------------------------- /** * Writes a line to the log * @param string $sLine the line to write */ protected function writeLog($sLine) { $this->oCronRouter->writeLog($sLine); } }
<?php /** * This class provides some common cron controller functionality * * @package Nails * @subpackage module-cron * @category Controller * @author Nails Dev Team * @link */ namespace Nails\Cron\Controller; class Base extends \MX_Controller { protected $oCronRouter; // -------------------------------------------------------------------------- /** * Construct the controller */ public function __construct($oCronRouter) { parent::__construct(); $this->oCronRouter = $oCronRouter; } // -------------------------------------------------------------------------- /** * Writes a line to the log * @param string $sLine the line to write */ protected function writeLog($sLine) { $this->oCronRouter->writeLog($sLine); } }
Fix session driver in cached config.
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; class ConfigCacheCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'config:cache'; /** * The console command description. * * @var string */ protected $description = 'Create a cache file for faster configuration loading'; /** * Execute the console command. * * @return void */ public function fire() { $this->call('config:clear'); $config = $this->getFreshConfiguration(); $config = $this->setRealSessionDriver($config); file_put_contents( $this->laravel->getCachedConfigPath(), '<?php return '.var_export($config, true).';'.PHP_EOL ); $this->info('Configuration cached successfully!'); } /** * Boot a fresh copy of the application configuration. * * @return \Illuminate\Routing\RouteCollection */ protected function getFreshConfiguration() { $app = require $this->laravel['path.base'].'/bootstrap/app.php'; $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap(); return $app['config']->all(); } /** * Set the "real" session driver on the configuratoin array. * * Typically the SessionManager forces the driver to "array" in CLI environment. * * @param array $config * @return array */ protected function setRealSessionDriver(array $config) { $session = require $this->laravel->configPath().'/session.php'; $config['session']['driver'] = $session['driver']; return $config; } }
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; class ConfigCacheCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'config:cache'; /** * The console command description. * * @var string */ protected $description = 'Create a cache file for faster configuration loading'; /** * Execute the console command. * * @return void */ public function fire() { $this->call('config:clear'); $config = $this->getFreshConfiguration(); file_put_contents( $this->laravel->getCachedConfigPath(), '<?php return '.var_export($config, true).';'.PHP_EOL ); $this->info('Configuration cached successfully!'); } /** * Boot a fresh copy of the application configuration. * * @return \Illuminate\Routing\RouteCollection */ protected function getFreshConfiguration() { $app = require $this->laravel['path.base'].'/bootstrap/app.php'; $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap(); return $app['config']->all(); } }
Fix tests for the new config format used in the init command
<?php namespace Liip\RMT\Tests\Functional; use Symfony\Component\Yaml\Yaml; class InitCommandTest extends RMTFunctionalTestBase { public function testInitConfig() { $configFile = '.rmt.yml'; unlink($configFile); $this->assertFileNotExists($configFile); exec('./RMT init --vcs=git --generator=semantic-versioning --persister=vcs-tag -n'); // $this->manualDebug(); $this->assertFileExists($configFile); $config = Yaml::parse(file_get_contents($configFile), true); $defaultConfig = $config["_default"]; $masterConfig = $config["master"]; $this->assertEquals('git', $defaultConfig['vcs']); $this->assertEquals('simple', $defaultConfig['version-generator']); $this->assertEquals('semantic', $masterConfig['version-generator']); $this->assertEquals(array("vcs-tag"=>array("tag-prefix"=>"{branch-name}_")), $defaultConfig['version-persister']); $this->assertEquals(array("vcs-tag"=>array("tag-prefix"=>"")), $masterConfig['version-persister']); } }
<?php namespace Liip\RMT\Tests\Functional; use Symfony\Component\Yaml\Yaml; class InitCommandTest extends RMTFunctionalTestBase { public function testInitConfig() { $configFile = '.rmt.yml'; unlink($configFile); $this->assertFileNotExists($configFile); // $this->manualDebug(); exec('./RMT init --vcs=git --generator=semantic-versioning --persister=vcs-tag -n'); $this->assertFileExists($configFile); $config = Yaml::parse(file_get_contents($configFile), true); $masterConfig = $config["branch-specific"]["master"]; $this->assertEquals('git', $config['vcs']); $this->assertEquals('simple', $config['version-generator']); $this->assertEquals('semantic', $masterConfig['version-generator']); $this->assertEquals(array("vcs-tag"=>array("tag-prefix"=>"{branch-name}_")), $config['version-persister']); $this->assertEquals(array("vcs-tag"=>array("tag-prefix"=>"")), $masterConfig['version-persister']); } }
Disable lint for line with unused var
/*eslint-disable react/no-danger*/ import React from "react"; import serialize from "serialize-javascript"; import path from "path"; import process from "process"; // Make sure path ends in forward slash let assetPath = require(path.resolve(path.join(process.cwd(), "src", "config", "application"))).default.assetPath; if (assetPath.substr(-1) !== "/") { assetPath = assetPath + "/"; } const isProduction = process.env.NODE_ENV === "production"; // eslint-disable-next-line no-unused-vars export default (config, entryPoint, assets) => { const tags = []; let key = 0; if (isProduction) { tags.push(<link key={key++} rel="stylesheet" type="text/css" href={`${config.assetPath}/${entryPoint}.css`} />); } tags.push( <script key={key++} type="text/javascript" dangerouslySetInnerHTML={{__html: `window.__GS_PUBLIC_PATH__ = ${serialize(assetPath)}; window.__GS_ENVIRONMENT__ = ${serialize(process.env.NODE_ENV)}`}}></script> ); return tags; };
/*eslint-disable react/no-danger*/ import React from "react"; import serialize from "serialize-javascript"; import path from "path"; import process from "process"; // Make sure path ends in forward slash let assetPath = require(path.resolve(path.join(process.cwd(), "src", "config", "application"))).default.assetPath; if (assetPath.substr(-1) !== "/") { assetPath = assetPath + "/"; } const isProduction = process.env.NODE_ENV === "production"; export default (config, entryPoint, assets) => { const tags = []; let key = 0; if (isProduction) { tags.push(<link key={key++} rel="stylesheet" type="text/css" href={`${config.assetPath}/${entryPoint}.css`} />); } tags.push( <script key={key++} type="text/javascript" dangerouslySetInnerHTML={{__html: `window.__GS_PUBLIC_PATH__ = ${serialize(assetPath)}; window.__GS_ENVIRONMENT__ = ${serialize(process.env.NODE_ENV)}`}}></script> ); return tags; };
Fix missing table name in alter_table
"""id(pirmary key) for torsion_init_mol Revision ID: 1604623c481a Revises: fb5bd88ae2f3 Create Date: 2020-07-02 18:42:17.267792 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "1604623c481a" down_revision = "fb5bd88ae2f3" branch_labels = None depends_on = None def upgrade(): # Removes (harmless) duplicate rows op.execute( "DELETE FROM torsion_init_mol_association a USING \ (SELECT MIN(ctid) as ctid, torsion_id, molecule_id \ FROM torsion_init_mol_association \ GROUP BY torsion_id, molecule_id HAVING COUNT(*) > 1 \ ) b \ WHERE a.torsion_id = b.torsion_id and a.molecule_id = b.molecule_id \ AND a.ctid <> b.ctid" ) op.execute("alter table torsion_init_mol_association add primary key (torsion_id, molecule_id)") def downgrade(): op.execute("alter table torsion_init_mol_association drop constraint torsion_init_mol_association_pkey")
"""id(pirmary key) for torsion_init_mol Revision ID: 1604623c481a Revises: fb5bd88ae2f3 Create Date: 2020-07-02 18:42:17.267792 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "1604623c481a" down_revision = "fb5bd88ae2f3" branch_labels = None depends_on = None def upgrade(): op.execute( "DELETE FROM torsion_init_mol_association a USING \ (SELECT MIN(ctid) as ctid, torsion_id, molecule_id \ FROM torsion_init_mol_association \ GROUP BY torsion_id, molecule_id HAVING COUNT(*) > 1 \ ) b \ WHERE a.torsion_id = b.torsion_id and a.molecule_id = b.molecule_id \ AND a.ctid <> b.ctid" ) op.execute("alter table add primary key (torsion_id, molecule_id)") def downgrade(): op.execute("alter table drop constraint torsion_init_mol_association_pkey")
Use official OSI name in the license metadata This makes it easier for automatic license checkers to verify the license of this package. The license file is included in MANIFEST.in as is standard practice.
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except: from distutils.core import setup long_description = "" with open('README.rst') as f: long_description = f.read() setup( name='ImageHash', version='4.2.1', author='Johannes Buchner', author_email='buchner.johannes@gmx.at', py_modules=['imagehash'], data_files=[('images', ['tests/data/imagehash.png'])], scripts=['find_similar_images.py'], url='https://github.com/JohannesBuchner/imagehash', license='2-clause BSD License', description='Image Hashing library', long_description=long_description, long_description_content_type='text/x-rst', install_requires=[ "six", "numpy", "scipy", # for phash "pillow", # or PIL "PyWavelets", # for whash ], test_suite='tests', tests_require=['pytest>=3'], )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except: from distutils.core import setup long_description = "" with open('README.rst') as f: long_description = f.read() setup( name='ImageHash', version='4.2.1', author='Johannes Buchner', author_email='buchner.johannes@gmx.at', py_modules=['imagehash'], data_files=[('images', ['tests/data/imagehash.png'])], scripts=['find_similar_images.py'], url='https://github.com/JohannesBuchner/imagehash', license='BSD 2-clause (see LICENSE file)', description='Image Hashing library', long_description=long_description, long_description_content_type='text/x-rst', install_requires=[ "six", "numpy", "scipy", # for phash "pillow", # or PIL "PyWavelets", # for whash ], test_suite='tests', tests_require=['pytest>=3'], )
Change code to be PEP-8 compliant
# # Copyright 2014-2015 Boundary, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions configured within a Boundary account"
### ### Copyright 2014-2015 Boundary, Inc. ### ### Licensed under the Apache License, Version 2.0 (the "License"); ### you may not use this file except in compliance with the License. ### You may obtain a copy of the License at ### ### http://www.apache.org/licenses/LICENSE-2.0 ### ### Unless required by applicable law or agreed to in writing, software ### distributed under the License is distributed on an "AS IS" BASIS, ### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ### See the License for the specific language governing permissions and ### limitations under the License. ### from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions associated with the Boundary account"
Make \r in topics optional
package de.tuberlin.dima.schubotz.fse.mappers; import eu.stratosphere.api.java.functions.FlatMapFunction; import eu.stratosphere.util.Collector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Cleans main task queries. TODO find way to do this using stratosphere built in data input? * Required due to Stratosphere split on {@link de.tuberlin.dima.schubotz.fse.MainProgram#QUERY_SEPARATOR} */ public class QueryCleaner extends FlatMapFunction<String, String> { Log LOG = LogFactory.getLog(QueryCleaner.class); @Override public void flatMap(String in, Collector<String> out) throws Exception { //TODO: check if \r is required if (in.trim().length() == 0 || in.startsWith("\r\n</topics>")) { if (LOG.isWarnEnabled()) { LOG.warn("Corrupt query " + in); } return; } if (in.startsWith("<?xml")) { in += "</topic></topics>"; }else if (!in.endsWith( "</topic>" )) { in += "</topic>"; } out.collect(in); } }
package de.tuberlin.dima.schubotz.fse.mappers; import eu.stratosphere.api.java.functions.FlatMapFunction; import eu.stratosphere.util.Collector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Cleans main task queries. TODO find way to do this using stratosphere built in data input? * Required due to Stratosphere split on {@link de.tuberlin.dima.schubotz.fse.MainProgram#QUERY_SEPARATOR} */ public class QueryCleaner extends FlatMapFunction<String, String> { Log LOG = LogFactory.getLog(QueryCleaner.class); @Override public void flatMap(String in, Collector<String> out) throws Exception { if (in.trim().length() == 0 || in.startsWith("\r\n</topics>")) { if (LOG.isWarnEnabled()) { LOG.warn("Corrupt query " + in); } return; } if (in.startsWith("<?xml")) { in += "</topic></topics>"; }else if (!in.endsWith( "</topic>" )) { in += "</topic>"; } out.collect(in); } }
Fix typo in fxml name
package com.annimon.jmr; import com.annimon.jmr.controllers.MainController; import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml")); Scene scene = new Scene(loader.load()); primaryStage.setTitle("JMethodRearranger"); primaryStage.setScene(scene); MainController controller = loader.getController(); controller.setPrimaryStage(primaryStage); primaryStage.show(); } }
package com.annimon.jmr; import com.annimon.jmr.controllers.MainController; import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Main.fxml")); Scene scene = new Scene(loader.load()); primaryStage.setTitle("JMethodRearranger"); primaryStage.setScene(scene); MainController controller = loader.getController(); controller.setPrimaryStage(primaryStage); primaryStage.show(); } }
Bump to next dev 0.1.2.dev1
#!/usr/bin/env python3 # encoding: utf-8 from setuptools import setup, find_packages setup( name='pyatv', version='0.1.2.dev1', license='MIT', url='https://github.com/postlund/pyatv', author='Pierre Ståhl', author_email='pierre.staahl@gmail.com', description='Library for controlling an Apple TV', packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'aiohttp==1.2.0', 'zeroconf==0.18.0', ], test_suite='tests', keywords=['apple', 'tv'], tests_require=['tox'], entry_points={ 'console_scripts': [ 'atvremote = pyatv.__main__:main' ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries', 'Topic :: Home Automation', ], )
#!/usr/bin/env python3 # encoding: utf-8 from setuptools import setup, find_packages setup( name='pyatv', version='0.1.1', license='MIT', url='https://github.com/postlund/pyatv', author='Pierre Ståhl', author_email='pierre.staahl@gmail.com', description='Library for controlling an Apple TV', packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'aiohttp==1.2.0', 'zeroconf==0.18.0', ], test_suite='tests', keywords=['apple', 'tv'], tests_require=['tox'], entry_points={ 'console_scripts': [ 'atvremote = pyatv.__main__:main' ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries', 'Topic :: Home Automation', ], )
Rename method 'testExample' to 'testRegister'
<?php use App\UserRegistrationRequest; use Illuminate\Foundation\Testing\DatabaseMigrations; class RegisterTest extends TestCase { use DatabaseMigrations; /** * A basic test example. */ public function testRegister() { $code = new UserRegistrationRequest(); $code->id = 1234567; $code->code = 'XXXXX-XXXXX-XXXXX'; $code->save(); $this->visit('/register') ->type($code->id, 'id') ->type($code->code, 'code') ->type('Fox', 'first_name') ->type('Red', 'middle_name') ->type('Snow', 'last_name') ->type('snow_fox@gmail.com', 'email') ->type('fox123', 'password') ->type('fox123', 'password_confirmation') ->press('Register') ->seePageIs('/home'); } }
<?php use App\UserRegistrationRequest; use Illuminate\Foundation\Testing\DatabaseMigrations; class RegisterTest extends TestCase { use DatabaseMigrations; /** * A basic test example. */ public function testExample() { $code = new UserRegistrationRequest(); $code->id = 1234567; $code->code = 'XXXXX-XXXXX-XXXXX'; $code->save(); $this->visit('/register') ->type($code->id, 'id') ->type($code->code, 'code') ->type('Fox', 'first_name') ->type('Red', 'middle_name') ->type('Snow', 'last_name') ->type('snow_fox@gmail.com', 'email') ->type('fox123', 'password') ->type('fox123', 'password_confirmation') ->press('Register') ->seePageIs('/home'); } }
Add date range filter to short url repository interface
<?php declare(strict_types=1); namespace Shlinkio\Shlink\Core\Repository; use Doctrine\Common\Persistence\ObjectRepository; use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\ShortUrl; interface ShortUrlRepositoryInterface extends ObjectRepository { /** * Gets a list of elements using provided filtering data * * @param string|array|null $orderBy */ public function findList( ?int $limit = null, ?int $offset = null, ?string $searchTerm = null, array $tags = [], $orderBy = null, ?DateRange $dateRange = null ): array; /** * Counts the number of elements in a list using provided filtering data */ public function countList(?string $searchTerm = null, array $tags = []): int; public function findOneByShortCode(string $shortCode, ?string $domain = null): ?ShortUrl; public function shortCodeIsInUse(string $slug, ?string $domain): bool; }
<?php declare(strict_types=1); namespace Shlinkio\Shlink\Core\Repository; use Doctrine\Common\Persistence\ObjectRepository; use Shlinkio\Shlink\Core\Entity\ShortUrl; interface ShortUrlRepositoryInterface extends ObjectRepository { /** * Gets a list of elements using provided filtering data * * @param string|array|null $orderBy */ public function findList( ?int $limit = null, ?int $offset = null, ?string $searchTerm = null, array $tags = [], $orderBy = null ): array; /** * Counts the number of elements in a list using provided filtering data */ public function countList(?string $searchTerm = null, array $tags = []): int; public function findOneByShortCode(string $shortCode, ?string $domain = null): ?ShortUrl; public function shortCodeIsInUse(string $slug, ?string $domain): bool; }
Fix parsing when style specified, add 'auto' score
"""Docstring parsing.""" from . import rest from .common import ParseError, Docstring _styles = {"rest": rest.parse} def _parse_score(docstring: Docstring) -> int: """ Produce a score for the parsing. :param Docstring docstring: parsed docstring representation :returns int: parse score, higher is better """ score = 0 if docstring.short_description: score += 1 if docstring.long_description: score += docstring.long_description.count('\n') score += len(docstring.params) score += len(docstring.raises) if docstring.returns: score += 2 return score def parse(text: str, style: str = 'auto') -> Docstring: """ Parse the docstring into its components. :param str text: docstring text to parse :param str style: docstring style, choose from: 'rest', 'auto' :returns Docstring: parsed docstring representation """ if style == 'auto': rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc return sorted(rets, key=_parse_score, reverse=True)[0] else: return _styles[style](text)
"""Docstring parsing.""" from . import rest from .common import ParseError _styles = {"rest": rest.parse} def parse(text: str, style: str = "auto"): """ Parse the docstring into its components. :param str text: docstring text to parse :param text style: docstring style, choose from: 'rest', 'auto' :returns: parsed docstring """ if style == "auto": rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc return sorted(rets, key=lambda ret: len(ret.meta), reverse=True)[0] else: return _styles[style]
Fix (Observation test): change methode name
<?php namespace AppBundle\TestsService; use AppBundle\Service\ObservationService; use AppBundle\Entity\Observation; use PHPUnit\Framework\TestCase; use OC\BookingBundle\Service\Utils; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; class ObservationTest extends WebTestCase { protected static $translation; protected static $em; public static function setUpBeforeClass() { $kernel = static::createKernel(); $kernel->boot(); self::$translation = $kernel->getContainer()->get('translator'); self::$em = $kernel->getContainer()->get('doctrine.orm.entity_manager'); } /** * Get last 3 Observations * * @return [type] [description] */ public function testObservations() { $ts = new TokenStorage(); $obs = new ObservationService(self::$em, $ts); $result = $obs->getLastObersations(2); $this->assertCount(2, $result); } }
<?php namespace AppBundle\TestsService; use AppBundle\Service\ObservationService; use AppBundle\Entity\Observation; use PHPUnit\Framework\TestCase; use OC\BookingBundle\Service\Utils; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; class ObservationTest extends WebTestCase { protected static $translation; protected static $em; public static function setUpBeforeClass() { $kernel = static::createKernel(); $kernel->boot(); self::$translation = $kernel->getContainer()->get('translator'); self::$em = $kernel->getContainer()->get('doctrine.orm.entity_manager'); } /** * Get last 3 Observations * * @return [type] [description] */ public function testObservations() { $ts = new TokenStorage(); $obs = new ObservationService(self::$em, $ts); $result = $obs->getLastObservations(2); $this->assertCount(2, $result); } }
Fix typo in compat mode attrs test.
import View from "ember-views/views/view"; import { runAppend, runDestroy } from "ember-runtime/tests/utils"; import compile from "ember-template-compiler/system/compile"; import Registry from "container/registry"; var view, registry, container; QUnit.module("ember-views: attrs-proxy", { setup() { registry = new Registry(); container = registry.container(); }, teardown() { runDestroy(view); } }); QUnit.skip('works with properties setup in root of view', function() { registry.register('view:foo', View.extend({ bar: 'qux', template: compile('{{view.bar}}') })); view = View.extend({ container: registry.container(), template: compile('{{view "foo" bar="baz"}}') }).create(); runAppend(view); equal(view.$().text(), 'baz', 'value specified in the template is used'); });
import View from "ember-views/views/view"; import { runAppend, runDestroy } from "ember-runtime/tests/utils"; import compile from "ember-template-compiler/system/compile"; import Registry from "container/registry"; var view, registry, container; QUnit.module("ember-views: attrs-proxy", { setup() { registry = new Registry(); container = registry.container(); }, teardown() { runDestroy(view); } }); QUnit.skip('works with properties setup in root of view', function() { registry.register('view:foo', View.extend({ bar: 'qux', template: compile('{{bar}}') })); view = View.extend({ container: registry.container(), template: compile('{{view "foo" bar="baz"}}') }).create(); runAppend(view); equal(view.$().text(), 'baz', 'value specified in the template is used'); });
Update HTMLManager in the documentation Signed-off-by: martinRenou <a8278cece597ec79cc59974d3d55dbb79bb38416@gmail.com>
# -*- coding: utf-8 -*- import sphinx_rtd_theme extensions = [ # 'sphinx.ext.autodoc', # 'sphinx.ext.intersphinx', # 'sphinx.ext.autosummary', # 'sphinx.ext.viewcode', # 'sphinx.ext.napoleon', # 'jupyter_sphinx.embed_widgets', ] templates_path = ['_templates'] def setup(app): app.add_javascript("https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js") app.add_javascript("https://unpkg.com/@jupyter-widgets/html-manager@0.18.4/dist/embed-amd.js") app.add_stylesheet("main_stylesheet.css") master_doc = 'index' source_suffix = '.rst' # General information about the project. project = 'ipyleaflet' copyright = '(c) Jupyter Development Team' author = 'Jupyter Development Team' exclude_patterns = [] highlight_language = 'python' pygments_style = 'sphinx' # Output file base name for HTML help builder. html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] htmlhelp_basename = 'ipyleafletdoc' html_static_path = ['_static']
# -*- coding: utf-8 -*- import sphinx_rtd_theme extensions = [ # 'sphinx.ext.autodoc', # 'sphinx.ext.intersphinx', # 'sphinx.ext.autosummary', # 'sphinx.ext.viewcode', # 'sphinx.ext.napoleon', # 'jupyter_sphinx.embed_widgets', ] templates_path = ['_templates'] def setup(app): app.add_javascript("https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js") app.add_javascript("https://unpkg.com/@jupyter-widgets/html-manager@0.15.0/dist/embed-amd.js") app.add_stylesheet("main_stylesheet.css") master_doc = 'index' source_suffix = '.rst' # General information about the project. project = 'ipyleaflet' copyright = '(c) Jupyter Development Team' author = 'Jupyter Development Team' exclude_patterns = [] highlight_language = 'python' pygments_style = 'sphinx' # Output file base name for HTML help builder. html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] htmlhelp_basename = 'ipyleafletdoc' html_static_path = ['_static']
Allow new blocks to be reloaded.
const { clone, pull } = require('./lib/git') const path = require('path') const jetpack = require('fs-jetpack') const freshRequire = require('./lib/freshRequire') const configuration = require('./configuration') class Package { constructor (url) { this.path = path.join(configuration.pluginDir, url) this.url = url this.clone = clone this.pull = pull } load () { return this.download().then(() => { const plugin = freshRequire(path.join(this.path, 'zazu.js')) plugin.blocks = plugin.blocks || {} plugin.blocks.external = plugin.blocks.external || [] plugin.blocks.input = plugin.blocks.input || [] plugin.blocks.output = plugin.blocks.output || [] return plugin }) } update () { if (!jetpack.exists(this.path)) { return Promise.reject('Package' + this.url + ' does not exist') } return this.pull(this.path) } download () { if (jetpack.exists(this.path)) { return Promise.resolve('exists') } return this.clone(this.url, this.path).then(() => { return 'downloaded' }) } } module.exports = Package
const { clone, pull } = require('./lib/git') const path = require('path') const jetpack = require('fs-jetpack') const configuration = require('./configuration') class Package { constructor (url) { this.path = path.join(configuration.pluginDir, url) this.url = url this.clone = clone this.pull = pull } load () { return this.download().then(() => { const plugin = require(path.join(this.path, 'zazu.js')) plugin.blocks = plugin.blocks || {} plugin.blocks.external = plugin.blocks.external || [] plugin.blocks.input = plugin.blocks.input || [] plugin.blocks.output = plugin.blocks.output || [] return plugin }) } update () { if (!jetpack.exists(this.path)) { return Promise.reject('Package' + this.url + ' does not exist') } return this.pull(this.path) } download () { if (jetpack.exists(this.path)) { return Promise.resolve('exists') } return this.clone(this.url, this.path).then(() => { return 'downloaded' }) } } module.exports = Package
Use context manager in example
from __future__ import print_function import unittest import modfoo import saliweb.test import os class JobTests(saliweb.test.TestCase): """Check custom ModFoo Job class""" def test_archive(self): """Test the archive method""" # Make a ModFoo Job test job in ARCHIVED state j = self.make_test_job(modfoo.Job, 'ARCHIVED') # Run the rest of this testcase in the job's directory with saliweb.test.working_directory(j.directory): # Make a test PDB file and another incidental file with open('test.pdb', 'w') as f: print("test pdb", file=f) with open('test.txt', 'w') as f: print("text file", file=f) # Run the job's "archive" method j.archive() # Job's archive method should have gzipped every PDB file but not # anything else self.assertTrue(os.path.exists('test.pdb.gz')) self.assertFalse(os.path.exists('test.pdb')) self.assertTrue(os.path.exists('test.txt')) if __name__ == '__main__': unittest.main()
from __future__ import print_function import unittest import modfoo import saliweb.test import os class JobTests(saliweb.test.TestCase): """Check custom ModFoo Job class""" def test_archive(self): """Test the archive method""" # Make a ModFoo Job test job in ARCHIVED state j = self.make_test_job(modfoo.Job, 'ARCHIVED') # Run the rest of this testcase in the job's directory d = saliweb.test.RunInDir(j.directory) # Make a test PDB file and another incidental file with open('test.pdb', 'w') as f: print("test pdb", file=f) with open('test.txt', 'w') as f: print("text file", file=f) # Run the job's "archive" method j.archive() # Job's archive method should have gzipped every PDB file but not # anything else self.assertTrue(os.path.exists('test.pdb.gz')) self.assertFalse(os.path.exists('test.pdb')) self.assertTrue(os.path.exists('test.txt')) if __name__ == '__main__': unittest.main()
Add a context processor that adds the UserProfile to each context.
from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['current_site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: context['GIT_COMMIT'] = settings.GIT_COMMIT context['site_email'] = settings.CONTACT_EMAIL if request.is_secure(): context['protocol'] = 'https://' else: context['protocol'] = 'http://' context['current_site_url'] = (context['protocol'] + context['current_site'].domain) return context def profile(request): context = {} if request.user.is_authenticated(): context['profile'] = request.user.get_profile() return context def ssl_media(request): if request.is_secure(): ssl_media_url = settings.MEDIA_URL.replace('http://','https://') else: ssl_media_url = settings.MEDIA_URL return {'MEDIA_URL': ssl_media_url}
from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['current_site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: context['GIT_COMMIT'] = settings.GIT_COMMIT context['site_email'] = settings.CONTACT_EMAIL if request.is_secure(): context['protocol'] = 'https://' else: context['protocol'] = 'http://' context['current_site_url'] = (context['protocol'] + context['current_site'].domain) return context def ssl_media(request): if request.is_secure(): ssl_media_url = settings.MEDIA_URL.replace('http://','https://') else: ssl_media_url = settings.MEDIA_URL return {'MEDIA_URL': ssl_media_url}
rcos: Add / to rcos tests
import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( "/", "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301]
import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301]
Change test to use something that looks like a real region code
package digitalocean import ( "testing" "github.com/mitchellh/packer/packer" ) func TestArtifact_Impl(t *testing.T) { var raw interface{} raw = &Artifact{} if _, ok := raw.(packer.Artifact); !ok { t.Fatalf("Artifact should be artifact") } } func TestArtifactId(t *testing.T) { a := &Artifact{"packer-foobar", 42, "sfo", nil} expected := "sfo:42" if a.Id() != expected { t.Fatalf("artifact ID should match: %v", expected) } } func TestArtifactString(t *testing.T) { a := &Artifact{"packer-foobar", 42, "sfo", nil} expected := "A snapshot was created: 'packer-foobar' (ID: 42) in region 'sfo'" if a.String() != expected { t.Fatalf("artifact string should match: %v", expected) } }
package digitalocean import ( "testing" "github.com/mitchellh/packer/packer" ) func TestArtifact_Impl(t *testing.T) { var raw interface{} raw = &Artifact{} if _, ok := raw.(packer.Artifact); !ok { t.Fatalf("Artifact should be artifact") } } func TestArtifactId(t *testing.T) { a := &Artifact{"packer-foobar", 42, "San Francisco", nil} expected := "San Francisco:42" if a.Id() != expected { t.Fatalf("artifact ID should match: %v", expected) } } func TestArtifactString(t *testing.T) { a := &Artifact{"packer-foobar", 42, "San Francisco", nil} expected := "A snapshot was created: 'packer-foobar' (ID: 42) in region 'San Francisco'" if a.String() != expected { t.Fatalf("artifact string should match: %v", expected) } }
Add default value for date with @NerdyProjects
from django.db.models import ForeignKey, DateTimeField, ManyToManyField from yunity.models.entities import User, Location, Mappable, Message from yunity.models.utils import BaseModel, MaxLengthCharField from yunity.utils.decorators import classproperty class Chat(BaseModel): participants = ManyToManyField(User) messages = ManyToManyField(Message) class MappableLocation(BaseModel): mappable = ForeignKey(Mappable) location = ForeignKey(Location) startTime = DateTimeField(null=True) endTime = DateTimeField(null=True) class MappableResponsibility(BaseModel): @classproperty def TYPE(cls): return cls.create_constants('type', 'OWNER') @classproperty def STATUS(cls): return cls.create_constants('status', 'GRANTED', 'PENDING', 'REQUESTED') responsible = ForeignKey(User) mappable = ForeignKey(Mappable) status = MaxLengthCharField() date = DateTimeField(null=True, auto_now=True) type = MaxLengthCharField() class UserLocation(BaseModel): user = ForeignKey(User) location = ForeignKey(Location) type = MaxLengthCharField() class ItemRequest(BaseModel): requester = ForeignKey(User) requested = ForeignKey(Mappable) feedback = MaxLengthCharField(null=True, default=None)
from django.db.models import ForeignKey, DateTimeField, ManyToManyField from yunity.models.entities import User, Location, Mappable, Message from yunity.models.utils import BaseModel, MaxLengthCharField from yunity.utils.decorators import classproperty class Chat(BaseModel): participants = ManyToManyField(User) messages = ManyToManyField(Message) class MappableLocation(BaseModel): mappable = ForeignKey(Mappable) location = ForeignKey(Location) startTime = DateTimeField(null=True) endTime = DateTimeField(null=True) class MappableResponsibility(BaseModel): @classproperty def TYPE(cls): return cls.create_constants('type', 'OWNER') @classproperty def STATUS(cls): return cls.create_constants('status', 'GRANTED', 'PENDING', 'REQUESTED') responsible = ForeignKey(User) mappable = ForeignKey(Mappable) status = MaxLengthCharField() date = DateTimeField(null=True) type = MaxLengthCharField() class UserLocation(BaseModel): user = ForeignKey(User) location = ForeignKey(Location) type = MaxLengthCharField() class ItemRequest(BaseModel): requester = ForeignKey(User) requested = ForeignKey(Mappable) feedback = MaxLengthCharField(null=True, default=None)
Use a space for scope separator to prevent issues with multiple scopes.
<?php namespace Rgbvader\OAuth; use League\OAuth2\Client\Provider\GenericProvider; class XenForoProvider extends GenericProvider { const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'user_id'; /** * @param string $url * @param string $query * @return string */ protected function appendQuery($url, $query) { if (substr($url, strlen($url)- 1, 1) == '&') { return $url.$query; } return parent::appendQuery($url, $query); } /** * Generate a random state, but do it publicly * @param int $length * @return string */ public function getRState($length = 32) { return parent::getRandomState($length); } /** * Use a space to force http_build_query to use '+'. * @return string */ protected function getScopeSeparator() { return ' '; } }
<?php namespace Rgbvader\OAuth; use League\OAuth2\Client\Provider\GenericProvider; class XenForoProvider extends GenericProvider { const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'user_id'; /** * @param string $url * @param string $query * @return string */ protected function appendQuery($url, $query) { if (substr($url, strlen($url)- 1, 1) == '&') { return $url.$query; } return parent::appendQuery($url, $query); } /** * Generate a random state, but do it publicly * @param int $length * @return string */ public function getRState($length = 32) { return parent::getRandomState($length); } }
SimonStewart: Convert the https test that we never run to use junit. git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@17194 07704840-8298-11de-bf8c-fd130f914ac9
/* Copyright 2012 Selenium committers Copyright 2012 Software Freedom Conservancy 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.thoughtworks.selenium.thirdparty; import com.thoughtworks.selenium.InternalSelenseTestBase; import org.junit.After; import org.junit.Test; public class YahooHttpsTest extends InternalSelenseTestBase { @After public void resetTimeout() { selenium.setTimeout("30000"); } @Test public void testYahoo() throws Exception { selenium.setTimeout("120000"); // this site has **two** HTTPS hosts (akamai and yahoo), so it's a good test of the new // multi-domain keystore support we just added selenium .open( "https://login11.marketingsolutions.yahoo.com/adui/signin/loadSignin.do?d=U2FsdGVkX1_evOPYuoCCKbeDENMTzoQ6O.oTzifl7TwsO8IqXh6duToE2tI2&p=11&s=21"); } }
/* Copyright 2012 Selenium committers Copyright 2012 Software Freedom Conservancy 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.thoughtworks.selenium.thirdparty; import com.thoughtworks.selenium.InternalSelenseTestBase; import org.testng.annotations.Test; public class YahooHttpsTest extends InternalSelenseTestBase { @Test(dataProvider = "system-properties") public void testYahoo() throws Exception { // this site has **two** HTTPS hosts (akamai and yahoo), so it's a good test of the new // multi-domain keystore support we just added selenium .open("https://login11.marketingsolutions.yahoo.com/adui/signin/loadSignin.do?d=U2FsdGVkX1_evOPYuoCCKbeDENMTzoQ6O.oTzifl7TwsO8IqXh6duToE2tI2&p=11&s=21"); } }
Allow workspaces outside of the workspace root Summary: As part of the workspace separation, and because our repo does not have an ideal layout (for example `react-native-github` consists of both product and tooling code, and is hard to move right now), I am in need of making workspaces outside of a workspace root work with Buck. This works with Yarn, assuming `$NODE_PATH` is used for correct resolutions, but did not work with Yarn's Buck Macros until this diff. ## How do the Yarn Buck Macros work? Up until this week we didn't have anyone left at the company who understands this infrastructure. Now that I am the owner, here is a high-level overview of how things work: * `yarn_workspace` creates a zip file of the workspace in `buck-out` (without `package.json` file). * `yarn_workspace_root` creates a zip file of the `package.json` files of the root and all workspaces, `yarn.lock`, and `node_modules` for the corresponding workspace. * `yarn_workspace_archive` merges the zip files for each workspace and the root to produce what is more or less the same as a Metronome package. * `yarn_workspace_binary` which ties together all of the above to run a JavaScript tool given an entry point. ## Why does it use zip files? The reason that this infrastructure uses zip files is because it was optimized for size and cache hits. In the past our `node_modules` folders were way too large and significantly slowed down buck builds. My end goal with the workspace separation is that product code will not use any of these rules at all (once the files are checked in), and that we should get rid of all the overhead and complexity of using zip files – either by using Metronome or by getting rid of the feature in the Yarn workspace rules. ## What does this diff do? With all this context in mind, this diff changes the layout of the zip files created by `yarn_workspace_root` and `yarn_workspace_archive` to align with the behavior of Metronome. Instead of using relative paths mirroring the source locations in the zip files, we now use package names. For example, instead of `workspace.zip/tools/metro/packages/metro-symbolicate` we now simply put this file into the root, like `workspace.zip/metro-symbolicate`. For namespaced packages, we now use `fb-tools/gen-rn-routes/` (package name) instead of `tools/gen-rn-routes/` (file system path). This will allow us to use workspaces outside of the workspace root without breaking out of the assigned output folder in `buck-out`. This also means that I had to update all callsites of `yarn_workspace_binary` to adjust the entry point to a package-relative path that can be resolved via node instead of a path generated from the source layout by Buck. NOTE: Arguably, this is how it should have been from the beginning. However, it requires the codebase to be well-organized with packages and without relative requires across the repo. We only reached this state earlier this year after our big cleanup, so the previous solution to mirror the source locations made the most sense up until now. Special thanks to davidaurelio for his patience and help over WhatsApp. Reviewed By: yungsters Differential Revision: D24359263 fbshipit-source-id: 40c4925ade1b8d87d2e65799bb059cda24c9a65b
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ import {dirname, join, resolve} from 'path'; const FLOW_ROOT = resolve(__dirname, '../../../'); export const defaultTestsDirName = 'newtests'; // This is where we look for tests to run and where we put newly converted // tests export function getTestsDir(relative_to?: string): string { if (relative_to !== undefined) { return resolve(relative_to, defaultTestsDirName); } else { return dirname(require.resolve(join(defaultTestsDirName, 'package.json'))); } } export const binOptions: Array<string> = [ resolve(FLOW_ROOT, 'bin/flow'), // Open source build resolve(FLOW_ROOT, 'bin/flow.exe'), // Open source windows build resolve(FLOW_ROOT, '../buck-out/gen/flow/flow/flow'), // Buck ]; export const defaultFlowConfigName = '_flowconfig';
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {resolve} from 'path'; const TOOL_ROOT = resolve(__dirname, "../"); const FLOW_ROOT = resolve(__dirname, "../../../"); export const defaultTestsDirName = "newtests"; // This is where we look for tests to run and where we put newly converted // tests export function getTestsDir(relative_to?: string): string { if (relative_to !== undefined) { return resolve(relative_to, defaultTestsDirName); } else { return resolve(FLOW_ROOT, defaultTestsDirName); } } export const binOptions: Array<string> = [ resolve(FLOW_ROOT, "bin/flow"), // Open source build resolve(FLOW_ROOT, "bin/flow.exe"), // Open source windows build resolve(FLOW_ROOT, "../buck-out/gen/flow/flow/flow"), // Buck ]; export const defaultFlowConfigName = "_flowconfig";
Allow character to appear more than once Using str_shuffle means that each character can only occur once in the generated string. This reduces the number of permutations possible. For example, using base 36, and 4 characters, there are 36^4 = 1.68M, but the current function can only generate 36*35*34*33 = 1.41M of these. This alternative will use the whole range of possible strings.
<?php /* Plugin Name: Random Keywords Plugin URI: http://yourls.org/ Description: Assign random keywords to shorturls, like bitly (sho.rt/hJudjK) Version: 1.1 Author: Ozh Author URI: http://ozh.org/ */ /* Release History: * * 1.0 Initial release * 1.1 Added: don't increment sequential keyword counter & save one SQL query * Fixed: plugin now complies to character set defined in config.php */ global $ozh_random_keyword; /* * CONFIG: EDIT THIS */ /* Length of random keyword */ $ozh_random_keyword['length'] = 5; /* * DO NOT EDIT FARTHER */ // Generate a random keyword yourls_add_filter( 'random_keyword', 'ozh_random_keyword' ); function ozh_random_keyword() { global $ozh_random_keyword; $possible = yourls_get_shorturl_charset() ; $str=''; while (strlen($str) < $ozh_random_keyword['length']) { $str .= substr($possible, rand(0,strlen($possible)),1); } return $str; } // Don't increment sequential keyword tracker yourls_add_filter( 'get_next_decimal', 'ozh_random_keyword_next_decimal' ); function ozh_random_keyword_next_decimal( $next ) { return ( $next - 1 ); }
<?php /* Plugin Name: Random Keywords Plugin URI: http://yourls.org/ Description: Assign random keywords to shorturls, like bitly (sho.rt/hJudjK) Version: 1.1 Author: Ozh Author URI: http://ozh.org/ */ /* Release History: * * 1.0 Initial release * 1.1 Added: don't increment sequential keyword counter & save one SQL query * Fixed: plugin now complies to character set defined in config.php */ global $ozh_random_keyword; /* * CONFIG: EDIT THIS */ /* Length of random keyword */ $ozh_random_keyword['length'] = 5; /* * DO NOT EDIT FARTHER */ // Generate a random keyword yourls_add_filter( 'random_keyword', 'ozh_random_keyword' ); function ozh_random_keyword() { global $ozh_random_keyword; return yourls_rnd_string( $ozh_random_keyword['length'] ); } // Don't increment sequential keyword tracker yourls_add_filter( 'get_next_decimal', 'ozh_random_keyword_next_decimal' ); function ozh_random_keyword_next_decimal( $next ) { return ( $next - 1 ); }
Make the test really work. (Learning how to do promises right with hamcrest)
import assert from 'assert'; import { assertThat, everyItem, hasProperty, endsWith, hasSize, promiseThat, is, fulfilled, fulfilledWith, allOf, truthy } from 'hamjest'; import fs from 'fs'; import path from 'path'; function convertOneFile(fileName, destFileName) { const fileReadPromise = new Promise(resolve => { fs.readFile(fileName, 'utf8', (error, content) => { if (!error) resolve(content); }); }); return fileReadPromise.then(fileContent => { return new Promise(resolve => { fs.writeFile(destFileName, minifyJson(fileContent), 'utf8', resolve); }); }); } function minifyJson(content) { return content; return JSON.stringify(JSON.parse(content)); } describe('converting `stars.json`', () => { const destFile = path.join(__dirname, '../../dist/data/stars.json'); const sourceFile = path.join(__dirname, '../../data/stars.json'); let promise; beforeEach(() => { if (fs.existsSync(destFile)) fs.unlinkSync(destFile); promise = convertOneFile(sourceFile, destFile); }); it('fulfills', () => { return promiseThat(promise, is(fulfilled())); }); it('writes the destination file', () => { return promise.then(() => assert(fs.existsSync(destFile), 'Destination file missing.')); }); });
import assert from 'assert'; import { assertThat, everyItem, hasProperty, endsWith, hasSize, promiseThat, is, fulfilled, fulfilledWith, allOf, truthy } from 'hamjest'; import fs from 'fs'; import path from 'path'; function convertOneFile(fileName, destFileName) { const fileReadPromise = new Promise(resolve => { fs.readFile(fileName, 'utf8', (error, content) => { if (!error) resolve(content); }); }); return fileReadPromise.then(fileContent => { return new Promise(resolve => { fs.writeFile(destFileName, minifyJson(fileContent), 'utf8', resolve); }); }); } function minifyJson(content) { return content; return JSON.stringify(JSON.parse(content)); } describe('converting `stars.json`', () => { const destFile = path.join(__dirname, '../../dist/data/stars.json'); const sourceFile = path.join(__dirname, '../../data/stars.json'); let promise; beforeEach(() => { if (fs.existsSync(destFile)) fs.unlinkSync(destFile); promise = convertOneFile(sourceFile, destFile); }); it('fulfills', () => { return promiseThat(promise, is(fulfilled())); }); it('writes the destination file', () => { return promiseThat(promise, allOf( fulfilled(), truthy(fs.existsSync(destFile)) ) ); }); });
Create random auth token on user signup
from .models import School, User import re import string import random def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site school['university'] = s.university.name school['city'] = s.university.city.name school['country'] = s.university.city.country.name school_list.append(school) return school_list def get_school_by_email(email): for school in School.objects.all(): if re.match(school.mailRegex, email): return school return None def create_user(email, school): password = User.objects.make_random_password() token = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(40)) user_obj = User.objects.create_user(email=email, school=school, password=password, token=token) user_obj.interestedInSchools.set(School.objects.all().values_list('id', flat=True)) user_obj.save() print 'Email:', email, 'Password:', password, 'Token:', token # TODO: Send signup mail to user
from .models import School, User import re def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site school['university'] = s.university.name school['city'] = s.university.city.name school['country'] = s.university.city.country.name school_list.append(school) return school_list def get_school_by_email(email): for school in School.objects.all(): if re.match(school.mailRegex, email): return school return None def create_user(email, school): password = User.objects.make_random_password() user_obj = User.objects.create_user(email=email, school=school, password=password) user_obj.interestedInSchools.set(School.objects.all().values_list('id', flat=True)) user_obj.save() # TODO: Send signup mail to user
Truncate rather than replace to prevent erroneous substitutions.
from django.urls import reverse from six.moves.urllib.parse import urljoin from kolibri.utils.conf import OPTIONS def reverse_remote( baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None ): # Get the reversed URL reversed_url = reverse( viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app ) # Remove any configured URL prefix from the URL that is specific to this deployment prefix_length = len(OPTIONS["Deployment"]["URL_PATH_PREFIX"]) reversed_url = reversed_url[prefix_length:] # Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl # it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/', # as it would be read as an absolute path) return urljoin(baseurl, reversed_url.lstrip("/"))
from django.urls import reverse from six.moves.urllib.parse import urljoin from kolibri.utils.conf import OPTIONS def reverse_remote( baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None ): # Get the reversed URL reversed_url = reverse( viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app ) # Remove any configured URL prefix from the URL that is specific to this deployment reversed_url = reversed_url.replace(OPTIONS["Deployment"]["URL_PATH_PREFIX"], "") # Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl # it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/', # as it would be read as an absolute path) return urljoin(baseurl, reversed_url.lstrip("/"))
Use "private" for fields in struct-like classes
package jauter; public class Pattern<T> { private final String path; private final String[] tokens; private final T target; public static String removeSlashAtBothEnds(String path) { if (path.isEmpty()) return path; int beginIndex = 0; while (beginIndex < path.length() && path.charAt(beginIndex) == '/') beginIndex++; if (beginIndex == path.length()) return ""; int endIndex = path.length() - 1; while (endIndex > beginIndex && path.charAt(endIndex) == '/') endIndex--; return path.substring(beginIndex, endIndex + 1); } public Pattern(String path, T target) { this.path = removeSlashAtBothEnds(path); this.tokens = this.path.split("/"); this.target = target; } public String path() { return path; } public String[] tokens() { return tokens; } public T target() { return target; } }
package jauter; public class Pattern<T> { protected final String path; protected final String[] tokens; protected final T target; public static String removeSlashAtBothEnds(String path) { if (path.isEmpty()) return path; int beginIndex = 0; while (beginIndex < path.length() && path.charAt(beginIndex) == '/') beginIndex++; if (beginIndex == path.length()) return ""; int endIndex = path.length() - 1; while (endIndex > beginIndex && path.charAt(endIndex) == '/') endIndex--; return path.substring(beginIndex, endIndex + 1); } public Pattern(String path, T target) { this.path = removeSlashAtBothEnds(path); this.tokens = this.path.split("/"); this.target = target; } public String path() { return path; } public String[] tokens() { return tokens; } public T target() { return target; } }
Allow the reporter to be a member of the required module
#!/usr/bin/env node require("ts-node/register"); var path = require("path"); var fs = require("fs"); var Jasmine = require("jasmine"); var Command = require("jasmine/lib/command.js"); var jasmine = new Jasmine({ projectBaseDir: path.resolve() }); var examplesDir = path.join("node_modules", "jasmine-core", "lib", "jasmine-core", "example", "node_example"); var command = new Command(path.resolve(), examplesDir, console.log); var initReporters = () => { var configPath = process.env.JASMINE_CONFIG_PATH || "spec/support/jasmine.json"; var config = JSON.parse(fs.readFileSync(path.resolve(configPath))); if(config.reporters && config.reporters.length > 0) { config.reporters.forEach(reporter => { var parts = reporter.name.split('#'); var name = parts[0]; var member = parts[1]; var reporterClass = member ? require(name)[member] : require(name); jasmine.addReporter(new (reporterClass)(reporter.options)) }); } }; initReporters(); command.run(jasmine, process.argv.slice(2));
#!/usr/bin/env node require("ts-node/register"); var path = require("path"); var fs = require("fs"); var Jasmine = require("jasmine"); var Command = require("jasmine/lib/command.js"); var jasmine = new Jasmine({ projectBaseDir: path.resolve() }); var examplesDir = path.join("node_modules", "jasmine-core", "lib", "jasmine-core", "example", "node_example"); var command = new Command(path.resolve(), examplesDir, console.log); var initReporters = () => { var configPath = process.env.JASMINE_CONFIG_PATH || "spec/support/jasmine.json"; var config = JSON.parse(fs.readFileSync(path.resolve(configPath))); if(config.reporters && config.reporters.length > 0) { config.reporters.forEach(reporter => jasmine.addReporter(new (require(reporter.name))(reporter.options)) ); } }; initReporters(); command.run(jasmine, process.argv.slice(2));
Fix return values in doc
<?php /** * Fiber: String * Copyright (c) 2013 Eirik Refsdal <eirikref@gmail.com> */ namespace Fiber; /** * Fiber: String * * Class for generating string test data * * Things: - strings of various length (min, max, exact) * - different charsets * - empty strings (just length 0) * - really long strings (1M, 5M, 10M, etc.) * - single string, words, sentences, lorem ipsum, special chars * (!?;:, etc.), password (fix of small, caps, numbers, * etc.) * * @package Fiber * @version 2013-06-27 * @author Eirik Refsdal <eirikref@gmail.com> */ class String extends DataType { /** * Get object * * @author Eirik Refsdal <eirikref@gmail.com> * @since 2013-06-27 * @access private * @return string */ private function generateString($length, $charset, $mode) { } /** * Get object * * @author Eirik Refsdal <eirikref@gmail.com> * @since 2013-07-18 * @access public * @return string */ public function getEmpty() { return ""; } }
<?php /** * Fiber: String * Copyright (c) 2013 Eirik Refsdal <eirikref@gmail.com> */ namespace Fiber; /** * Fiber: String * * Class for generating string test data * * Things: - strings of various length (min, max, exact) * - different charsets * - empty strings (just length 0) * - really long strings (1M, 5M, 10M, etc.) * - single string, words, sentences, lorem ipsum, special chars * (!?;:, etc.), password (fix of small, caps, numbers, * etc.) * * @package Fiber * @version 2013-06-27 * @author Eirik Refsdal <eirikref@gmail.com> */ class String extends DataType { /** * Get object * * @author Eirik Refsdal <eirikref@gmail.com> * @since 2013-06-27 * @access private * @return object */ private function generateString($length, $charset, $mode) { } /** * Get object * * @author Eirik Refsdal <eirikref@gmail.com> * @since 2013-07-18 * @access public * @return object */ public function getEmpty() { return ""; } }
Replace field injection by constructor injection
package org.synyx.urlaubsverwaltung; import no.api.freemarker.java8.Java8ObjectWrapper; import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration; import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; @Configuration public class FreemarkerConfig extends FreeMarkerAutoConfiguration { private final freemarker.template.Configuration configuration; public FreemarkerConfig(ApplicationContext applicationContext, FreeMarkerProperties properties, freemarker.template.Configuration configuration) { super(applicationContext, properties); this.configuration = configuration; } @PostConstruct public void postConstruct() { configuration.setObjectWrapper(new Java8ObjectWrapper(freemarker.template.Configuration.getVersion())); } }
package org.synyx.urlaubsverwaltung; import no.api.freemarker.java8.Java8ObjectWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration; import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; @Configuration public class FreemarkerConfig extends FreeMarkerAutoConfiguration { @Autowired private freemarker.template.Configuration configuration; public FreemarkerConfig(ApplicationContext applicationContext, FreeMarkerProperties properties) { super(applicationContext, properties); } @PostConstruct public void postConstruct() { configuration.setObjectWrapper( new Java8ObjectWrapper(freemarker.template.Configuration.getVersion())); } }
Add collections to JSON arrays
package com.aemreunal.helper.json; /* * *********************** * * Copyright (c) 2015 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * aemreunal@gmail.com * * emre.unal@ozu.edu.tr * * * * aemreunal.com * * *********************** * */ import net.minidev.json.JSONArray; import java.util.ArrayList; import java.util.Collection; public class JsonArrayBuilder { private ArrayList<Object> jsonList = new ArrayList<>(); JsonArrayBuilder() { } public JsonArrayBuilder add(Object item) { jsonList.add(item); return this; } public JsonArrayBuilder addAll(Collection items) { jsonList.addAll(items); return this; } public JSONArray build() { JSONArray array = new JSONArray(); array.addAll(jsonList); return array; } }
package com.aemreunal.helper.json; /* * *********************** * * Copyright (c) 2015 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * aemreunal@gmail.com * * emre.unal@ozu.edu.tr * * * * aemreunal.com * * *********************** * */ import net.minidev.json.JSONArray; import java.util.ArrayList; public class JsonArrayBuilder { private ArrayList<Object> jsonList = new ArrayList<>(); JsonArrayBuilder() { } public JsonArrayBuilder add(Object value) { jsonList.add(value); return this; } public JSONArray build() { JSONArray array = new JSONArray(); array.addAll(jsonList); return array; } }
Drop the TLS tests for a moment to see if we can get a success for timing.
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting import t_loadbalancer import t_lua_scripts import t_mappingtests import t_optiontests import t_plain import t_ratelimit import t_redirect import t_shadow import t_stats import t_tcpmapping # import t_tls import t_tracing import t_retrypolicy import t_consul import t_circuitbreaker import t_knative # pytest will find this because Runner is a toplevel callable object in a file # that pytest is willing to look inside. # # Also note: # - Runner(cls) will look for variants of _every subclass_ of cls. # - Any class you pass to Runner needs to be standalone (it must have its # own manifests and be able to set up its own world). main = Runner(AmbassadorTest)
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting import t_loadbalancer import t_lua_scripts import t_mappingtests import t_optiontests import t_plain import t_ratelimit import t_redirect import t_shadow import t_stats import t_tcpmapping import t_tls import t_tracing import t_retrypolicy import t_consul import t_circuitbreaker import t_knative # pytest will find this because Runner is a toplevel callable object in a file # that pytest is willing to look inside. # # Also note: # - Runner(cls) will look for variants of _every subclass_ of cls. # - Any class you pass to Runner needs to be standalone (it must have its # own manifests and be able to set up its own world). main = Runner(AmbassadorTest)
Add loot table for basic block
package info.u_team.u_team_test.data.provider; import java.util.function.BiConsumer; import info.u_team.u_team_core.data.*; import info.u_team.u_team_test.init.*; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.loot.LootTable; public class TestLootTablesProvider extends CommonLootTablesProvider { public TestLootTablesProvider(GenerationData data) { super(data); } @Override protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) { registerBlock(TestBlocks.BASIC, addFortuneBlockLootTable(TestBlocks.BASIC, TestItems.BASIC), consumer); registerBlock(TestBlocks.BASIC_TILEENTITY, addTileEntityBlockLootTable(TestBlocks.BASIC_TILEENTITY), consumer); registerBlock(TestBlocks.BASIC_ENERGY_CREATOR, addTileEntityBlockLootTable(TestBlocks.BASIC_ENERGY_CREATOR), consumer); registerBlock(TestBlocks.BASIC_FLUID_INVENTORY, addTileEntityBlockLootTable(TestBlocks.BASIC_FLUID_INVENTORY), consumer); } }
package info.u_team.u_team_test.data.provider; import java.util.function.BiConsumer; import info.u_team.u_team_core.data.*; import info.u_team.u_team_test.init.TestBlocks; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.loot.LootTable; public class TestLootTablesProvider extends CommonLootTablesProvider { public TestLootTablesProvider(GenerationData data) { super(data); } @Override protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) { registerBlock(TestBlocks.BASIC_TILEENTITY, addTileEntityBlockLootTable(TestBlocks.BASIC_TILEENTITY), consumer); registerBlock(TestBlocks.BASIC_ENERGY_CREATOR, addTileEntityBlockLootTable(TestBlocks.BASIC_ENERGY_CREATOR), consumer); registerBlock(TestBlocks.BASIC_FLUID_INVENTORY, addTileEntityBlockLootTable(TestBlocks.BASIC_FLUID_INVENTORY), consumer); } }
Add a global scope for the reply count
<?php namespace App\Data; use Eloquent; use DiscussionPresenter; use Laracasts\Presenter\PresentableTrait; use Illuminate\Database\Eloquent\SoftDeletes; class Discussion extends Eloquent { use SoftDeletes, PresentableTrait; protected $fillable = ['title', 'body', 'user_id', 'topic_id']; protected $dates = ['created_at', 'updated_at', 'deleted_at']; protected $presenter = DiscussionPresenter::class; protected static function boot() { parent::boot(); static::addGlobalScope('replyCount', function ($builder) { $builder->withCount('replies'); }); } //-------------------------------------------------------------------------- // Relationships //-------------------------------------------------------------------------- public function author() { return $this->belongsTo(User::class, 'user_id'); } public function replies() { return $this->hasMany(Reply::class); } public function topic() { return $this->belongsTo(Topic::class); } //-------------------------------------------------------------------------- // Model Methods //-------------------------------------------------------------------------- public function addReply(array $data) { $this->replies()->create($data); } public function scopeFilter($query, $filters) { return $filters->apply($query); } }
<?php namespace App\Data; use Eloquent; use DiscussionPresenter; use Laracasts\Presenter\PresentableTrait; use Illuminate\Database\Eloquent\SoftDeletes; class Discussion extends Eloquent { use SoftDeletes, PresentableTrait; protected $fillable = ['title', 'body', 'user_id', 'topic_id']; protected $dates = ['created_at', 'updated_at', 'deleted_at']; protected $presenter = DiscussionPresenter::class; //-------------------------------------------------------------------------- // Relationships //-------------------------------------------------------------------------- public function author() { return $this->belongsTo(User::class, 'user_id'); } public function replies() { return $this->hasMany(Reply::class); } public function topic() { return $this->belongsTo(Topic::class); } //-------------------------------------------------------------------------- // Model Methods //-------------------------------------------------------------------------- public function addReply(array $data) { $this->replies()->create($data); } public function scopeFilter($query, $filters) { return $filters->apply($query); } }
Remove save method for auto_now_add=True
from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), auto_now_add=True, ) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', )
from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), ) def save(self, *args, **kwargs): if self.pk is None: self.posted_at = now() super(Note, self).save(*args, **kwargs) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', )
Include legend label text in update block.
import {Index, Label, Offset, Size, Total, Value} from './constants'; import guideMark from './guide-mark'; import {TextMark} from '../marks/marktypes'; import {LegendLabelRole} from '../marks/roles'; import {addEncode} from '../encode/encode-util'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero }; addEncode(enter, 'align', config.labelAlign); addEncode(enter, 'baseline', config.labelBaseline); addEncode(enter, 'fill', config.labelColor); addEncode(enter, 'font', config.labelFont); addEncode(enter, 'fontSize', config.labelFontSize); addEncode(enter, 'limit', config.labelLimit); encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1}, text: {field: Label} }; enter.x = update.x = { field: Offset, offset: config.labelOffset }; enter.y = update.y = { field: Size, mult: 0.5, offset: { field: Total, offset: { field: {group: 'entryPadding'}, mult: {field: Index} } } }; return guideMark(TextMark, LegendLabelRole, Value, dataRef, encode, userEncode); }
import {Index, Label, Offset, Size, Total, Value} from './constants'; import guideMark from './guide-mark'; import {TextMark} from '../marks/marktypes'; import {LegendLabelRole} from '../marks/roles'; import {addEncode} from '../encode/encode-util'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, text: {field: Label} }; addEncode(enter, 'align', config.labelAlign); addEncode(enter, 'baseline', config.labelBaseline); addEncode(enter, 'fill', config.labelColor); addEncode(enter, 'font', config.labelFont); addEncode(enter, 'fontSize', config.labelFontSize); addEncode(enter, 'limit', config.labelLimit); encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Offset, offset: config.labelOffset }; enter.y = update.y = { field: Size, mult: 0.5, offset: { field: Total, offset: { field: {group: 'entryPadding'}, mult: {field: Index} } } }; return guideMark(TextMark, LegendLabelRole, Value, dataRef, encode, userEncode); }
Allow date without time with date injector
<?php namespace Maphper\Lib; //Replaces dates in an object graph with \DateTime instances class DateInjector { private $processCache; public function replaceDates($obj, $reset = true) { //prevent infinite recursion, only process each object once if ($reset) $this->processCache = new \SplObjectStorage(); if (is_object($obj) && $this->processCache->contains($obj)) return $obj; else if (is_object($obj)) $this->processCache->attach($obj, true); if (is_array($obj) || (is_object($obj) && ($obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false); if (is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20) { try { $date = new \DateTime($obj); if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20) || $date->format('Y-m-d') == substr($obj, 0, 10)) $obj = $date; } catch (\Exception $e) { //Doesn't need to do anything as the try/catch is working out whether $obj is a date } } return $obj; } }
<?php namespace Maphper\Lib; //Replaces dates in an object graph with \DateTime instances class DateInjector { private $processCache; public function replaceDates($obj, $reset = true) { //prevent infinite recursion, only process each object once if ($reset) $this->processCache = new \SplObjectStorage(); if (is_object($obj) && $this->processCache->contains($obj)) return $obj; else if (is_object($obj)) $this->processCache->attach($obj, true); if (is_array($obj) || (is_object($obj) && ($obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false); if (is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20) { try { $date = new \DateTime($obj); if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20)) $obj = $date; } catch (\Exception $e) { //Doesn't need to do anything as the try/catch is working out whether $obj is a date } } return $obj; } }
Fix tests refering to wrong IAM resource
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest @pytest.fixture def resources(plan_runner): _, resources = plan_runner() return resources def test_resource_count(resources): "Test number of resources created." assert len(resources) == 3 def test_iam(resources): "Test IAM binding resources." bindings = [r['values'] for r in resources if r['type'] == 'google_cloudfunctions2_function_iam_binding'] assert len(bindings) == 1 assert bindings[0]['role'] == 'roles/cloudfunctions.invoker'
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest @pytest.fixture def resources(plan_runner): _, resources = plan_runner() return resources def test_resource_count(resources): "Test number of resources created." assert len(resources) == 3 def test_iam(resources): "Test IAM binding resources." bindings = [r['values'] for r in resources if r['type'] == 'google_cloudfunctions_function_iam_binding'] assert len(bindings) == 1 assert bindings[0]['role'] == 'roles/cloudfunctions.invoker'
Set replace to false in pushState method
import { _win } from 'core/variables'; import { genTimeKey } from './key'; let _key = genTimeKey(); export const supportsPushState = _win.history && _win.history.pushState; /** * Either replace existing History entry or add new entry * * @param {string} url * @param {boolean} replace=false */ export function pushState(url, replace = false) { // TODO: Save scroll position when pushState is executed // https://github.com/vuejs/vue-router/blob/dev/src/util/push-state.js // saveScrollPosition(); try { if (replace) { _win.history.replaceState({ key: _key }, '', url); } else { _key = genTimeKey(); _win.history.pushState({ key: _key }, '', url); } } catch(e) { // Fallback if something goes wrong _win.location[replace ? 'replace' : 'assign'](url); } } /** * Replace entry in History * * @param {string} url */ export function replaceState(url) { pushState(url, true); }
import { _win } from 'core/variables'; import { genTimeKey } from './key'; let _key = genTimeKey(); export const supportsPushState = _win.history && _win.history.pushState; /** * Either replace existing History entry or add new entry * * @param {string} url * @param {boolean} [replace] */ export function pushState(url, replace) { // TODO: Save scroll position when pushState is executed // https://github.com/vuejs/vue-router/blob/dev/src/util/push-state.js // saveScrollPosition(); try { if (replace) { _win.history.replaceState({ key: _key }, '', url); } else { _key = genTimeKey(); _win.history.pushState({ key: _key }, '', url); } } catch(e) { // Fallback if something goes wrong _win.location[replace ? 'replace' : 'assign'](url); } } /** * Replace entry in History * * @param {string} url */ export function replaceState(url) { pushState(url, true); }
Load fresh data for each request
import {Server} from 'hapi' import inert from 'inert' import getProjects from './app/get-projects' /** * @param {string} configFilename The config filename * @param {number} port The port number */ export function serve(configFilename, port) { const server = new Server() let projects server.connection({port}) server.register(inert, err => { server.route({ method: 'GET', path: '/api/projects', handler: (request, reply) => { reply(getProjects(configFilename)) } }) server.route({ method: 'GET', path: '/site/{param*}', handler: { directory: { path: 'site', listing: true } } }) server.start(err => { if (err) { console.log(err.stack) return } try { projects = getProjects(configFilename) } catch (e) { console.log(e.stack) process.exit(1) } console.log('Server running at:', server.info.uri + '/site') }) }) }
import {Server} from 'hapi' import inert from 'inert' import getProjects from './app/get-projects' /** * @param {string} configFilename The config filename * @param {number} port The port number */ export function serve(configFilename, port) { const server = new Server() let projects server.connection({port}) server.register(inert, err => { server.route({ method: 'GET', path: '/api/projects', handler: (request, reply) => { reply(projects) } }) server.route({ method: 'GET', path: '/site/{param*}', handler: { directory: { path: 'site', listing: true } } }) server.start(err => { if (err) { console.log(err.stack) return } try { projects = getProjects(configFilename) } catch (e) { console.log(e.stack) process.exit(1) } console.log('Server running at:', server.info.uri + '/site') }) }) }
Allow object literals to be IDisposable RELNOTES[INC]: goog.disposable.IDisposable is now @record ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=129902477
// Copyright 2011 The Closure Library 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. /** * @fileoverview Definition of the disposable interface. A disposable object * has a dispose method to to clean up references and resources. * @author nnaze@google.com (Nathan Naze) */ goog.provide('goog.disposable.IDisposable'); /** * Interface for a disposable object. If a instance requires cleanup * (references COM objects, DOM nodes, or other disposable objects), it should * implement this interface (it may subclass goog.Disposable). * @record */ goog.disposable.IDisposable = function() {}; /** * Disposes of the object and its resources. * @return {void} Nothing. */ goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod; /** * @return {boolean} Whether the object has been disposed of. */ goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
// Copyright 2011 The Closure Library 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. /** * @fileoverview Definition of the disposable interface. A disposable object * has a dispose method to to clean up references and resources. * @author nnaze@google.com (Nathan Naze) */ goog.provide('goog.disposable.IDisposable'); /** * Interface for a disposable object. If a instance requires cleanup * (references COM objects, DOM notes, or other disposable objects), it should * implement this interface (it may subclass goog.Disposable). * @interface */ goog.disposable.IDisposable = function() {}; /** * Disposes of the object and its resources. * @return {void} Nothing. */ goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod; /** * @return {boolean} Whether the object has been disposed of. */ goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
Change visibility of storage interruption manager
package com.orientechnologies.orient.core.storage.impl.local; import com.orientechnologies.common.concur.lock.OInterruptedException; import com.orientechnologies.common.log.OLogManager; public class OStorageInterruptionManager { private int depth = 0; private boolean interrupted = false; protected void interrupt(Thread thread) { synchronized (this) { if (depth <= 0) { interrupted = true; } else if (thread != null) { thread.interrupt(); } } } public void enterCriticalPath() { synchronized (this) { if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } this.depth++; } } public void exitCriticalPath() { synchronized (this) { this.depth--; if (interrupted && depth == 0) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } } } }
package com.orientechnologies.orient.core.storage.impl.local; import com.orientechnologies.common.concur.lock.OInterruptedException; import com.orientechnologies.common.log.OLogManager; public class OStorageInterruptionManager { private int depth = 0; private boolean interrupted = false; protected void interrupt(Thread thread) { synchronized (this) { if (depth <= 0) { interrupted = true; } else if (thread != null) { thread.interrupt(); } } } protected void enterCriticalPath() { synchronized (this) { if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } this.depth++; } } protected void exitCriticalPath() { synchronized (this) { this.depth--; if (interrupted && depth == 0) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } } } }
Fix error update widget action
import { createAction } from './create-action' import * as t from '../action-types' import AuthSelectors from '~authenticate/redux/selectors' import Selectors from '../selectors' export default widget => (dispatch, getState, { api }) => { dispatch(createAction(t.UPDATE_WIDGET_REQUEST)) const credentials = AuthSelectors(getState()).getCredentials() const mobilization = Selectors(getState()).getMobilization() return api .put(`/mobilizations/${mobilization.id}/widgets/${widget.id}`, { widget }, { headers: credentials }) .then(res => { dispatch(createAction(t.UPDATE_WIDGET_SUCCESS, res.data)) }) .catch(ex => { dispatch(createAction(t.UPDATE_WIDGET_FAILURE, ex)) return Promise.reject(ex) }) }
import { createAction } from './create-action' import * as t from '../action-types' import AuthSelectors from '~authenticate/redux/selectors' import Selectors from '../selectors' export default widget => (dispatch, getState, { api }) => { dispatch(createAction(t.UPDATE_WIDGET_REQUEST)) const credentials = AuthSelectors(getState()).getCredentials() const mobilization = Selectors(getState()).getMobilization() return api .put(`/mobilizations/${mobilization.id}/widgets/${widget.id}`, { widget }, { headers: credentials }) .then(res => { dispatch(createAction(t.UPDATE_WIDGET_SUCCESS, res.data)) }) .catch(ex => { dispatch(createAction(t.UPDATE_WIDGET_FAILURE, error)) return Promise.reject(ex) }) }
Tag is not required, of course
"""Forms for dealing with jobs/posts.""" from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from taggit.models import Tag class PostFilterForm(forms.Form): """Form for filtering the PostListView.""" title = forms.CharField(required=False) is_job_posting = forms.BooleanField(required=False) is_freelance = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(PostFilterForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_method = 'get' self.helper.add_input(Submit('submit', 'Filter')) class JobSearchForm(forms.Form): """Form for filtering the JobListView.""" search = forms.CharField(required=False) tag = forms.ModelChoiceField(queryset=Tag.objects.all(), required=False) def __init__(self, *args, **kwargs): super(JobSearchForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_method = 'get' self.helper.add_input(Submit('submit', 'Search'))
"""Forms for dealing with jobs/posts.""" from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from taggit.models import Tag class PostFilterForm(forms.Form): """Form for filtering the PostListView.""" title = forms.CharField(required=False) is_job_posting = forms.BooleanField(required=False) is_freelance = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(PostFilterForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_method = 'get' self.helper.add_input(Submit('submit', 'Filter')) class JobSearchForm(forms.Form): """Form for filtering the JobListView.""" search = forms.CharField(required=False) tag = forms.ModelChoiceField(queryset=Tag.objects.all()) def __init__(self, *args, **kwargs): super(JobSearchForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_method = 'get' self.helper.add_input(Submit('submit', 'Search'))
Add filter by language for list by tag.
from dragoman_blog.models import EntryTranslation from django.views.generic.list import ListView from django.utils.translation import get_language class ListByTagView(ListView): """ View for listing posts by tags""" template_name = "dragoman_blog/entrytranslation_list_by_tag.html" model = EntryTranslation def get_queryset(self): try: tag = self.kwargs['tag'] except: tag = '' if (tag != ''): object_list = self.model.objects.filter( tags__name=tag, language_code=get_language()) else: object_list = self.model.objects.none() return object_list def get_context_data(self, **kwargs): context = super(ListByTagView, self).get_context_data(**kwargs) context['tag'] = self.kwargs['tag'] return context
from dragoman_blog.models import EntryTranslation from django.views.generic.list import ListView class ListByTagView(ListView): """ View for listing posts by tags""" template_name = "dragoman_blog/entrytranslation_list_by_tag.html" model = EntryTranslation def get_queryset(self): try: tag = self.kwargs['tag'] except: tag = '' if (tag != ''): object_list = self.model.objects.filter(tags__name=tag) else: object_list = self.model.objects.none() return object_list def get_context_data(self, **kwargs): context = super(ListByTagView, self).get_context_data(**kwargs) context['tag'] = self.kwargs['tag'] return context
Tidy up array handling hiccup
import { VACCINE_ACTIONS } from '../actions/VaccineActions'; const initialState = () => ({ scannedSensors: [], isScanning: false, }); export const VaccineReducer = (state = initialState(), action) => { const { type } = action; switch (type) { case VACCINE_ACTIONS.SCAN_START: { return { ...state, isScanning: true, }; } case VACCINE_ACTIONS.SCAN_STOP: { return { ...state, isScanning: false, }; } case VACCINE_ACTIONS.SENSOR_FOUND: { const { payload } = action; const { scannedSensors } = state; scannedSensors.push(payload); return { ...state, scannedSensors, }; } default: return state; } };
import { VACCINE_ACTIONS } from '../actions/VaccineActions'; const initialState = () => ({ scannedSensors: [], isScanning: false, }); export const VaccineReducer = (state = initialState(), action) => { const { type } = action; switch (type) { case VACCINE_ACTIONS.SCAN_START: { return { ...state, isScanning: true, }; } case VACCINE_ACTIONS.SCAN_STOP: { return { ...state, isScanning: false, }; } case VACCINE_ACTIONS.SENSOR_FOUND: { const { payload } = action; const { scannedSensors } = state; const updatedSensorList = scannedSensors.push(payload); return { ...state, scannedSensors: updatedSensorList, }; } default: return state; } };
Improve comment on Batch interface
// (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. // For ease of implementation, our database's interface matches Ethereum's // database implementation. This was to allow use to use Geth code as is for the // EVM chain. package database // Batch is a write-only database that commits changes to its host database // when Write is called. A batch cannot be used concurrently. type Batch interface { KeyValueWriter // Size retrieves the amount of data queued up for writing, this includes // the keys, values, and deleted keys. Size() int // Write flushes any accumulated data to disk. Write() error // Reset resets the batch for reuse. Reset() // Replay replays the batch contents in the same order they were written // to the batch. Replay(w KeyValueWriter) error // Inner returns a Batch writing to the inner database, if one exists. If // this batch is already writing to the base DB, then itself should be // returned. Inner() Batch } // Batcher wraps the NewBatch method of a backing data store. type Batcher interface { // NewBatch creates a write-only database that buffers changes to its host db // until a final write is called. NewBatch() Batch }
// (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. // For ease of implementation, our database's interface matches Ethereum's // database implementation. This was to allow use to use Geth code as is for the // EVM chain. package database // Batch is a write-only database that commits changes to its host database // when Write is called. A batch cannot be used concurrently. type Batch interface { KeyValueWriter // Size retrieves the amount of data queued up for writing, this includes // the keys, values, and deleted keys. Size() int // Write flushes any accumulated data to disk. Write() error // Reset resets the batch for reuse. Reset() // Replay replays the batch contents. Replay(w KeyValueWriter) error // Inner returns a Batch writing to the inner database, if one exists. If // this batch is already writing to the base DB, then itself should be // returned. Inner() Batch } // Batcher wraps the NewBatch method of a backing data store. type Batcher interface { // NewBatch creates a write-only database that buffers changes to its host db // until a final write is called. NewBatch() Batch }
Use better start values for arm
#!/usr/bin/env python3 import socket import time import math import random HOST, PORT = 'localhost', 7777 LIMIT = 0.5 posx = random.uniform(-50.00, 50.00) posy = random.uniform(-50.00, 50.00) posz = random.uniform(-50.00, 50.00) def change_pos(*values): range_delta = 0.1 output = [] for pos in values: pos_min = pos - range_delta pos_min = -0.5 if pos_min < -0.5 else pos_min pos_max = pos + range_delta pos_max = 0.5 if pos_max > 0.5 else pos_max output.append(round(random.uniform(pos_min, pos_max), 2)) return output num = 1 while True: with socket.socket() as sock: sock.connect((HOST, PORT)) data = ';'.join([str(posx), str(posy), str(posz)]) sock.sendall(bytes(data, 'utf-8')) time.sleep(0.5) posx, posy, posz = change_pos(posx, posy, posz) num += 1
#!/usr/bin/env python3 import socket import time import math import random HOST, PORT = 'localhost', 7777 LIMIT = 0.5 posx, posy, posz = 0.0, 0.0, 0.0 def change_pos(*values): range_delta = 0.1 output = [] for pos in values: pos_min = pos - range_delta pos_min = -0.5 if pos_min < -0.5 else pos_min pos_max = pos + range_delta pos_max = 0.5 if pos_max > 0.5 else pos_max output.append(round(random.uniform(pos_min, pos_max), 2)) return output num = 1 while True: with socket.socket() as sock: sock.connect((HOST, PORT)) data = ';'.join([str(posx), str(posy), str(posz)]) sock.sendall(bytes(data, 'utf-8')) time.sleep(0.5) posx, posy, posz = change_pos(posx, posy, posz) num += 1
Add DM support, and first start at self-update
import discord import asyncio import os import signal import sys import subprocess #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise KeyboardInterrupt sys.exit('Shutting down...') #Register SIGTERM Handler signal.signal(signal.SIGTERM, sigterm_handler) @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): #Look at DMs for special commands if message.channel.startswith('Direct Message'): if message.content.startswith('!update'): tmp = await client.send_message(message.channel, 'Updating my code via git...') subprocess.call(["ls", "-l"]) if message.content.startswith('!test'): counter = 0 tmp = await client.send_message(message.channel, 'Calculating messages...') async for log in client.logs_from(message.channel, limit=100): if log.author == message.author: counter += 1 await client.edit_message(tmp, 'You have {} messages.'.format(counter)) #Start event loop client.run(CLIENT_TOKEN)
import discord import asyncio import os import signal import sys #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise KeyboardInterrupt sys.exit('Shutting down...') #Register SIGTERM Handler signal.signal(signal.SIGTERM, sigterm_handler) @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): if message.content.startswith('!test'): counter = 0 tmp = await client.send_message(message.channel, 'Calculating messages...') async for log in client.logs_from(message.channel, limit=100): if log.author == message.author: counter += 1 await client.edit_message(tmp, 'You have {} messages.'.format(counter)) elif message.content.startswith('!sleep'): await asyncio.sleep(5) await client.send_message(message.channel, 'Done sleeping') client.run(CLIENT_TOKEN)
Use strings for IDs in Committee Popolo
from django.http import JsonResponse from django.views.generic import ListView from pombola.core.models import Organisation # Output Popolo JSON suitable for WriteInPublic for any committees that have an # email address. class CommitteesPopoloJson(ListView): queryset = Organisation.objects.filter( kind__name='National Assembly Committees', contacts__kind__slug='email' ) def render_to_response(self, context, **response_kwargs): return JsonResponse( { 'persons': [ { 'id': str(committee.id), 'name': committee.name, 'email': committee.contacts.filter(kind__slug='email')[0].value, 'contact_details': [] } for committee in context['object_list'] ] } )
from django.http import JsonResponse from django.views.generic import ListView from pombola.core.models import Organisation # Output Popolo JSON suitable for WriteInPublic for any committees that have an # email address. class CommitteesPopoloJson(ListView): queryset = Organisation.objects.filter( kind__name='National Assembly Committees', contacts__kind__slug='email' ) def render_to_response(self, context, **response_kwargs): return JsonResponse( { 'persons': [ { 'id': committee.id, 'name': committee.name, 'email': committee.contacts.filter(kind__slug='email')[0].value, 'contact_details': [] } for committee in context['object_list'] ] } )
Fix bug in flag parsing
package main import ( "errors" "flag" "io/ioutil" "os" "strings" ) // Token Getter is a function that can retrieve a token type tokenGetter func() (string, error) // goes through the provided TokenGetter chain and stops once one reports // a non-"" value. If any produce errors it'll wrap those up and return 'em. func getTokenFromChain(getters ...tokenGetter) (string, error) { errs := make([]string, len(getters)) for _, g := range getters { str, err := g() if err != nil { errs = append(errs, err.Error()) continue } if str != "" { return str, nil } } return "", errors.New(strings.Join(errs, "\n")) } // opens the "token" file and reads it into a string func getTokenFromFile() (string, error) { bytes, err := ioutil.ReadFile("token") if err != nil { return "", err } return string(bytes), nil } // checks the DO_TOKEN env variable func getTokenFromEnv() (string, error) { return os.Getenv("DO_TOKEN"), nil } // checks the "-token" flag on the CLI func getTokenFromCli() (string, error) { str := flag.String("token", "", "The token to use with the DO API") flag.Parse() return *str, nil }
package main import ( "errors" "flag" "io/ioutil" "os" "strings" ) // a function that provides a means to retrieve a token type TokenGetter func() (string, error) // goes through the provided TokenGetter chain and stops once one reports // a non-"" value. If any produce errors it'll wrap those up and return 'em. func getTokenFromChain(getters ...TokenGetter) (string, error) { errs := make([]string, len(getters)) for _, g := range getters { str, err := g() if err != nil { errs = append(errs, err.Error()) continue } if str != "" { return str, nil } } return "", errors.New(strings.Join(errs, "\n")) } // opens the "token" file and reads it into a string func getTokenFromFile() (string, error) { bytes, err := ioutil.ReadFile("token") if err != nil { return "", err } return string(bytes), nil } // checks the DO_TOKEN env variable func getTokenFromEnv() (string, error) { return os.Getenv("DO_TOKEN"), nil } // checks the "-token" flag on the CLI func getTokenFromCli() (string, error) { var str *string flag.StringVar(str, "token", "", "The token to use with the DO API") flag.Parse() return *str, nil }
Add pod name to payload
package enmasse.config.service.podsense; import enmasse.config.service.openshift.MessageEncoder; import io.fabric8.kubernetes.api.model.Pod; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.message.Message; import java.io.IOException; import java.util.*; /** * Encodes podsense responses */ public class PodSenseMessageEncoder implements MessageEncoder<PodResource> { @Override public Message encode(Set<PodResource> set) throws IOException { Message message = Message.Factory.create(); List<Map<String, Object>> root = new ArrayList<>(); set.forEach(pod -> root.add(encodePod(pod))); message.setBody(new AmqpValue(root)); return message; } private Map<String, Object> encodePod(PodResource pod) { Map<String, Object> map = new LinkedHashMap<>(); map.put("name", pod.getName()); map.put("host", pod.getHost()); map.put("phase", pod.getPhase()); map.put("ready", pod.getReady()); map.put("ports", pod.getPortMap()); return map; } }
package enmasse.config.service.podsense; import enmasse.config.service.openshift.MessageEncoder; import io.fabric8.kubernetes.api.model.Pod; import org.apache.qpid.proton.amqp.messaging.AmqpSequence; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.message.Message; import java.io.IOException; import java.util.*; /** * Encodes podsense responses */ public class PodSenseMessageEncoder implements MessageEncoder<PodResource> { @Override public Message encode(Set<PodResource> set) throws IOException { Message message = Message.Factory.create(); List<Map<String, Object>> root = new ArrayList<>(); set.forEach(pod -> root.add(encodePod(pod))); message.setBody(new AmqpValue(root)); return message; } private Map<String, Object> encodePod(PodResource pod) { Map<String, Object> map = new LinkedHashMap<>(); map.put("host", pod.getHost()); map.put("phase", pod.getPhase()); map.put("ready", pod.getReady()); map.put("ports", pod.getPortMap()); return map; } }
Make sami/sami config PSR1/2 compliant
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $dir = __DIR__ . '/src'; $iterator = Finder::create() ->files() ->name('*.php') ->in($dir); $versions = GitVersionCollection::create($dir) ->addFromTags(function ($version) { return preg_match('/^v?\d+\.\d+\.\d+$/', $version); }) ->add('master', 'production') ->add('develop', 'development'); $options = array( 'title' => 'jk/restserver API', 'versions' => $versions, 'build_dir' => __DIR__ . '/build/sami/%version%', 'cache_dir' => __DIR__ . '/build/sami_cache/%version%', 'default_opened_level' => 2, ); return new Sami($iterator, $options);
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $dir = __DIR__ . '/src'; $iterator = Finder::create() ->files() ->name('*.php') ->in($dir) ; $versions = GitVersionCollection::create($dir) ->addFromTags(function ($version) { return preg_match('/^v?\d+\.\d+\.\d+$/', $version); }) ->add('master', 'production') ->add('develop', 'development') ; $options = array( 'title' => 'jk/restserver API', 'versions' => $versions, 'build_dir' => __DIR__.'/build/sami/%version%', 'cache_dir' => __DIR__.'/build/sami_cache/%version%', 'default_opened_level' => 2, ); return new Sami($iterator, $options);
Switch to a geo IP API that isn't down
package net.maxbraun.mirror; import android.location.Location; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; /** * A helper class to look up location by IP. */ public abstract class GeoLocation { private static final String TAG = GeoLocation.class.getSimpleName(); /** * The URL of the geo location API endpoint. */ private static final String GEO_IP_URL = "http://ip-api.com/json"; /** * Makes a request to the geo location API and returns the current location or {@code null} on * error. */ public static Location getLocation() { String response = Network.get(GEO_IP_URL); if (response == null) { Log.e(TAG, "Empty response."); return null; } // Parse the latitude and longitude from the response JSON. try { JSONObject responseJson = new JSONObject(response); double latitude = responseJson.getDouble("lat"); double longitude = responseJson.getDouble("lon"); Location location = new Location(""); location.setLatitude(latitude); location.setLongitude(longitude); return location; } catch (JSONException e) { Log.e(TAG, "Failed to parse geo location JSON."); return null; } } }
package net.maxbraun.mirror; import android.location.Location; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; /** * A helper class to look up location by IP. */ public abstract class GeoLocation { private static final String TAG = GeoLocation.class.getSimpleName(); /** * The URL of the geo location API endpoint. */ private static final String GEO_IP_URL = "http://freegeoip.net/json/"; /** * Makes a request to the geo location API and returns the current location or {@code null} on * error. */ public static Location getLocation() { String response = Network.get(GEO_IP_URL); if (response == null) { Log.e(TAG, "Empty response."); return null; } // Parse the latitude and longitude from the response JSON. try { JSONObject responseJson = new JSONObject(response); double latitude = responseJson.getDouble("latitude"); double longitude = responseJson.getDouble("longitude"); Location location = new Location(""); location.setLatitude(latitude); location.setLongitude(longitude); return location; } catch (JSONException e) { Log.e(TAG, "Failed to parse geo location JSON."); return null; } } }
Fix bug on deepExtend helper
/** * Orion Helpers */ orion.helpers = {} /** * Searchs a object with a givin string * you can specify if you want the searcher to * take the first values of array if they are */ orion.helpers.searchObjectWithDots = function(object, key, selectFirstIfIsArray) { key = key.split('.'); try { for (var i = 0; i < key.length; i++) { if (selectFirstIfIsArray && object.length && object.length > 0) { object = object[0]; } if (key[i] in object) { object = object[key[i]]; } else { return null; } } } catch(error) { return null; } return object || null; } /** * Deep extend */ orion.helpers.deepExtend = function(target, source) { for (var prop in source) if (prop in target && typeof(target[prop]) == 'object' && typeof(source[prop]) == 'object') orion.helpers.deepExtend(target[prop], source[prop]); else target[prop] = source[prop]; return target; }
/** * Orion Helpers */ orion.helpers = {} /** * Searchs a object with a givin string * you can specify if you want the searcher to * take the first values of array if they are */ orion.helpers.searchObjectWithDots = function(object, key, selectFirstIfIsArray) { key = key.split('.'); try { for (var i = 0; i < key.length; i++) { if (selectFirstIfIsArray && object.length && object.length > 0) { object = object[0]; } if (key[i] in object) { object = object[key[i]]; } else { return null; } } } catch(error) { return null; } return object || null; } /** * Deep extend */ orion.helpers.deepExtend = function(target, source) { for (var prop in source) if (prop in target && typeof(target[prop]) == 'object' && typeof(source[prop]) == 'object') deepExtend(target[prop], source[prop]); else target[prop] = source[prop]; return target; }
Refactor to use method references
package helloworld; import static org.requirementsascode.UseCaseModelBuilder.newBuilder; import org.requirementsascode.UseCaseModel; import org.requirementsascode.UseCaseModelBuilder; import org.requirementsascode.UseCaseModelRunner; public class HelloWorld01_PrintHelloUserExample { public UseCaseModel buildWith(UseCaseModelBuilder modelBuilder) { UseCaseModel useCaseModel = modelBuilder.useCase("Get greeted") .basicFlow() .step("S1").system(this::greetUser) .build(); return useCaseModel; } private void greetUser(UseCaseModelRunner runner) { System.out.println("Hello, User."); } public static void main(String[] args){ HelloWorld01_PrintHelloUserExample example = new HelloWorld01_PrintHelloUserExample(); example.start(); } private void start() { UseCaseModelRunner useCaseModelRunner = new UseCaseModelRunner(); UseCaseModel useCaseModel = buildWith(newBuilder()); useCaseModelRunner.run(useCaseModel); } }
package helloworld; import static org.requirementsascode.UseCaseModelBuilder.newBuilder; import java.util.function.Consumer; import org.requirementsascode.UseCaseModel; import org.requirementsascode.UseCaseModelBuilder; import org.requirementsascode.UseCaseModelRunner; public class HelloWorld01_PrintHelloUserExample { public UseCaseModel buildWith(UseCaseModelBuilder modelBuilder) { UseCaseModel useCaseModel = modelBuilder.useCase("Get greeted") .basicFlow() .step("S1").system(greetUser()) .build(); return useCaseModel; } private Consumer<UseCaseModelRunner> greetUser() { return r -> System.out.println("Hello, User."); } public static void main(String[] args){ HelloWorld01_PrintHelloUserExample example = new HelloWorld01_PrintHelloUserExample(); example.start(); } private void start() { UseCaseModelRunner useCaseModelRunner = new UseCaseModelRunner(); UseCaseModel useCaseModel = buildWith(newBuilder()); useCaseModelRunner.run(useCaseModel); } }
Update metadata defaults to Rootstrikers-specific info
angular .module('app') .factory('MetaMachine', function($rootScope) { var metaDefaults = { metaTitle: "Home | Rootstrikers", metaDescription: "We fight the corrupting influence of money in politics", metaImage: "/app/images/favicon/apple-touch-icon-144x144-precomposed.png", metaUrl: "http://rs002dev.herokuapp.com/" }; (function setDefaults() { _.each(metaDefaults, function(val, key) { $rootScope[key] = val; }); })(); var MetaMachine = { title: function(pageTitle, baseTitle) { baseTitle = typeof baseTitle != 'undefined' ? baseTitle : "Rootstrikers"; $rootScope.metaTitle = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; }, description: function(description) { $rootScope.metaDescription = description || "We fight the corrupting influence of money in politics"; }, image: function(url) { $rootScope.metaImage = url || "/app/images/favicon/apple-touch-icon-144x144-precomposed.png"; }, url: function(url) { $rootScope.metaUrl = url || "http://rs002dev.herokuapp.com/"; } }; return MetaMachine; });
angular .module('app') .factory('MetaMachine', function($rootScope) { var metaDefaults = { metaTitle: "Home | Rootstrikers", metaDescription: "We fight the corrupting influence of money in politics", metaImage: "http://facultycreative.com/img/icons/facultyicon114.png", metaUrl: "http://rs002dev.herokuapp.com/" }; (function setDefaults() { _.each(metaDefaults, function(val, key) { $rootScope[key] = val; }); })(); var MetaMachine = { title: function(pageTitle, baseTitle) { baseTitle = typeof baseTitle != 'undefined' ? baseTitle : "Rootstrikers"; $rootScope.metaTitle = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; }, description: function(description) { $rootScope.metaDescription = description || "We fight the corrupting influence of money in politics"; }, image: function(url) { $rootScope.metaImage = url || "http://facultycreative.com/img/icons/facultyicon114.png"; }, url: function(url) { $rootScope.metaUrl = url || "http://rs002dev.herokuapp.com/"; } }; return MetaMachine; });
Remove some hidden magic + adjust output to be compatible with view block
<?php declare(strict_types=1); namespace block\dbblock; use app; use arr; use attr; function render(array $block): string { $data = $block['cfg']['data']; if (!$data || !($attrs = arr\extract($data['_entity']['attr'], $block['cfg']['attr_id']))) { return ''; } $html = ''; foreach ($attrs as $attr) { $cfg = ['wrap' => true] + (in_array($attr['id'], ['file_id', 'title']) ? ['link' => $data['link']] : []); $html .= attr\viewer($data, $attr, $cfg); } if ($html) { return app\html('section', ['data-entity' => $block['cfg']['data']['entity_id']], $html); } return ''; }
<?php declare(strict_types=1); namespace block\dbblock; use app; use arr; use attr; function render(array $block): string { $data = $block['cfg']['data']; if (!$data || !($attrs = arr\extract($data['_entity']['attr'], $block['cfg']['attr_id']))) { return ''; } $html = ''; foreach ($attrs as $attr) { $cfg = ['wrap' => true] + (in_array($attr['id'], ['file_id', 'title']) ? ['link' => $data['link']] : []); $html .= attr\viewer($data, $attr, $cfg); } if ($html) { return app\html('section', ['class' => str_replace('_', '-', $block['cfg']['data']['entity_id'])], $html); } return ''; }
Fix duplicate prefix sending with party chat & logging.
package com.gmail.nossr50.chat; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.events.chat.McMMOPartyChatEvent; public class PartyChatManager extends ChatManager { private Party party; protected PartyChatManager(Plugin plugin) { super(plugin, Config.getInstance().getPartyDisplayNames(), "Commands.Party.Chat.Prefix"); } public void setParty(Party party) { this.party = party; } @Override public void handleChat(String senderName, String displayName, String message, boolean isAsync) { handleChat(new McMMOPartyChatEvent(plugin, senderName, displayName, party.getName(), message, isAsync)); } @Override protected void sendMessage() { for (Player member : party.getOnlineMembers()) { member.sendMessage(message); } plugin.getLogger().info("[P]<" + party.getName() + ">" + message); } }
package com.gmail.nossr50.chat; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.events.chat.McMMOPartyChatEvent; import com.gmail.nossr50.locale.LocaleLoader; public class PartyChatManager extends ChatManager { private Party party; protected PartyChatManager(Plugin plugin) { super(plugin, Config.getInstance().getPartyDisplayNames(), "Commands.Party.Chat.Prefix"); } public void setParty(Party party) { this.party = party; } @Override public void handleChat(String senderName, String displayName, String message, boolean isAsync) { handleChat(new McMMOPartyChatEvent(plugin, senderName, displayName, party.getName(), message, isAsync)); } @Override protected void sendMessage() { for (Player member : party.getOnlineMembers()) { member.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Prefix", displayName) + message); } plugin.getLogger().info("[P](" + party.getName() + ")" + "<" + ChatColor.stripColor(displayName) + "> " + message); } }
Install bash completion script only when running the installation script as root. This is also a workaround for a bug that prevents tox from install the above script while creating the virtual environment.
import os from setuptools import find_packages from distutils.core import setup data_files = [] # Add bash completion script in case we are running as root if os.getuid() == 0: data_files=[ ('/etc/bash_completion.d', ['data/skipper-complete.sh']) ] setup( name='skipper', version='0.0.1', url='http://github.com/Stratoscale/skipper', author='Adir Gabai', author_mail='adir@stratoscale.com', packages=find_packages(include=['skipper*']), data_files=data_files, entry_points={ 'console_scripts': [ 'skipper = skipper.main:main', ], }, install_requires=[ 'PyYAML>=3.11', 'click>=6.6', 'requests>=2.10.0', 'tabulate>=0.7.5', ] )
from setuptools import find_packages from distutils.core import setup setup( name='skipper', version='0.0.1', url='http://github.com/Stratoscale/skipper', author='Adir Gabai', author_mail='adir@stratoscale.com', packages=find_packages(include=['skipper*']), data_files=[ ('/etc/bash_completion.d', ['data/skipper-complete.sh']), ], entry_points={ 'console_scripts': [ 'skipper = skipper.main:main', ], }, install_requires=[ 'PyYAML>=3.11', 'click>=6.6', 'requests>=2.10.0', 'tabulate>=0.7.5', ] )
Fix Validate Site popup when open on mobile phones
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2016, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function() { $.get(pH7Url.base + 'validate-site/main/validationbox', function(oData) { $.colorbox({ width : '100%', maxWidth : '450px', maxHeight : '85%', speed : 500, scrolling : false, html : $(oData).find('#box_block') }) }) }); $validationBox();
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2016, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function() { $.get(pH7Url.base + 'validate-site/main/validationbox', function(oData) { $.colorbox({ width : '450px', maxHeight : '85%', speed : 500, scrolling : false, html : $(oData).find('#box_block') }) }) }); $validationBox();
Add a body to posts
from django.contrib.auth.models import User from django.db import models class Discussion(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=255) slug = models.SlugField() def __unicode__(self): return self.name class Post(models.Model): discussion = models.ForeignKey(Discussion) user = models.ForeignKey(User) name = models.CharField(max_length=255) slug = models.SlugField() body = models.TextField() posts_file = models.FileField(upload_to='uploads/posts', blank=True, null=True) def __unicode__(self): return self.name class Comment(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(User) body = models.TextField() comment_file = models.FileField(upload_to='uploads/comments', blank=True, null=True) def __unicode__(self): return 'Comment on %s by %s' % (self.post.name, self.user)
from django.contrib.auth.models import User from django.db import models class Discussion(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=255) slug = models.SlugField() def __unicode__(self): return self.name class Post(models.Model): discussion = models.ForeignKey(Discussion) user = models.ForeignKey(User) name = models.CharField(max_length=255) slug = models.SlugField() posts_file = models.FileField(upload_to='uploads/posts', blank=True, null=True) def __unicode__(self): return self.name class Comment(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(User) body = models.TextField() comment_file = models.FileField(upload_to='uploads/comments', blank=True, null=True) def __unicode__(self): return 'Comment on %s by %s' % (self.post.name, self.user)
Rename PyPi dist. to wallace-platform
"""Install Wallace as a command line utility.""" from setuptools import setup setup_args = dict( name='wallace-platform', packages=['wallace'], version="0.11.1", description='Wallace, a platform for experimental cultural evolution', url='http://github.com/berkeley-cocosci/Wallace', author='Berkeley CoCoSci', author_email='wallace@cocosci.berkeley.edu', license='MIT', keywords=['science', 'cultural evolution', 'experiments', 'psychology'], classifiers=[], zip_safe=False, entry_points={ 'console_scripts': [ 'wallace = wallace.command_line:wallace', ], } ) # Read in requirements.txt for dependencies. setup_args['install_requires'] = install_requires = [] setup_args['dependency_links'] = dependency_links = [] with open('requirements.txt') as f: for line in f.readlines(): req = line.strip() if not req or req.startswith('#'): continue if req.startswith('-e '): dependency_links.append(req[3:]) else: install_requires.append(req) setup(**setup_args)
"""Install Wallace as a command line utility.""" from setuptools import setup setup_args = dict( name='w', packages=['wallace'], version="0.11.1", description='Wallace, a platform for experimental cultural evolution', url='http://github.com/berkeley-cocosci/Wallace', author='Berkeley CoCoSci', author_email='wallace@cocosci.berkeley.edu', license='MIT', keywords=['science', 'cultural evolution', 'experiments', 'psychology'], classifiers=[], zip_safe=False, entry_points={ 'console_scripts': [ 'wallace = wallace.command_line:wallace', ], } ) # Read in requirements.txt for dependencies. setup_args['install_requires'] = install_requires = [] setup_args['dependency_links'] = dependency_links = [] with open('requirements.txt') as f: for line in f.readlines(): req = line.strip() if not req or req.startswith('#'): continue if req.startswith('-e '): dependency_links.append(req[3:]) else: install_requires.append(req) setup(**setup_args)
docs(TrackerDash): Remove mention of private GitHub project
import $ from 'jquery'; import topInfoBar from './templates/topInfoBar.jade'; import VisComponent from '../../VisComponent'; class TopInfoBar extends VisComponent { constructor (el, settings) { super(el); this.$el = $(this.el); this.name = settings.name || 'Ground Truth'; this.branch = settings.branch || 'No branch set'; this.day = settings.day || this.getToday(); this.submissionUuid = settings.submission_uuid; this.helpLink = settings.help_link; } render () { this.$el.html(topInfoBar({ name: this.name, branch: this.branch, day: this.day, uuid: this.submissionUuid, helpLink: this.helpLink })); } } export default TopInfoBar;
import $ from 'jquery'; import topInfoBar from './templates/topInfoBar.jade'; import VisComponent from '../../VisComponent'; class TopInfoBar extends VisComponent { constructor (el, settings) { super(el); this.$el = $(this.el); this.name = settings.name || 'Ground Truth'; this.branch = settings.branch || 'No branch set'; this.day = settings.day || this.getToday(); this.submissionUuid = settings.submission_uuid; this.helpLink = settings.help_link || 'https://github.com/Trailmix/RedwoodInternal/wiki/Midas-for-Metrics-Based-Testing#performance-dashboards'; } render () { this.$el.html(topInfoBar({ name: this.name, branch: this.branch, day: this.day, uuid: this.submissionUuid, helpLink: this.helpLink })); } } export default TopInfoBar;
Add more comments in capturist dashboard view
from django.contrib.auth.decorators import user_passes_test, login_required from django.shortcuts import render from perfiles_usuario.utils import is_capturista from estudios_socioeconomicos.models import Estudio @login_required @user_passes_test(is_capturista) def capturista_dashboard(request): """View to render the capturista control dashboard. This view shows the list of socio-economic studies that are under review and the button to add a new socio-economic study. Also shows the edit and see feedback buttons to each socio-economic study shown in the list if this exist for the current user (capturist). """ estudios = [] iduser = request.user.id rechazados = Estudio.objects.filter(status='rechazado') for estudio in rechazados: if estudio.capturista_id == iduser: estudios.append(estudio) return render(request, 'captura/dashboard_capturista.html', {'estudios': estudios})
from django.contrib.auth.decorators import user_passes_test, login_required from django.shortcuts import render from perfiles_usuario.utils import is_capturista from estudios_socioeconomicos.models import Estudio @login_required #@user_passes_test(is_capturista) def capturista_dashboard(request): """View to render the capturista control dashboard. This view shows the list of socio-economic studies that are under review and the action buttons to add and edit each socio-economic study. """ estudios = [] iduser = request.user.id rechazados = Estudio.objects.filter(status='rechazado') for estudio in rechazados: if estudio.capturista_id == iduser: estudios.append(estudio) return render(request, 'captura/dashboard_capturista.html', {'estudios': estudios})
Use resource_string for error messages Signed-off-by: Michael Barton <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@michaelbarton.me.uk>
import sys, yaml, os.path def select_module(module, name): """ Select and return a biobox module """ mod_name = ".".join(["biobox_cli", module, name]) try: __import__(mod_name) except ImportError: err_exit('unknown_command', {'command_type': str.replace(module, '_', ' '), 'command': name}) return sys.modules[mod_name] def parse_docopt(doc, argv, is_main_module): from docopt import docopt from version import __version__ return docopt(doc, argv = argv, version = __version__, options_first = is_main_module) def err_message(msg_key, locals_): from pkg_resources import resource_string errors = yaml.load(resource_string(__name__, os.path.join('..', 'assets', 'error_messages.yml'))) return errors[msg_key].format(**locals_) def err_exit(msg_key, locals_): sys.stderr.write(err_message(msg_key, locals_)) exit(1)
import sys, yaml, os.path def select_module(module, name): """ Select and return a biobox module """ mod_name = ".".join(["biobox_cli", module, name]) try: __import__(mod_name) except ImportError: err_exit('unknown_command', {'command_type': str.replace(module, '_', ' '), 'command': name}) return sys.modules[mod_name] def parse_docopt(doc, argv, is_main_module): from docopt import docopt from version import __version__ return docopt(doc, argv = argv, version = __version__, options_first = is_main_module) def err_message(msg_key, locals_): path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets', 'error_messages.yml') with open(path, 'r') as f: errors = yaml.load(f.read()) return errors[msg_key].format(**locals_) def err_exit(msg_key, locals_): sys.stderr.write(err_message(msg_key, locals_)) exit(1)
Allow action message customization by service
<?php namespace PragmaRX\Health\Notifications\Channels; use Request; abstract class BaseChannel implements Contract { /** * @return mixed */ protected function getActionTitle() { return config('health.notifications.action-title'); } /** * @param $item * @return string */ protected function getMessage($item) { $domain = Request::server('SERVER_NAME'); $message = isset($item['action_message']) ? $item['action_message'] : config('health.notifications.action_message'); return sprintf( $message, studly_case($item['name']), $domain ? " in {$domain}." : '.' ); } /** * @return string */ protected function getActionLink() { return route(config('health.routes.notification')); } }
<?php namespace PragmaRX\Health\Notifications\Channels; use Request; abstract class BaseChannel implements Contract { /** * @return mixed */ protected function getActionTitle() { return config('health.notifications.action-title'); } /** * @param $item * @return string */ protected function getMessage($item) { $domain = Request::server('SERVER_NAME'); return sprintf( config('health.notifications.action_message'), studly_case($item['name']), $domain ? " in {$domain}." : '.' ); } /** * @return string */ protected function getActionLink() { return route(config('health.routes.notification')); } }
Update footer not to use grid layout.
/** * Footer component of the ModulePopularPagesWidget widget. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ /** * WordPress dependencies */ import { _x } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { MODULES_ANALYTICS } from '../../../datastore/constants'; import SourceLink from '../../../../../components/SourceLink'; const { useSelect } = Data; export default function Footer() { const visitorsOverview = useSelect( ( select ) => select( MODULES_ANALYTICS ).getServiceReportURL( 'visitors-overview' ) ); return ( <SourceLink href={ visitorsOverview } name={ _x( 'Analytics', 'Service name', 'google-site-kit' ) } external /> ); }
/** * Footer component of the ModulePopularPagesWidget widget. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ /** * WordPress dependencies */ import { _x } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { MODULES_ANALYTICS } from '../../../datastore/constants'; import { Cell, Grid, Row } from '../../../../../material-components'; import SourceLink from '../../../../../components/SourceLink'; const { useSelect } = Data; export default function Footer() { const visitorsOverview = useSelect( ( select ) => select( MODULES_ANALYTICS ).getServiceReportURL( 'visitors-overview' ) ); return ( <Grid> <Row> <Cell size={ 12 } alignMiddle> <SourceLink href={ visitorsOverview } name={ _x( 'Analytics', 'Service name', 'google-site-kit' ) } external /> </Cell> </Row> </Grid> ); }
Replace deprecated imp with importlib
import pytest # noqa import os import sys import glob import importlib def test_examples(): examples_pat = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../examples/*/*.py') # Filter out __init__.py examples = [f for f in glob.glob(examples_pat) if not any([x in f for x in ['__init__.py', 'molecular', 'custom_table_caching']])] for e in examples: example_dir = os.path.dirname(e) sys.path.insert(0, example_dir) (module_name, _) = os.path.splitext(os.path.basename(e)) m = importlib.import_module(module_name) if hasattr(m, 'main'): m.main(debug=False)
import pytest # noqa import os import sys import glob import imp def test_examples(): examples_pat = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../examples/*/*.py') # Filter out __init__.py examples = [f for f in glob.glob(examples_pat) if not any([x in f for x in ['__init__.py', 'molecular', 'custom_table_caching']])] for e in examples: example_dir = os.path.dirname(e) sys.path.insert(0, example_dir) (module_name, _) = os.path.splitext(os.path.basename(e)) (module_file, module_path, desc) = \ imp.find_module(module_name, [example_dir]) m = imp.load_module(module_name, module_file, module_path, desc) if hasattr(m, 'main'): m.main(debug=False)
Fix Theme To Make Sure Its An Object
import Form from "./components/form.js" import Input from "./components/input.js" import Submit from "./components/submit.js" import FormErrorList from "./components/form_error_list.js" import Fieldset from "./components/fieldset.js" import FieldsetText from "./components/fieldset_text.js" import ValueLinkedSelect from "./components/value_linked_select.js" import util from "./util.js" import typeMapping from "./type_mapping.js" import * as factories from "./factories.js" const HigherOrderComponents = { Boolean: require("./higher_order_components/boolean.js"), Focusable: require("./higher_order_components/focusable.js"), } // Setter and getter for the Frig default theme function defaultTheme(theme) { if (theme === null) return Form.defaultProps.theme if (typeof theme !== "object") throw "Invalid theme. Expected an object" Form.originalClass.defaultProps.theme = theme Input.originalClass.defaultProps.theme = theme } export default { defaultTheme, Form, Input, Submit, FormErrorList, Fieldset, FieldsetText, ValueLinkedSelect, HigherOrderComponents, util, typeMapping, factories, }
import Form from "./components/form.js" import Input from "./components/input.js" import Submit from "./components/submit.js" import FormErrorList from "./components/form_error_list.js" import Fieldset from "./components/fieldset.js" import FieldsetText from "./components/fieldset_text.js" import ValueLinkedSelect from "./components/value_linked_select.js" import util from "./util.js" import typeMapping from "./type_mapping.js" import * as factories from "./factories.js" const HigherOrderComponents = { Boolean: require("./higher_order_components/boolean.js"), Focusable: require("./higher_order_components/focusable.js"), } // Setter and getter for the Frig default theme function defaultTheme(theme) { if (theme == null) return Form.defaultProps.theme if (theme.component == null) throw "Invalid theme. Expected an object" Form.originalClass.defaultProps.theme = theme Input.originalClass.defaultProps.theme = theme } export default { defaultTheme, Form, Input, Submit, FormErrorList, Fieldset, FieldsetText, ValueLinkedSelect, HigherOrderComponents, util, typeMapping, factories, }
Fix wrong test naming for docs
import { expect } from 'chai' import AtomicString from '../../src/atomic/string' /** @test {AtomicString} */ describe('AtomicString', () => { const bitArrayHello = [104, 97, 108, 108, 111, 0, 0, 0] let atomic before(() => { atomic = new AtomicString('hallo') }) /** @test {AtomicString#unpack} */ describe('unpack', () => { let returnValue before(() => { const data = new Uint8Array(bitArrayHello) const dataView = new DataView(data.buffer) returnValue = atomic.unpack(dataView, 0) }) it('returns a number', () => { expect(returnValue).to.be.a('number') }) it('sets the offset to a multiple of 4', () => { expect(atomic.offset % 4).to.equal(0) }) it('sets the value to a human readable string', () => { expect(atomic.value).to.equal('hallo') }) }) /** @test {AtomicString#pack} */ describe('pack', () => { it('returns correct bits', () => { expect(JSON.stringify(atomic.pack())).to.equal( JSON.stringify(new Int8Array(bitArrayHello)) ) }) }) })
import { expect } from 'chai' import AtomicString from '../../src/atomic/string' /** @test {AtomicString} */ describe('AtomicString', () => { const bitArrayHello = [104, 97, 108, 108, 111, 0, 0, 0] let atomic before(() => { atomic = new AtomicString('hallo') }) /** @test {AtomicString#pack} */ describe('unpack', () => { let returnValue before(() => { const data = new Uint8Array(bitArrayHello) const dataView = new DataView(data.buffer) returnValue = atomic.unpack(dataView, 0) }) it('returns a number', () => { expect(returnValue).to.be.a('number') }) it('sets the offset to a multiple of 4', () => { expect(atomic.offset % 4).to.equal(0) }) it('sets the value to a human readable string', () => { expect(atomic.value).to.equal('hallo') }) }) /** @test {AtomicString#unpack} */ describe('pack', () => { it('returns correct bits', () => { expect(JSON.stringify(atomic.pack())).to.equal( JSON.stringify(new Int8Array(bitArrayHello)) ) }) }) })
Handle path separator differences in AntLoader DAT-4036
package liquibase.integration.ant; import liquibase.resource.FileSystemResourceAccessor; import liquibase.util.StringUtil; import org.apache.tools.ant.AntClassLoader; import java.io.File; public class AntResourceAccessor extends FileSystemResourceAccessor { public AntResourceAccessor(AntClassLoader classLoader, String changeLogDirectory) { if (changeLogDirectory != null) { changeLogDirectory = changeLogDirectory.replace("\\", "/"); } if (changeLogDirectory == null) { this.addRootPath(new File("").getAbsoluteFile().toPath()); this.addRootPath(new File("/").getAbsoluteFile().toPath()); } else { this.addRootPath(new File(changeLogDirectory).getAbsoluteFile().toPath()); } final String classpath = StringUtil.trimToNull(classLoader.getClasspath()); if (classpath != null) { for (String path : classpath.split(System.getProperty("path.separator"))) { this.addRootPath(new File(path).toPath()); } } } }
package liquibase.integration.ant; import liquibase.resource.FileSystemResourceAccessor; import liquibase.util.StringUtil; import org.apache.tools.ant.AntClassLoader; import java.io.File; public class AntResourceAccessor extends FileSystemResourceAccessor { public AntResourceAccessor(AntClassLoader classLoader, String changeLogDirectory) { if (changeLogDirectory == null) { this.addRootPath(new File(".").getAbsoluteFile().toPath()); } else { this.addRootPath(new File(changeLogDirectory).getAbsoluteFile().toPath()); } final String classpath = StringUtil.trimToNull(classLoader.getClasspath()); if (classpath != null) { for (String path : classpath.split(System.getProperty("path.separator"))) { this.addRootPath(new File(path).toPath()); } } } }
Revert accidental gums test change from previous commit. git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@17355 4e558342-562e-0410-864c-e07659590f8c
import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums-service') host_dn, _ = core.certificate_info(core.config['certs.hostcert']) pwd_entry = pwd.getpwnam(core.options.username) cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) command = ('gums', 'mapUser', '--serv', host_dn, user_dn) core.check_system(command, 'Map GUMS user')
import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums-service') host_dn, _ = core.certificate_info(core.config['certs.hostcert']) pwd_entry = pwd.getpwnam(core.options.username) cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) command = ('gums-host', 'mapUser', user_dn) core.check_system(command, 'Map GUMS user')
Fix AMD / UMD problems.
(function(root, factory) { if (typeof define === 'function' && define.amd) { define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) { Backbone.PageableCollection = PageableCollection; return (root.Hal = factory(root, Backbone, _)); }); } else if (typeof exports !== 'undefined') { var Backbone = require('backbone'); var _ = require('underscore'); Backbone.PageableCollection = require('backbone.paginator'); module.exports = factory(root, Backbone, _); } else { root.Hal = factory(root, root.Backbone, root._); } }(this, function(root, Backbone, _) { 'use strict'; /** * @namespace Hal */ var Hal = {}; // @include link.js // @include model.js // @include collection.js return Hal; }));
(function(root, factory) { if (typeof define === 'function' && define.amd) { define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) { return (root.Hal = factory(root, Backbone, _, PageableCollection)); }); } else if (typeof exports !== 'undefined') { var Backbone = require('backbone'); var _ = require('underscore'); var PageableCollection = require('backbone.paginator'); module.exports = factory(root, Backbone, _, PageableCollection); } else { root.Hal = factory(root, root.Backbone, root._, root.PageableCollection); } }(this, function(root) { 'use strict'; /** * @namespace Hal */ var Hal = {}; // @include link.js // @include model.js // @include collection.js return Hal; }));
Add CBO column to cnes professional
from sqlalchemy import Column, Integer, String, func from app import db class CnesProfessional(db.Model): __tablename__ = 'cnes_professional' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) cbo = Column(String(2), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', 'cbo', ] @classmethod def aggregate(cls, value): return { 'professionals': func.count(cls.cnes) }[value] @classmethod def values(cls): return ['professionals']
from sqlalchemy import Column, Integer, String, func from app import db class CnesProfessional(db.Model): __tablename__ = 'cnes_professional' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Column(String(5), primary_key=True) state = Column(String(2), primary_key=True) municipality = Column(String(7), primary_key=True) cnes = Column(String(7), primary_key=True) @classmethod def dimensions(cls): return [ 'year', 'region', 'mesoregion', 'microregion', 'state', 'municipality', ] @classmethod def aggregate(cls, value): return { 'professionals': func.count(cls.cnes) }[value] @classmethod def values(cls): return ['professionals']
Use new resolver in LexicalID resolution
from thinglang.utils.type_descriptors import ValueType from thinglang.lexer.symbols import LexicalSymbol class LexicalQuote(LexicalSymbol): # " EMITTABLE = False @classmethod def next_operator_set(cls, current, original): if current is original: return {'"': LexicalQuote} return original class LexicalParenthesesOpen(LexicalSymbol): pass # ( class LexicalParenthesesClose(LexicalSymbol): pass # ) class LexicalBracketOpen(LexicalSymbol): pass # [ class LexicalBracketClose(LexicalSymbol): pass # ] class LexicalSeparator(LexicalSymbol): pass # , class LexicalIndent(LexicalSymbol): pass # <TAB> class LexicalAccess(LexicalSymbol): pass # a.b class LexicalInlineComment(LexicalSymbol): pass class LexicalAssignment(LexicalSymbol): pass class LexicalIdentifier(LexicalSymbol, ValueType): def __init__(self, value): super(LexicalIdentifier, self).__init__(value) self.value = value def describe(self): return self.value def evaluate(self, resolver): return resolver.resolve(self) def __hash__(self): return hash(self.value) def __eq__(self, other): return type(other) == type(self) and self.value == other.value LexicalIdentifier.SELF = LexicalIdentifier("self")
from thinglang.utils.type_descriptors import ValueType from thinglang.lexer.symbols import LexicalSymbol class LexicalQuote(LexicalSymbol): # " EMITTABLE = False @classmethod def next_operator_set(cls, current, original): if current is original: return {'"': LexicalQuote} return original class LexicalParenthesesOpen(LexicalSymbol): pass # ( class LexicalParenthesesClose(LexicalSymbol): pass # ) class LexicalBracketOpen(LexicalSymbol): pass # [ class LexicalBracketClose(LexicalSymbol): pass # ] class LexicalSeparator(LexicalSymbol): pass # , class LexicalIndent(LexicalSymbol): pass # <TAB> class LexicalAccess(LexicalSymbol): pass # a.b class LexicalInlineComment(LexicalSymbol): pass class LexicalAssignment(LexicalSymbol): pass class LexicalIdentifier(LexicalSymbol, ValueType): def __init__(self, value): super(LexicalIdentifier, self).__init__(value) self.value = value def describe(self): return self.value def evaluate(self, stack): return stack[self.value] def __hash__(self): return hash(self.value) def __eq__(self, other): return type(other) == type(self) and self.value == other.value LexicalIdentifier.SELF = LexicalIdentifier("self")
[terraform-conversions] Add json tags to CAI asset. Signed-off-by: Modular Magician <86ce7da8ad74b1c583667a2bebd347455fa06219@google.com>
package google // Asset is the CAI representation of a resource. type Asset struct { // The name, in a peculiar format: `\\<api>.googleapis.com/<self_link>` Name string `json:"name"` // The type name in `google.<api>.<resourcename>` format. Type string `json:"asset_type"` Resource *AssetResource `json:"resource,omitempty"` IAMPolicy *IAMPolicy `json:"iam_policy,omitempty"` } // AssetResource is the Asset's Resource field. type AssetResource struct { // Api version Version string `json:"version"` // URI including scheme for the discovery doc - assembled from // product name and version. DiscoveryDocumentURI string `json:"discovery_document_uri"` // Resource name. DiscoveryName string `json:"discovery_name"` // Actual resource state as per Terraform. Note that this does // not necessarily correspond perfectly with the CAI representation // as there are occasional deviations between CAI and API responses. // This returns the API response values instead. Data map[string]interface{} `json:"data,omitempty"` } type IAMPolicy struct { Bindings []IAMBinding `json:"bindings"` } type IAMBinding struct { Role string `json:"role"` Members []string `json:"members"` }
package google // Asset is the CAI representation of a resource. type Asset struct { // The name, in a peculiar format: `\\<api>.googleapis.com/<self_link>` Name string // The type name in `google.<api>.<resourcename>` format. Type string Resource *AssetResource IAMPolicy *IAMPolicy } // AssetResource is the Asset's Resource field. type AssetResource struct { // Api version Version string // URI including scheme for the discovery doc - assembled from // product name and version. DiscoveryDocumentURI string // Resource name. DiscoveryName string // Actual resource state as per Terraform. Note that this does // not necessarily correspond perfectly with the CAI representation // as there are occasional deviations between CAI and API responses. // This returns the API response values instead. Data map[string]interface{} } type IAMPolicy struct { Bindings []IAMBinding } type IAMBinding struct { Role string Members []string }